blob: d0651e6bda702650a05069f7d742315a5883ba70 [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"
Greg Clayton100eb932014-07-02 21:10:39 +000037#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000038#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000039#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000040#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000041#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000042#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000043#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000045#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000046#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000047#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000048#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000050#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000051#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000052#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000053#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000054#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000055#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000056#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000058#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000059#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000060#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Target/Target.h"
62#include "lldb/Target/TargetList.h"
63#include "lldb/Target/Thread.h"
64#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000065#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000066#include "lldb/Target/UnixSignals.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000067#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000068#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000069#include "lldb/Utility/SelectHelper.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070
71using namespace lldb;
72using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000073using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074
Kate Stoneb9c1b512016-09-06 20:57:50 +000075// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000076// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000077#define ENABLE_MEMORY_CACHING
78
79#ifdef ENABLE_MEMORY_CACHING
80#define DISABLE_MEM_CACHE_DEFAULT false
81#else
82#define DISABLE_MEM_CACHE_DEFAULT true
83#endif
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000086public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 ProcessOptionValueProperties(const ConstString &name)
88 : OptionValueProperties(name) {}
89
90 // This constructor is used when creating ProcessOptionValueProperties when it
91 // is part of a new lldb_private::Process instance. It will copy all current
92 // global property values as needed
93 ProcessOptionValueProperties(ProcessProperties *global_properties)
94 : OptionValueProperties(*global_properties->GetValueProperties()) {}
95
96 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
97 bool will_modify,
98 uint32_t idx) const override {
99 // When getting the value for a key from the process options, we will always
100 // try and grab the setting from the current process if there is one. Else
101 // we just
102 // use the one from this instance.
103 if (exe_ctx) {
104 Process *process = exe_ctx->GetProcessPtr();
105 if (process) {
106 ProcessOptionValueProperties *instance_properties =
107 static_cast<ProcessOptionValueProperties *>(
108 process->GetValueProperties().get());
109 if (this != instance_properties)
110 return instance_properties->ProtectedGetPropertyAtIndex(idx);
111 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000112 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 return ProtectedGetPropertyAtIndex(idx);
114 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000115};
116
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117static PropertyDefinition g_properties[] = {
118 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
119 DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr,
120 "Disable reading and caching of memory in fixed-size units."},
121 {"extra-startup-command", OptionValue::eTypeArray, false,
122 OptionValue::eTypeString, nullptr, nullptr,
123 "A list containing extra commands understood by the particular process "
124 "plugin used. "
125 "For instance, to turn on debugserver logging set this to "
126 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
127 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
128 nullptr, nullptr,
129 "If true, breakpoints will be ignored during expression evaluation."},
130 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
131 nullptr, nullptr, "If true, errors in expression evaluation will unwind "
132 "the stack back to the state before the call."},
133 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
134 nullptr, "A path to a python OS plug-in module file that contains a "
135 "OperatingSystemPlugIn class."},
136 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
137 nullptr, nullptr,
138 "If true, stop when a shared library is loaded or unloaded."},
139 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
140 nullptr, "If true, detach will attempt to keep the process stopped."},
141 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
142 nullptr, "The memory cache line size"},
143 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
144 nullptr, "If true, warn when stopped in code that is optimized where "
145 "stepping and variable availability may not behave as expected."},
146 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000147
148enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 ePropertyDisableMemCache,
150 ePropertyExtraStartCommand,
151 ePropertyIgnoreBreakpointsInExpressions,
152 ePropertyUnwindOnErrorInExpressions,
153 ePropertyPythonOSPluginPath,
154 ePropertyStopOnSharedLibraryEvents,
155 ePropertyDetachKeepsStopped,
156 ePropertyMemCacheLineSize,
157 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000158};
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160ProcessProperties::ProcessProperties(lldb_private::Process *process)
161 : Properties(),
162 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000163{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 if (process == nullptr) {
165 // Global process properties, set them up one time
166 m_collection_sp.reset(
167 new ProcessOptionValueProperties(ConstString("process")));
168 m_collection_sp->Initialize(g_properties);
169 m_collection_sp->AppendProperty(
170 ConstString("thread"), ConstString("Settings specific to threads."),
171 true, Thread::GetGlobalProperties()->GetValueProperties());
172 } else {
173 m_collection_sp.reset(
174 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
175 m_collection_sp->SetValueChangedCallback(
176 ePropertyPythonOSPluginPath,
177 ProcessProperties::OptionValueChangedCallback, this);
178 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000179}
180
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000181ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183void ProcessProperties::OptionValueChangedCallback(void *baton,
184 OptionValue *option_value) {
185 ProcessProperties *properties = (ProcessProperties *)baton;
186 if (properties->m_process)
187 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000188}
189
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190bool ProcessProperties::GetDisableMemoryCache() const {
191 const uint32_t idx = ePropertyDisableMemCache;
192 return m_collection_sp->GetPropertyAtIndexAsBoolean(
193 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000194}
195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
197 const uint32_t idx = ePropertyMemCacheLineSize;
198 return m_collection_sp->GetPropertyAtIndexAsUInt64(
199 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202Args ProcessProperties::GetExtraStartupCommands() const {
203 Args args;
204 const uint32_t idx = ePropertyExtraStartCommand;
205 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
206 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000207}
208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209void ProcessProperties::SetExtraStartupCommands(const Args &args) {
210 const uint32_t idx = ePropertyExtraStartCommand;
211 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000212}
213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214FileSpec ProcessProperties::GetPythonOSPluginPath() const {
215 const uint32_t idx = ePropertyPythonOSPluginPath;
216 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000217}
218
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
220 const uint32_t idx = ePropertyPythonOSPluginPath;
221 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000222}
223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
225 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
226 return m_collection_sp->GetPropertyAtIndexAsBoolean(
227 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000228}
229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
231 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
232 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000233}
234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
236 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
237 return m_collection_sp->GetPropertyAtIndexAsBoolean(
238 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000239}
240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
242 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
243 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000244}
245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
247 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
248 return m_collection_sp->GetPropertyAtIndexAsBoolean(
249 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000250}
251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
253 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
254 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
255}
256
257bool ProcessProperties::GetDetachKeepsStopped() const {
258 const uint32_t idx = ePropertyDetachKeepsStopped;
259 return m_collection_sp->GetPropertyAtIndexAsBoolean(
260 nullptr, idx, g_properties[idx].default_uint_value != 0);
261}
262
263void ProcessProperties::SetDetachKeepsStopped(bool stop) {
264 const uint32_t idx = ePropertyDetachKeepsStopped;
265 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
266}
267
268bool ProcessProperties::GetWarningsOptimization() const {
269 const uint32_t idx = ePropertyWarningOptimization;
270 return m_collection_sp->GetPropertyAtIndexAsBoolean(
271 nullptr, idx, g_properties[idx].default_uint_value != 0);
272}
273
274void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
275 const char *cstr;
276 if (m_pid != LLDB_INVALID_PROCESS_ID)
277 s.Printf(" pid = %" PRIu64 "\n", m_pid);
278
279 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
280 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
281
282 if (m_executable) {
283 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
284 s.PutCString(" file = ");
285 m_executable.Dump(&s);
286 s.EOL();
287 }
288 const uint32_t argc = m_arguments.GetArgumentCount();
289 if (argc > 0) {
290 for (uint32_t i = 0; i < argc; i++) {
291 const char *arg = m_arguments.GetArgumentAtIndex(i);
292 if (i < 10)
293 s.Printf(" arg[%u] = %s\n", i, arg);
294 else
295 s.Printf("arg[%u] = %s\n", i, arg);
296 }
297 }
298
299 const uint32_t envc = m_environment.GetArgumentCount();
300 if (envc > 0) {
301 for (uint32_t i = 0; i < envc; i++) {
302 const char *env = m_environment.GetArgumentAtIndex(i);
303 if (i < 10)
304 s.Printf(" env[%u] = %s\n", i, env);
305 else
306 s.Printf("env[%u] = %s\n", i, env);
307 }
308 }
309
310 if (m_arch.IsValid()) {
311 s.Printf(" arch = ");
312 m_arch.DumpTriple(s);
313 s.EOL();
314 }
315
316 if (m_uid != UINT32_MAX) {
317 cstr = platform->GetUserName(m_uid);
318 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
319 }
320 if (m_gid != UINT32_MAX) {
321 cstr = platform->GetGroupName(m_gid);
322 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
323 }
324 if (m_euid != UINT32_MAX) {
325 cstr = platform->GetUserName(m_euid);
326 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
327 }
328 if (m_egid != UINT32_MAX) {
329 cstr = platform->GetGroupName(m_egid);
330 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
331 }
332}
333
334void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
335 bool show_args, bool verbose) {
336 const char *label;
337 if (show_args || verbose)
338 label = "ARGUMENTS";
339 else
340 label = "NAME";
341
342 if (verbose) {
343 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
344 " %s\n",
345 label);
346 s.PutCString("====== ====== ========== ========== ========== ========== "
347 "======================== ============================\n");
348 } else {
349 s.Printf("PID PARENT USER TRIPLE %s\n", label);
350 s.PutCString("====== ====== ========== ======================== "
351 "============================\n");
352 }
353}
354
355void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
356 bool show_args, bool verbose) const {
357 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000358 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000362 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 m_arch.DumpTriple(arch_strm);
364
365 if (verbose) {
366 cstr = platform->GetUserName(m_uid);
367 if (cstr &&
368 cstr[0]) // Watch for empty string that indicates lookup failed
369 s.Printf("%-10s ", cstr);
370 else
371 s.Printf("%-10u ", m_uid);
372
373 cstr = platform->GetGroupName(m_gid);
374 if (cstr &&
375 cstr[0]) // Watch for empty string that indicates lookup failed
376 s.Printf("%-10s ", cstr);
377 else
378 s.Printf("%-10u ", m_gid);
379
380 cstr = platform->GetUserName(m_euid);
381 if (cstr &&
382 cstr[0]) // Watch for empty string that indicates lookup failed
383 s.Printf("%-10s ", cstr);
384 else
385 s.Printf("%-10u ", m_euid);
386
387 cstr = platform->GetGroupName(m_egid);
388 if (cstr &&
389 cstr[0]) // Watch for empty string that indicates lookup failed
390 s.Printf("%-10s ", cstr);
391 else
392 s.Printf("%-10u ", m_egid);
393
Zachary Turnerc1564272016-11-16 21:15:24 +0000394 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 } else {
396 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000397 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000398 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 if (verbose || show_args) {
401 const uint32_t argc = m_arguments.GetArgumentCount();
402 if (argc > 0) {
403 for (uint32_t i = 0; i < argc; i++) {
404 if (i > 0)
405 s.PutChar(' ');
406 s.PutCString(m_arguments.GetArgumentAtIndex(i));
407 }
408 }
409 } else {
410 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000411 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412
413 s.EOL();
414 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000415}
416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417Error ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000418 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 ExecutionContext *execution_context) {
420 Error error;
421 const int short_option = m_getopt_table[option_idx].val;
422
423 switch (short_option) {
424 case 's': // Stop at program entry point
425 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
426 break;
427
428 case 'i': // STDIN for read only
429 {
430 FileAction action;
431 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
432 launch_info.AppendFileAction(action);
433 break;
434 }
435
436 case 'o': // Open STDOUT for write only
437 {
438 FileAction action;
439 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
440 launch_info.AppendFileAction(action);
441 break;
442 }
443
444 case 'e': // STDERR for write only
445 {
446 FileAction action;
447 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
448 launch_info.AppendFileAction(action);
449 break;
450 }
451
452 case 'p': // Process plug-in name
453 launch_info.SetProcessPluginName(option_arg);
454 break;
455
456 case 'n': // Disable STDIO
457 {
458 FileAction action;
459 const FileSpec dev_null{FileSystem::DEV_NULL, false};
460 if (action.Open(STDIN_FILENO, dev_null, true, false))
461 launch_info.AppendFileAction(action);
462 if (action.Open(STDOUT_FILENO, dev_null, false, true))
463 launch_info.AppendFileAction(action);
464 if (action.Open(STDERR_FILENO, dev_null, false, true))
465 launch_info.AppendFileAction(action);
466 break;
467 }
468
469 case 'w':
470 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
471 break;
472
473 case 't': // Open process in new terminal window
474 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
475 break;
476
477 case 'a': {
478 TargetSP target_sp =
479 execution_context ? execution_context->GetTargetSP() : TargetSP();
480 PlatformSP platform_sp =
481 target_sp ? target_sp->GetPlatform() : PlatformSP();
482 if (!launch_info.GetArchitecture().SetTriple(option_arg, platform_sp.get()))
483 launch_info.GetArchitecture().SetTriple(option_arg);
484 } break;
485
486 case 'A': // Disable ASLR.
487 {
488 bool success;
489 const bool disable_aslr_arg =
Zachary Turnerfe114832016-11-12 16:56:47 +0000490 Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 if (success)
492 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000493 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 error.SetErrorStringWithFormat(
495 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000496 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 break;
498 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 case 'X': // shell expand args.
501 {
502 bool success;
Zachary Turnerfe114832016-11-12 16:56:47 +0000503 const bool expand_args = Args::StringToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 if (success)
505 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000506 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 error.SetErrorStringWithFormat(
508 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000509 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 break;
511 }
512
513 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000514 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 launch_info.SetShell(FileSpec(option_arg, false));
516 else
517 launch_info.SetShell(HostInfo::GetDefaultShell());
518 break;
519
520 case 'v':
Zachary Turnerfe114832016-11-12 16:56:47 +0000521 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 break;
523
524 default:
525 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
526 short_option);
527 break;
528 }
529 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000530}
531
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000532static OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
534 nullptr, nullptr, 0, eArgTypeNone,
535 "Stop at the entry point of the program when launching a process."},
536 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
537 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
538 "Set whether to disable address space layout randomization when launching "
539 "a process."},
540 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
541 nullptr, nullptr, 0, eArgTypePlugin,
542 "Name of the process plugin you want to use."},
543 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
544 OptionParser::eRequiredArgument, nullptr, nullptr, 0,
545 eArgTypeDirectoryName,
546 "Set the current working directory to <path> when running the inferior."},
547 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
548 nullptr, nullptr, 0, eArgTypeArchitecture,
549 "Set the architecture for the process to launch when ambiguous."},
550 {LLDB_OPT_SET_ALL, false, "environment", 'v',
551 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone,
552 "Specify an environment variable name/value string (--environment "
553 "NAME=VALUE). Can be specified multiple times for subsequent environment "
554 "entries."},
555 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
556 OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename,
557 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
560 nullptr, nullptr, 0, eArgTypeFilename,
561 "Redirect stdin for the process to <filename>."},
562 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
563 nullptr, nullptr, 0, eArgTypeFilename,
564 "Redirect stdout for the process to <filename>."},
565 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
566 nullptr, nullptr, 0, eArgTypeFilename,
567 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
570 nullptr, 0, eArgTypeNone,
571 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
574 nullptr, 0, eArgTypeNone,
575 "Do not set up for terminal I/O to go to running process."},
576 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
577 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean,
578 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000579};
580
581llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000582 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000583}
Greg Clayton32e0a752011-03-30 18:16:51 +0000584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000586 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000587 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 const char *match_name = m_match_info.GetName();
589 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000590 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591
592 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000593}
594
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595bool ProcessInstanceInfoMatch::Matches(
596 const ProcessInstanceInfo &proc_info) const {
597 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599
600 if (m_match_info.ProcessIDIsValid() &&
601 m_match_info.GetProcessID() != proc_info.GetProcessID())
602 return false;
603
604 if (m_match_info.ParentProcessIDIsValid() &&
605 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
606 return false;
607
608 if (m_match_info.UserIDIsValid() &&
609 m_match_info.GetUserID() != proc_info.GetUserID())
610 return false;
611
612 if (m_match_info.GroupIDIsValid() &&
613 m_match_info.GetGroupID() != proc_info.GetGroupID())
614 return false;
615
616 if (m_match_info.EffectiveUserIDIsValid() &&
617 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
618 return false;
619
620 if (m_match_info.EffectiveGroupIDIsValid() &&
621 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
622 return false;
623
624 if (m_match_info.GetArchitecture().IsValid() &&
625 !m_match_info.GetArchitecture().IsCompatibleMatch(
626 proc_info.GetArchitecture()))
627 return false;
628 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629}
630
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000632 if (m_name_match_type != NameMatch::Ignore)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 return false;
634
635 if (m_match_info.ProcessIDIsValid())
636 return false;
637
638 if (m_match_info.ParentProcessIDIsValid())
639 return false;
640
641 if (m_match_info.UserIDIsValid())
642 return false;
643
644 if (m_match_info.GroupIDIsValid())
645 return false;
646
647 if (m_match_info.EffectiveUserIDIsValid())
648 return false;
649
650 if (m_match_info.EffectiveGroupIDIsValid())
651 return false;
652
653 if (m_match_info.GetArchitecture().IsValid())
654 return false;
655
656 if (m_match_all_users)
657 return false;
658
659 return true;
660}
661
662void ProcessInstanceInfoMatch::Clear() {
663 m_match_info.Clear();
Pavel Labathc4a33952017-02-20 11:35:33 +0000664 m_name_match_type = NameMatch::Ignore;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 m_match_all_users = false;
666}
667
Zachary Turner31659452016-11-17 21:15:14 +0000668ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
669 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 ListenerSP listener_sp,
671 const FileSpec *crash_file_path) {
672 static uint32_t g_process_unique_id = 0;
673
674 ProcessSP process_sp;
675 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000676 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 ConstString const_plugin_name(plugin_name);
678 create_callback =
679 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
680 if (create_callback) {
681 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
682 if (process_sp) {
683 if (process_sp->CanDebug(target_sp, true)) {
684 process_sp->m_process_unique_id = ++g_process_unique_id;
685 } else
686 process_sp.reset();
687 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 } else {
690 for (uint32_t idx = 0;
691 (create_callback =
692 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
693 ++idx) {
694 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
695 if (process_sp) {
696 if (process_sp->CanDebug(target_sp, false)) {
697 process_sp->m_process_unique_id = ++g_process_unique_id;
698 break;
699 } else
700 process_sp.reset();
701 }
702 }
703 }
704 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705}
706
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707ConstString &Process::GetStaticBroadcasterClass() {
708 static ConstString class_name("lldb.process");
709 return class_name;
710}
711
712Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
713 : Process(target_sp, listener_sp,
714 UnixSignals::Create(HostInfo::GetArchitecture())) {
715 // This constructor just delegates to the full Process constructor,
716 // defaulting to using the Host's UnixSignals.
717}
718
719Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
720 const UnixSignalsSP &unix_signals_sp)
721 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
722 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
723 Process::GetStaticBroadcasterClass().AsCString()),
724 m_target_sp(target_sp), m_public_state(eStateUnloaded),
725 m_private_state(eStateUnloaded),
726 m_private_state_broadcaster(nullptr,
727 "lldb.process.internal_state_broadcaster"),
728 m_private_state_control_broadcaster(
729 nullptr, "lldb.process.internal_state_control_broadcaster"),
730 m_private_state_listener_sp(
731 Listener::MakeListener("lldb.process.internal_state_listener")),
732 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
733 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
734 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
735 m_thread_list(this), m_extended_thread_list(this),
736 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
737 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
738 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
739 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
740 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
741 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
742 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
743 m_memory_cache(*this), m_allocated_memory_cache(*this),
744 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
745 m_private_run_lock(), m_stop_info_override_callback(nullptr),
746 m_finalizing(false), m_finalize_called(false),
747 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
748 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
749 m_can_interpret_function_calls(false), m_warnings_issued(),
750 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
751 CheckInWithManager();
752
753 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
754 if (log)
755 log->Printf("%p Process::Process()", static_cast<void *>(this));
756
757 if (!m_unix_signals_sp)
758 m_unix_signals_sp = std::make_shared<UnixSignals>();
759
760 SetEventName(eBroadcastBitStateChanged, "state-changed");
761 SetEventName(eBroadcastBitInterrupt, "interrupt");
762 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
763 SetEventName(eBroadcastBitSTDERR, "stderr-available");
764 SetEventName(eBroadcastBitProfileData, "profile-data-available");
765 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
766
767 m_private_state_control_broadcaster.SetEventName(
768 eBroadcastInternalStateControlStop, "control-stop");
769 m_private_state_control_broadcaster.SetEventName(
770 eBroadcastInternalStateControlPause, "control-pause");
771 m_private_state_control_broadcaster.SetEventName(
772 eBroadcastInternalStateControlResume, "control-resume");
773
774 m_listener_sp->StartListeningForEvents(
775 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
776 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
777 eBroadcastBitProfileData | eBroadcastBitStructuredData);
778
779 m_private_state_listener_sp->StartListeningForEvents(
780 &m_private_state_broadcaster,
781 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
782
783 m_private_state_listener_sp->StartListeningForEvents(
784 &m_private_state_control_broadcaster,
785 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
786 eBroadcastInternalStateControlResume);
787 // We need something valid here, even if just the default UnixSignalsSP.
788 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
789
790 // Allow the platform to override the default cache line size
791 OptionValueSP value_sp =
792 m_collection_sp
793 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
794 ->GetValue();
795 uint32_t platform_cache_line_size =
796 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
797 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
798 value_sp->SetUInt64Value(platform_cache_line_size);
799}
800
801Process::~Process() {
802 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
803 if (log)
804 log->Printf("%p Process::~Process()", static_cast<void *>(this));
805 StopPrivateStateThread();
806
807 // ThreadList::Clear() will try to acquire this process's mutex, so
808 // explicitly clear the thread list here to ensure that the mutex
809 // is not destroyed before the thread list.
810 m_thread_list.Clear();
811}
812
813const ProcessPropertiesSP &Process::GetGlobalProperties() {
814 // NOTE: intentional leak so we don't crash if global destructor chain gets
815 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000816 static ProcessPropertiesSP *g_settings_sp_ptr =
817 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 return *g_settings_sp_ptr;
819}
820
821void Process::Finalize() {
822 m_finalizing = true;
823
824 // Destroy this process if needed
825 switch (GetPrivateState()) {
826 case eStateConnected:
827 case eStateAttaching:
828 case eStateLaunching:
829 case eStateStopped:
830 case eStateRunning:
831 case eStateStepping:
832 case eStateCrashed:
833 case eStateSuspended:
834 Destroy(false);
835 break;
836
837 case eStateInvalid:
838 case eStateUnloaded:
839 case eStateDetached:
840 case eStateExited:
841 break;
842 }
843
844 // Clear our broadcaster before we proceed with destroying
845 Broadcaster::Clear();
846
847 // Do any cleanup needed prior to being destructed... Subclasses
848 // that override this method should call this superclass method as well.
849
850 // We need to destroy the loader before the derived Process class gets
851 // destroyed
852 // since it is very likely that undoing the loader will require access to the
853 // real process.
854 m_dynamic_checkers_ap.reset();
855 m_abi_sp.reset();
856 m_os_ap.reset();
857 m_system_runtime_ap.reset();
858 m_dyld_ap.reset();
859 m_jit_loaders_ap.reset();
860 m_thread_list_real.Destroy();
861 m_thread_list.Destroy();
862 m_extended_thread_list.Destroy();
863 m_queue_list.Clear();
864 m_queue_list_stop_id = 0;
865 std::vector<Notifications> empty_notifications;
866 m_notifications.swap(empty_notifications);
867 m_image_tokens.clear();
868 m_memory_cache.Clear();
869 m_allocated_memory_cache.Clear();
870 m_language_runtimes.clear();
871 m_instrumentation_runtimes.clear();
872 m_next_event_action_ap.reset();
873 m_stop_info_override_callback = nullptr;
874 // Clear the last natural stop ID since it has a strong
875 // reference to this process
876 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
877 //#ifdef LLDB_CONFIGURATION_DEBUG
878 // StreamFile s(stdout, false);
879 // EventSP event_sp;
880 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
881 // {
882 // event_sp->Dump (&s);
883 // s.EOL();
884 // }
885 //#endif
886 // We have to be very careful here as the m_private_state_listener might
887 // contain events that have ProcessSP values in them which can keep this
888 // process around forever. These events need to be cleared out.
889 m_private_state_listener_sp->Clear();
890 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
891 m_public_run_lock.SetStopped();
892 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
893 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000894 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 m_finalize_called = true;
896}
897
898void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
899 m_notifications.push_back(callbacks);
900 if (callbacks.initialize != nullptr)
901 callbacks.initialize(callbacks.baton, this);
902}
903
904bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
905 std::vector<Notifications>::iterator pos, end = m_notifications.end();
906 for (pos = m_notifications.begin(); pos != end; ++pos) {
907 if (pos->baton == callbacks.baton &&
908 pos->initialize == callbacks.initialize &&
909 pos->process_state_changed == callbacks.process_state_changed) {
910 m_notifications.erase(pos);
911 return true;
912 }
913 }
914 return false;
915}
916
917void Process::SynchronouslyNotifyStateChanged(StateType state) {
918 std::vector<Notifications>::iterator notification_pos,
919 notification_end = m_notifications.end();
920 for (notification_pos = m_notifications.begin();
921 notification_pos != notification_end; ++notification_pos) {
922 if (notification_pos->process_state_changed)
923 notification_pos->process_state_changed(notification_pos->baton, this,
924 state);
925 }
926}
927
928// FIXME: We need to do some work on events before the general Listener sees
929// them.
930// For instance if we are continuing from a breakpoint, we need to ensure that
931// we do
932// the little "insert real insn, step & stop" trick. But we can't do that when
933// the
934// event is delivered by the broadcaster - since that is done on the thread that
935// is
936// waiting for new events, so if we needed more than one event for our handling,
937// we would
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000938// stall. So instead we do it when we fetch the event off of the queue.
939//
940
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941StateType Process::GetNextEvent(EventSP &event_sp) {
942 StateType state = eStateInvalid;
943
Pavel Labathd35031e12016-11-30 10:41:42 +0000944 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
945 std::chrono::seconds(0)) &&
946 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
948
949 return state;
950}
951
952void Process::SyncIOHandler(uint32_t iohandler_id, uint64_t timeout_msec) {
953 // don't sync (potentially context switch) in case where there is no process
954 // IO
955 if (!m_process_input_reader)
956 return;
957
958 uint32_t new_iohandler_id = 0;
959 m_iohandler_sync.WaitForValueNotEqualTo(
960 iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
961
962 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
963 if (log)
964 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, "
965 "new value is %u",
966 __FUNCTION__, iohandler_id, new_iohandler_id);
967}
968
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000969StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
970 EventSP *event_sp_ptr, bool wait_always,
971 ListenerSP hijack_listener_sp,
972 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 // We can't just wait for a "stopped" event, because the stopped event may
974 // have restarted the target.
975 // We have to actually check each event, and in the case of a stopped event
976 // check the restarted flag
977 // on the event.
978 if (event_sp_ptr)
979 event_sp_ptr->reset();
980 StateType state = GetState();
981 // If we are exited or detached, we won't ever get back to any
982 // other valid state...
983 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000987 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000988
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 if (!wait_always && StateIsStoppedState(state, true) &&
990 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000991 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 log->Printf("Process::%s returning without waiting for events; process "
993 "private and public states are already 'stopped'.",
994 __FUNCTION__);
995 // We need to toggle the run lock as this won't get done in
996 // SetPublicState() if the process is hijacked.
997 if (hijack_listener_sp && use_run_lock)
998 m_public_run_lock.SetStopped();
999 return state;
1000 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 while (state != eStateInvalid) {
1003 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001004 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 if (event_sp_ptr && event_sp)
1006 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001007
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1009 Process::HandleProcessStateChangedEvent(event_sp, stream,
1010 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 switch (state) {
1013 case eStateCrashed:
1014 case eStateDetached:
1015 case eStateExited:
1016 case eStateUnloaded:
1017 // We need to toggle the run lock as this won't get done in
1018 // SetPublicState() if the process is hijacked.
1019 if (hijack_listener_sp && use_run_lock)
1020 m_public_run_lock.SetStopped();
1021 return state;
1022 case eStateStopped:
1023 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1024 continue;
1025 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001026 // We need to toggle the run lock as this won't get done in
1027 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001028 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 m_public_run_lock.SetStopped();
1030 return state;
1031 }
1032 default:
1033 continue;
1034 }
1035 }
1036 return state;
1037}
1038
1039bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1040 Stream *stream,
1041 bool &pop_process_io_handler) {
1042 const bool handle_pop = pop_process_io_handler;
1043
1044 pop_process_io_handler = false;
1045 ProcessSP process_sp =
1046 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1047
1048 if (!process_sp)
1049 return false;
1050
1051 StateType event_state =
1052 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1053 if (event_state == eStateInvalid)
1054 return false;
1055
1056 switch (event_state) {
1057 case eStateInvalid:
1058 case eStateUnloaded:
1059 case eStateAttaching:
1060 case eStateLaunching:
1061 case eStateStepping:
1062 case eStateDetached:
1063 if (stream)
1064 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1065 StateAsCString(event_state));
1066 if (event_state == eStateDetached)
1067 pop_process_io_handler = true;
1068 break;
1069
1070 case eStateConnected:
1071 case eStateRunning:
1072 // Don't be chatty when we run...
1073 break;
1074
1075 case eStateExited:
1076 if (stream)
1077 process_sp->GetStatus(*stream);
1078 pop_process_io_handler = true;
1079 break;
1080
1081 case eStateStopped:
1082 case eStateCrashed:
1083 case eStateSuspended:
1084 // Make sure the program hasn't been auto-restarted:
1085 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1086 if (stream) {
1087 size_t num_reasons =
1088 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1089 if (num_reasons > 0) {
1090 // FIXME: Do we want to report this, or would that just be annoyingly
1091 // chatty?
1092 if (num_reasons == 1) {
1093 const char *reason =
1094 Process::ProcessEventData::GetRestartedReasonAtIndex(
1095 event_sp.get(), 0);
1096 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1097 process_sp->GetID(),
1098 reason ? reason : "<UNKNOWN REASON>");
1099 } else {
1100 stream->Printf("Process %" PRIu64
1101 " stopped and restarted, reasons:\n",
1102 process_sp->GetID());
1103
1104 for (size_t i = 0; i < num_reasons; i++) {
1105 const char *reason =
1106 Process::ProcessEventData::GetRestartedReasonAtIndex(
1107 event_sp.get(), i);
1108 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1109 }
1110 }
1111 }
1112 }
1113 } else {
1114 StopInfoSP curr_thread_stop_info_sp;
1115 // Lock the thread list so it doesn't change on us, this is the scope for
1116 // the locker:
1117 {
1118 ThreadList &thread_list = process_sp->GetThreadList();
1119 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1120
1121 ThreadSP curr_thread(thread_list.GetSelectedThread());
1122 ThreadSP thread;
1123 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1124 if (curr_thread) {
1125 curr_thread_stop_reason = curr_thread->GetStopReason();
1126 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1127 }
1128 if (!curr_thread || !curr_thread->IsValid() ||
1129 curr_thread_stop_reason == eStopReasonInvalid ||
1130 curr_thread_stop_reason == eStopReasonNone) {
1131 // Prefer a thread that has just completed its plan over another
1132 // thread as current thread.
1133 ThreadSP plan_thread;
1134 ThreadSP other_thread;
1135
1136 const size_t num_threads = thread_list.GetSize();
1137 size_t i;
1138 for (i = 0; i < num_threads; ++i) {
1139 thread = thread_list.GetThreadAtIndex(i);
1140 StopReason thread_stop_reason = thread->GetStopReason();
1141 switch (thread_stop_reason) {
1142 case eStopReasonInvalid:
1143 case eStopReasonNone:
1144 break;
1145
1146 case eStopReasonSignal: {
1147 // Don't select a signal thread if we weren't going to stop at
1148 // that
1149 // signal. We have to have had another reason for stopping here,
1150 // and
1151 // the user doesn't want to see this thread.
1152 uint64_t signo = thread->GetStopInfo()->GetValue();
1153 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1154 if (!other_thread)
1155 other_thread = thread;
1156 }
1157 break;
1158 }
1159 case eStopReasonTrace:
1160 case eStopReasonBreakpoint:
1161 case eStopReasonWatchpoint:
1162 case eStopReasonException:
1163 case eStopReasonExec:
1164 case eStopReasonThreadExiting:
1165 case eStopReasonInstrumentation:
1166 if (!other_thread)
1167 other_thread = thread;
1168 break;
1169 case eStopReasonPlanComplete:
1170 if (!plan_thread)
1171 plan_thread = thread;
1172 break;
1173 }
1174 }
1175 if (plan_thread)
1176 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1177 else if (other_thread)
1178 thread_list.SetSelectedThreadByID(other_thread->GetID());
1179 else {
1180 if (curr_thread && curr_thread->IsValid())
1181 thread = curr_thread;
1182 else
1183 thread = thread_list.GetThreadAtIndex(0);
1184
1185 if (thread)
1186 thread_list.SetSelectedThreadByID(thread->GetID());
1187 }
1188 }
1189 }
1190 // Drop the ThreadList mutex by here, since GetThreadStatus below might
1191 // have to run code,
1192 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the
1193 // process is going to
1194 // have a hard time restarting the process.
1195 if (stream) {
1196 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1197 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1198 &process_sp->GetTarget()) {
1199 const bool only_threads_with_stop_reason = true;
1200 const uint32_t start_frame = 0;
1201 const uint32_t num_frames = 1;
1202 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001203 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 process_sp->GetStatus(*stream);
1205 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1206 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001207 num_frames_with_source,
1208 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 if (curr_thread_stop_info_sp) {
1210 lldb::addr_t crashing_address;
1211 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1212 curr_thread_stop_info_sp, &crashing_address);
1213 if (valobj_sp) {
1214 const bool qualify_cxx_base_classes = false;
1215
1216 const ValueObject::GetExpressionPathFormat format =
1217 ValueObject::GetExpressionPathFormat::
1218 eGetExpressionPathFormatHonorPointers;
1219 stream->PutCString("Likely cause: ");
1220 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1221 format);
1222 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1223 }
1224 }
1225 } else {
1226 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1227 process_sp->GetTarget().shared_from_this());
1228 if (target_idx != UINT32_MAX)
1229 stream->Printf("Target %d: (", target_idx);
1230 else
1231 stream->Printf("Target <unknown index>: (");
1232 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1233 stream->Printf(") stopped.\n");
1234 }
1235 }
1236
1237 // Pop the process IO handler
1238 pop_process_io_handler = true;
1239 }
1240 break;
1241 }
1242
1243 if (handle_pop && pop_process_io_handler)
1244 process_sp->PopProcessIOHandler();
1245
1246 return true;
1247}
1248
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1250 if (listener_sp) {
1251 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1252 eBroadcastBitInterrupt);
1253 } else
1254 return false;
1255}
Greg Claytondc6224e2014-10-21 01:00:42 +00001256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001258
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001259StateType Process::GetStateChangedEvents(EventSP &event_sp,
1260 const Timeout<std::micro> &timeout,
1261 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001263 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001264
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 ListenerSP listener_sp = hijack_listener_sp;
1266 if (!listener_sp)
1267 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001268
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001270 if (listener_sp->GetEventForBroadcasterWithType(
1271 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001272 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1274 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001275 else
1276 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001277 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001278
Pavel Labathd02b1c82017-02-10 11:49:33 +00001279 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280 return state;
1281}
Greg Claytondc6224e2014-10-21 01:00:42 +00001282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283Event *Process::PeekAtStateChangedEvents() {
1284 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001285
Kate Stoneb9c1b512016-09-06 20:57:50 +00001286 if (log)
1287 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001288
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 Event *event_ptr;
1290 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1291 this, eBroadcastBitStateChanged);
1292 if (log) {
1293 if (event_ptr) {
1294 log->Printf(
1295 "Process::%s (event_ptr) => %s", __FUNCTION__,
1296 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1297 } else {
1298 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 }
1301 return event_ptr;
1302}
Greg Claytondc6224e2014-10-21 01:00:42 +00001303
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001304StateType
1305Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1306 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001308 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309
1310 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001311 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1312 &m_private_state_broadcaster,
1313 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001314 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1316 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1317
Pavel Labathd02b1c82017-02-10 11:49:33 +00001318 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1319 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 return state;
1321}
1322
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001323bool Process::GetEventsPrivate(EventSP &event_sp,
1324 const Timeout<std::micro> &timeout,
1325 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001327 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328
1329 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001330 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001331 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001333 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334}
1335
1336bool Process::IsRunning() const {
1337 return StateIsRunningState(m_public_state.GetValue());
1338}
1339
1340int Process::GetExitStatus() {
1341 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1342
1343 if (m_public_state.GetValue() == eStateExited)
1344 return m_exit_status;
1345 return -1;
1346}
1347
1348const char *Process::GetExitDescription() {
1349 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1350
1351 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1352 return m_exit_string.c_str();
1353 return nullptr;
1354}
1355
1356bool Process::SetExitStatus(int status, const char *cstr) {
1357 // Use a mutex to protect setting the exit status.
1358 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1359
1360 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1361 LIBLLDB_LOG_PROCESS));
1362 if (log)
1363 log->Printf(
1364 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1365 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1366 cstr ? "\"" : "");
1367
1368 // We were already in the exited state
1369 if (m_private_state.GetValue() == eStateExited) {
1370 if (log)
1371 log->Printf("Process::SetExitStatus () ignoring exit status because "
1372 "state was already set to eStateExited");
1373 return false;
1374 }
1375
1376 m_exit_status = status;
1377 if (cstr)
1378 m_exit_string = cstr;
1379 else
1380 m_exit_string.clear();
1381
1382 // Clear the last natural stop ID since it has a strong
1383 // reference to this process
1384 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1385
1386 SetPrivateState(eStateExited);
1387
1388 // Allow subclasses to do some cleanup
1389 DidExit();
1390
1391 return true;
1392}
1393
1394bool Process::IsAlive() {
1395 switch (m_private_state.GetValue()) {
1396 case eStateConnected:
1397 case eStateAttaching:
1398 case eStateLaunching:
1399 case eStateStopped:
1400 case eStateRunning:
1401 case eStateStepping:
1402 case eStateCrashed:
1403 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001404 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 default:
1406 return false;
1407 }
Jason Molendaa814f702015-11-05 23:03:44 +00001408}
1409
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001411// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001412// found in the global target list (we want to be completely sure that the
1413// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414bool Process::SetProcessExitStatus(
1415 lldb::pid_t pid, bool exited,
1416 int signo, // Zero for no signal
1417 int exit_status // Exit value of process if signal is zero
1418 ) {
1419 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1420 if (log)
1421 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1422 ", exited=%i, signal=%i, exit_status=%i)\n",
1423 pid, exited, signo, exit_status);
1424
1425 if (exited) {
1426 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1427 if (target_sp) {
1428 ProcessSP process_sp(target_sp->GetProcessSP());
1429 if (process_sp) {
1430 const char *signal_cstr = nullptr;
1431 if (signo)
1432 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1433
1434 process_sp->SetExitStatus(exit_status, signal_cstr);
1435 }
1436 }
1437 return true;
1438 }
1439 return false;
1440}
1441
1442void Process::UpdateThreadListIfNeeded() {
1443 const uint32_t stop_id = GetStopID();
1444 if (m_thread_list.GetSize(false) == 0 ||
1445 stop_id != m_thread_list.GetStopID()) {
1446 const StateType state = GetPrivateState();
1447 if (StateIsStoppedState(state, true)) {
1448 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1449 // m_thread_list does have its own mutex, but we need to
1450 // hold onto the mutex between the call to UpdateThreadList(...)
1451 // and the os->UpdateThreadList(...) so it doesn't change on us
1452 ThreadList &old_thread_list = m_thread_list;
1453 ThreadList real_thread_list(this);
1454 ThreadList new_thread_list(this);
1455 // Always update the thread list with the protocol specific
1456 // thread list, but only update if "true" is returned
1457 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1458 // Don't call into the OperatingSystem to update the thread list if we
1459 // are shutting down, since
1460 // that may call back into the SBAPI's, requiring the API lock which is
1461 // already held by whoever is
1462 // shutting us down, causing a deadlock.
1463 OperatingSystem *os = GetOperatingSystem();
1464 if (os && !m_destroy_in_process) {
1465 // Clear any old backing threads where memory threads might have been
1466 // backed by actual threads from the lldb_private::Process subclass
1467 size_t num_old_threads = old_thread_list.GetSize(false);
1468 for (size_t i = 0; i < num_old_threads; ++i)
1469 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1470
1471 // Turn off dynamic types to ensure we don't run any expressions.
1472 // Objective C
1473 // can run an expression to determine if a SBValue is a dynamic type
1474 // or not
1475 // and we need to avoid this. OperatingSystem plug-ins can't run
1476 // expressions
1477 // that require running code...
1478
1479 Target &target = GetTarget();
1480 const lldb::DynamicValueType saved_prefer_dynamic =
1481 target.GetPreferDynamicValue();
1482 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1483 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1484
1485 // Now let the OperatingSystem plug-in update the thread list
1486
1487 os->UpdateThreadList(
1488 old_thread_list, // Old list full of threads created by OS plug-in
1489 real_thread_list, // The actual thread list full of threads
1490 // created by each lldb_private::Process
1491 // subclass
1492 new_thread_list); // The new thread list that we will show to the
1493 // user that gets filled in
1494
1495 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1496 target.SetPreferDynamicValue(saved_prefer_dynamic);
1497 } else {
1498 // No OS plug-in, the new thread list is the same as the real thread
1499 // list
1500 new_thread_list = real_thread_list;
1501 }
1502
1503 m_thread_list_real.Update(real_thread_list);
1504 m_thread_list.Update(new_thread_list);
1505 m_thread_list.SetStopID(stop_id);
1506
1507 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1508 // Clear any extended threads that we may have accumulated previously
1509 m_extended_thread_list.Clear();
1510 m_extended_thread_stop_id = GetLastNaturalStopID();
1511
1512 m_queue_list.Clear();
1513 m_queue_list_stop_id = GetLastNaturalStopID();
1514 }
1515 }
1516 }
1517 }
1518}
1519
1520void Process::UpdateQueueListIfNeeded() {
1521 if (m_system_runtime_ap) {
1522 if (m_queue_list.GetSize() == 0 ||
1523 m_queue_list_stop_id != GetLastNaturalStopID()) {
1524 const StateType state = GetPrivateState();
1525 if (StateIsStoppedState(state, true)) {
1526 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1527 m_queue_list_stop_id = GetLastNaturalStopID();
1528 }
1529 }
1530 }
1531}
1532
1533ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1534 OperatingSystem *os = GetOperatingSystem();
1535 if (os)
1536 return os->CreateThread(tid, context);
1537 return ThreadSP();
1538}
1539
1540uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1541 return AssignIndexIDToThread(thread_id);
1542}
1543
1544bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1545 return (m_thread_id_to_index_id_map.find(thread_id) !=
1546 m_thread_id_to_index_id_map.end());
1547}
1548
1549uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1550 uint32_t result = 0;
1551 std::map<uint64_t, uint32_t>::iterator iterator =
1552 m_thread_id_to_index_id_map.find(thread_id);
1553 if (iterator == m_thread_id_to_index_id_map.end()) {
1554 result = ++m_thread_index_id;
1555 m_thread_id_to_index_id_map[thread_id] = result;
1556 } else {
1557 result = iterator->second;
1558 }
1559
1560 return result;
1561}
1562
1563StateType Process::GetState() {
1564 // If any other threads access this we will need a mutex for it
1565 return m_public_state.GetValue();
1566}
1567
1568bool Process::StateChangedIsExternallyHijacked() {
1569 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1570 const char *hijacking_name = GetHijackingListenerName();
1571 if (hijacking_name &&
1572 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1573 return true;
1574 }
1575 return false;
1576}
1577
1578void Process::SetPublicState(StateType new_state, bool restarted) {
1579 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1580 LIBLLDB_LOG_PROCESS));
1581 if (log)
1582 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1583 StateAsCString(new_state), restarted);
1584 const StateType old_state = m_public_state.GetValue();
1585 m_public_state.SetValue(new_state);
1586
1587 // On the transition from Run to Stopped, we unlock the writer end of the
1588 // run lock. The lock gets locked in Resume, which is the public API
1589 // to tell the program to run.
1590 if (!StateChangedIsExternallyHijacked()) {
1591 if (new_state == eStateDetached) {
1592 if (log)
1593 log->Printf(
1594 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1595 StateAsCString(new_state));
1596 m_public_run_lock.SetStopped();
1597 } else {
1598 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1599 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1600 if ((old_state_is_stopped != new_state_is_stopped)) {
1601 if (new_state_is_stopped && !restarted) {
1602 if (log)
1603 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1604 StateAsCString(new_state));
1605 m_public_run_lock.SetStopped();
1606 }
1607 }
1608 }
1609 }
1610}
1611
1612Error Process::Resume() {
1613 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1614 LIBLLDB_LOG_PROCESS));
1615 if (log)
1616 log->Printf("Process::Resume -- locking run lock");
1617 if (!m_public_run_lock.TrySetRunning()) {
1618 Error error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001619 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001621 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001622 }
1623 return PrivateResume();
Greg Claytondc6224e2014-10-21 01:00:42 +00001624}
1625
Kate Stoneb9c1b512016-09-06 20:57:50 +00001626Error Process::ResumeSynchronous(Stream *stream) {
1627 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1628 LIBLLDB_LOG_PROCESS));
1629 if (log)
1630 log->Printf("Process::ResumeSynchronous -- locking run lock");
1631 if (!m_public_run_lock.TrySetRunning()) {
1632 Error error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001633 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1635 return error;
1636 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637
Kate Stoneb9c1b512016-09-06 20:57:50 +00001638 ListenerSP listener_sp(
1639 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1640 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001641
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 Error error = PrivateResume();
1643 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001644 StateType state =
1645 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646 const bool must_be_alive =
1647 false; // eStateExited is ok, so this must be false
1648 if (!StateIsStoppedState(state, must_be_alive))
1649 error.SetErrorStringWithFormat(
1650 "process not in stopped state after synchronous resume: %s",
1651 StateAsCString(state));
1652 }
Ed Mastec29693f2013-07-02 16:35:47 +00001653
Kate Stoneb9c1b512016-09-06 20:57:50 +00001654 // Undo the hijacking of process events...
1655 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001656
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 return error;
1658}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001659
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001661
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662void Process::SetPrivateState(StateType new_state) {
1663 if (m_finalize_called)
1664 return;
1665
1666 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1667 LIBLLDB_LOG_PROCESS));
1668 bool state_changed = false;
1669
1670 if (log)
1671 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1672
1673 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1674 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1675
1676 const StateType old_state = m_private_state.GetValueNoLock();
1677 state_changed = old_state != new_state;
1678
1679 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1680 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1681 if (old_state_is_stopped != new_state_is_stopped) {
1682 if (new_state_is_stopped)
1683 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685 m_private_run_lock.SetRunning();
1686 }
1687
1688 if (state_changed) {
1689 m_private_state.SetValueNoLock(new_state);
1690 EventSP event_sp(
1691 new Event(eBroadcastBitStateChanged,
1692 new ProcessEventData(shared_from_this(), new_state)));
1693 if (StateIsStoppedState(new_state, false)) {
1694 // Note, this currently assumes that all threads in the list
1695 // stop when the process stops. In the future we will want to
1696 // support a debugging model where some threads continue to run
1697 // while others are stopped. When that happens we will either need
1698 // a way for the thread list to identify which threads are stopping
1699 // or create a special thread list containing only threads which
1700 // actually stopped.
1701 //
1702 // The process plugin is responsible for managing the actual
1703 // behavior of the threads and should have stopped any threads
1704 // that are going to stop before we get here.
1705 m_thread_list.DidStop();
1706
1707 m_mod_id.BumpStopID();
1708 if (!m_mod_id.IsLastResumeForUserExpression())
1709 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1710 m_memory_cache.Clear();
1711 if (log)
1712 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1713 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001714 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716 // Use our target to get a shared pointer to ourselves...
1717 if (m_finalize_called && !PrivateStateThreadIsValid())
1718 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001719 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720 m_private_state_broadcaster.BroadcastEvent(event_sp);
1721 } else {
1722 if (log)
1723 log->Printf(
1724 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1725 StateAsCString(new_state));
1726 }
Jim Ingham22777012010-09-23 02:01:19 +00001727}
1728
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729void Process::SetRunningUserExpression(bool on) {
1730 m_mod_id.SetRunningUserExpression(on);
1731}
1732
1733addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1734
1735const lldb::ABISP &Process::GetABI() {
1736 if (!m_abi_sp)
1737 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
1738 return m_abi_sp;
1739}
1740
1741LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1742 bool retry_if_null) {
1743 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001744 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745
1746 LanguageRuntimeCollection::iterator pos;
1747 pos = m_language_runtimes.find(language);
1748 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1749 lldb::LanguageRuntimeSP runtime_sp(
1750 LanguageRuntime::FindPlugin(this, language));
1751
1752 m_language_runtimes[language] = runtime_sp;
1753 return runtime_sp.get();
1754 } else
1755 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001756}
1757
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1759 LanguageRuntime *runtime =
1760 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1761 if (runtime != nullptr &&
1762 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1763 return static_cast<CPPLanguageRuntime *>(runtime);
1764 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001765}
1766
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1768 LanguageRuntime *runtime =
1769 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1770 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1771 return static_cast<ObjCLanguageRuntime *>(runtime);
1772 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001773}
1774
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1776 if (m_finalizing)
1777 return false;
1778
1779 if (in_value.IsDynamic())
1780 return false;
1781 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1782
1783 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1784 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1785 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1786 }
1787
1788 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1789 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1790 return true;
1791
1792 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1793 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001794}
1795
Kate Stoneb9c1b512016-09-06 20:57:50 +00001796void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1797 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001798}
1799
Kate Stoneb9c1b512016-09-06 20:57:50 +00001800BreakpointSiteList &Process::GetBreakpointSiteList() {
1801 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802}
1803
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1805 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806}
1807
Kate Stoneb9c1b512016-09-06 20:57:50 +00001808void Process::DisableAllBreakpointSites() {
1809 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1810 // bp_site->SetEnabled(true);
1811 DisableBreakpointSite(bp_site);
1812 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813}
1814
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815Error Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1816 Error error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818 if (error.Success())
1819 m_breakpoint_site_list.Remove(break_id);
1820
1821 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001822}
1823
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824Error Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1825 Error error;
1826 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1827 if (bp_site_sp) {
1828 if (bp_site_sp->IsEnabled())
1829 error = DisableBreakpointSite(bp_site_sp.get());
1830 } else {
1831 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1832 break_id);
1833 }
1834
1835 return error;
1836}
1837
1838Error Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1839 Error error;
1840 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1841 if (bp_site_sp) {
1842 if (!bp_site_sp->IsEnabled())
1843 error = EnableBreakpointSite(bp_site_sp.get());
1844 } else {
1845 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1846 break_id);
1847 }
1848 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849}
1850
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001851lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001852Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1853 bool use_hardware) {
1854 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001855
Kate Stoneb9c1b512016-09-06 20:57:50 +00001856 bool show_error = true;
1857 switch (GetState()) {
1858 case eStateInvalid:
1859 case eStateUnloaded:
1860 case eStateConnected:
1861 case eStateAttaching:
1862 case eStateLaunching:
1863 case eStateDetached:
1864 case eStateExited:
1865 show_error = false;
1866 break;
1867
1868 case eStateStopped:
1869 case eStateRunning:
1870 case eStateStepping:
1871 case eStateCrashed:
1872 case eStateSuspended:
1873 show_error = IsAlive();
1874 break;
1875 }
1876
1877 // Reset the IsIndirect flag here, in case the location changes from
1878 // pointing to a indirect symbol to a regular symbol.
1879 owner->SetIsIndirect(false);
1880
1881 if (owner->ShouldResolveIndirectFunctions()) {
1882 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1883 if (symbol && symbol->IsIndirect()) {
1884 Error error;
1885 Address symbol_address = symbol->GetAddress();
1886 load_addr = ResolveIndirectFunction(&symbol_address, error);
1887 if (!error.Success() && show_error) {
1888 GetTarget().GetDebugger().GetErrorFile()->Printf(
1889 "warning: failed to resolve indirect function at 0x%" PRIx64
1890 " for breakpoint %i.%i: %s\n",
1891 symbol->GetLoadAddress(&GetTarget()),
1892 owner->GetBreakpoint().GetID(), owner->GetID(),
1893 error.AsCString() ? error.AsCString() : "unknown error");
1894 return LLDB_INVALID_BREAK_ID;
1895 }
1896 Address resolved_address(load_addr);
1897 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1898 owner->SetIsIndirect(true);
1899 } else
1900 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1901 } else
1902 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1903
1904 if (load_addr != LLDB_INVALID_ADDRESS) {
1905 BreakpointSiteSP bp_site_sp;
1906
1907 // Look up this breakpoint site. If it exists, then add this new owner,
1908 // otherwise
1909 // create a new breakpoint site and add it.
1910
1911 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1912
1913 if (bp_site_sp) {
1914 bp_site_sp->AddOwner(owner);
1915 owner->SetBreakpointSite(bp_site_sp);
1916 return bp_site_sp->GetID();
1917 } else {
1918 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1919 load_addr, use_hardware));
1920 if (bp_site_sp) {
1921 Error error = EnableBreakpointSite(bp_site_sp.get());
1922 if (error.Success()) {
1923 owner->SetBreakpointSite(bp_site_sp);
1924 return m_breakpoint_site_list.Add(bp_site_sp);
1925 } else {
1926 if (show_error) {
1927 // Report error for setting breakpoint...
1928 GetTarget().GetDebugger().GetErrorFile()->Printf(
1929 "warning: failed to set breakpoint site at 0x%" PRIx64
1930 " for breakpoint %i.%i: %s\n",
1931 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1932 error.AsCString() ? error.AsCString() : "unknown error");
1933 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001936 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001937 }
1938 // We failed to enable the breakpoint
1939 return LLDB_INVALID_BREAK_ID;
1940}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1943 lldb::user_id_t owner_loc_id,
1944 BreakpointSiteSP &bp_site_sp) {
1945 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1946 if (num_owners == 0) {
1947 // Don't try to disable the site if we don't have a live process anymore.
1948 if (IsAlive())
1949 DisableBreakpointSite(bp_site_sp.get());
1950 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1951 }
1952}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001953
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1955 uint8_t *buf) const {
1956 size_t bytes_removed = 0;
1957 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1960 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001961 bp_sites_in_range.ForEach([bp_addr, size,
1962 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001963 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1964 addr_t intersect_addr;
1965 size_t intersect_size;
1966 size_t opcode_offset;
1967 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1968 &intersect_size, &opcode_offset)) {
1969 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1970 assert(bp_addr < intersect_addr + intersect_size &&
1971 intersect_addr + intersect_size <= bp_addr + size);
1972 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1973 size_t buf_offset = intersect_addr - bp_addr;
1974 ::memcpy(buf + buf_offset,
1975 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1976 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 }
1979 });
1980 }
1981 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982}
1983
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1985 PlatformSP platform_sp(GetTarget().GetPlatform());
1986 if (platform_sp)
1987 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1988 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001989}
1990
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991Error Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1992 Error error;
1993 assert(bp_site != nullptr);
1994 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1995 const addr_t bp_addr = bp_site->GetLoadAddress();
1996 if (log)
1997 log->Printf(
1998 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1999 bp_site->GetID(), (uint64_t)bp_addr);
2000 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002001 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002 log->Printf(
2003 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2004 " -- already enabled",
2005 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 }
2008
2009 if (bp_addr == LLDB_INVALID_ADDRESS) {
2010 error.SetErrorString("BreakpointSite contains an invalid load address.");
2011 return error;
2012 }
2013 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2014 // trap for the breakpoint site
2015 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2016
2017 if (bp_opcode_size == 0) {
2018 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2019 "returned zero, unable to get breakpoint "
2020 "trap for address 0x%" PRIx64,
2021 bp_addr);
2022 } else {
2023 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2024
2025 if (bp_opcode_bytes == nullptr) {
2026 error.SetErrorString(
2027 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2028 return error;
2029 }
2030
2031 // Save the original opcode by reading it
2032 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2033 error) == bp_opcode_size) {
2034 // Write a software breakpoint in place of the original opcode
2035 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2036 bp_opcode_size) {
2037 uint8_t verify_bp_opcode_bytes[64];
2038 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2039 error) == bp_opcode_size) {
2040 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2041 bp_opcode_size) == 0) {
2042 bp_site->SetEnabled(true);
2043 bp_site->SetType(BreakpointSite::eSoftware);
2044 if (log)
2045 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2046 "addr = 0x%" PRIx64 " -- SUCCESS",
2047 bp_site->GetID(), (uint64_t)bp_addr);
2048 } else
2049 error.SetErrorString(
2050 "failed to verify the breakpoint trap in memory.");
2051 } else
2052 error.SetErrorString(
2053 "Unable to read memory to verify breakpoint trap.");
2054 } else
2055 error.SetErrorString("Unable to write breakpoint trap to memory.");
2056 } else
2057 error.SetErrorString("Unable to read memory at breakpoint address.");
2058 }
2059 if (log && error.Fail())
2060 log->Printf(
2061 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2062 " -- FAILED: %s",
2063 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2064 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002065}
2066
Kate Stoneb9c1b512016-09-06 20:57:50 +00002067Error Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2068 Error error;
2069 assert(bp_site != nullptr);
2070 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2071 addr_t bp_addr = bp_site->GetLoadAddress();
2072 lldb::user_id_t breakID = bp_site->GetID();
2073 if (log)
2074 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2075 ") addr = 0x%" PRIx64,
2076 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002077
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 if (bp_site->IsHardware()) {
2079 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2080 } else if (bp_site->IsEnabled()) {
2081 const size_t break_op_size = bp_site->GetByteSize();
2082 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2083 if (break_op_size > 0) {
2084 // Clear a software breakpoint instruction
2085 uint8_t curr_break_op[8];
2086 assert(break_op_size <= sizeof(curr_break_op));
2087 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 // Read the breakpoint opcode
2090 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2091 break_op_size) {
2092 bool verify = false;
2093 // Make sure the breakpoint opcode exists at this address
2094 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2095 break_op_found = true;
2096 // We found a valid breakpoint opcode at this address, now restore
2097 // the saved opcode.
2098 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2099 break_op_size, error) == break_op_size) {
2100 verify = true;
2101 } else
2102 error.SetErrorString(
2103 "Memory write failed when restoring original opcode.");
2104 } else {
2105 error.SetErrorString(
2106 "Original breakpoint trap is no longer in memory.");
2107 // Set verify to true and so we can check if the original opcode has
2108 // already been restored
2109 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 if (verify) {
2113 uint8_t verify_opcode[8];
2114 assert(break_op_size < sizeof(verify_opcode));
2115 // Verify that our original opcode made it back to the inferior
2116 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2117 break_op_size) {
2118 // compare the memory we just read with the original opcode
2119 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2120 break_op_size) == 0) {
2121 // SUCCESS
2122 bp_site->SetEnabled(false);
2123 if (log)
2124 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2125 "addr = 0x%" PRIx64 " -- SUCCESS",
2126 bp_site->GetID(), (uint64_t)bp_addr);
2127 return error;
2128 } else {
2129 if (break_op_found)
2130 error.SetErrorString("Failed to restore original opcode.");
2131 }
2132 } else
2133 error.SetErrorString("Failed to read memory to verify that "
2134 "breakpoint trap was restored.");
2135 }
2136 } else
2137 error.SetErrorString(
2138 "Unable to read memory that should contain the breakpoint trap.");
2139 }
2140 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002142 log->Printf(
2143 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2144 " -- already disabled",
2145 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147 }
2148
2149 if (log)
2150 log->Printf(
2151 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2152 " -- FAILED: %s",
2153 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2154 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155}
2156
Greg Clayton58be07b2011-01-07 06:08:19 +00002157// Uncomment to verify memory caching works after making changes to caching code
2158//#define VERIFY_MEMORY_READS
2159
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Error &error) {
2161 error.Clear();
2162 if (!GetDisableMemoryCache()) {
2163#if defined(VERIFY_MEMORY_READS)
2164 // Memory caching is enabled, with debug verification
2165
2166 if (buf && size) {
2167 // Uncomment the line below to make sure memory caching is working.
2168 // I ran this through the test suite and got no assertions, so I am
2169 // pretty confident this is working well. If any changes are made to
2170 // memory caching, uncomment the line below and test your changes!
2171
2172 // Verify all memory reads by using the cache first, then redundantly
2173 // reading the same memory from the inferior and comparing to make sure
2174 // everything is exactly the same.
2175 std::string verify_buf(size, '\0');
2176 assert(verify_buf.size() == size);
2177 const size_t cache_bytes_read =
2178 m_memory_cache.Read(this, addr, buf, size, error);
2179 Error verify_error;
2180 const size_t verify_bytes_read =
2181 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2182 verify_buf.size(), verify_error);
2183 assert(cache_bytes_read == verify_bytes_read);
2184 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2185 assert(verify_error.Success() == error.Success());
2186 return cache_bytes_read;
2187 }
2188 return 0;
2189#else // !defined(VERIFY_MEMORY_READS)
2190 // Memory caching is enabled, without debug verification
2191
2192 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002193#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002194 } else {
2195 // Memory caching is disabled
2196
2197 return ReadMemoryFromInferior(addr, buf, size, error);
2198 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002199}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200
2201size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2202 Error &error) {
2203 char buf[256];
2204 out_str.clear();
2205 addr_t curr_addr = addr;
2206 while (true) {
2207 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2208 if (length == 0)
2209 break;
2210 out_str.append(buf, length);
2211 // If we got "length - 1" bytes, we didn't get the whole C string, we
2212 // need to read some more characters
2213 if (length == sizeof(buf) - 1)
2214 curr_addr += length;
2215 else
2216 break;
2217 }
2218 return out_str.size();
2219}
2220
2221size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2222 Error &error, size_t type_width) {
2223 size_t total_bytes_read = 0;
2224 if (dst && max_bytes && type_width && max_bytes >= type_width) {
2225 // Ensure a null terminator independent of the number of bytes that is read.
2226 memset(dst, 0, max_bytes);
2227 size_t bytes_left = max_bytes - type_width;
2228
2229 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2230 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2231 "string with more than 4 bytes "
2232 "per character!");
2233
Greg Clayton4c82d422012-05-18 23:20:01 +00002234 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2236 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002237
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 error.Clear();
2239 while (bytes_left > 0 && error.Success()) {
2240 addr_t cache_line_bytes_left =
2241 cache_line_size - (curr_addr % cache_line_size);
2242 addr_t bytes_to_read =
2243 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2244 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002245
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 if (bytes_read == 0)
2247 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002248
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 // Search for a null terminator of correct size and alignment in
2250 // bytes_read
2251 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2252 for (size_t i = aligned_start;
2253 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2254 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2255 error.Clear();
2256 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258
2259 total_bytes_read += bytes_read;
2260 curr_dst += bytes_read;
2261 curr_addr += bytes_read;
2262 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002263 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002264 } else {
2265 if (max_bytes)
2266 error.SetErrorString("invalid arguments");
2267 }
2268 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002269}
2270
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271// Deprecated in favor of ReadStringFromMemory which has wchar support and
2272// correct code to find
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002273// null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2275 size_t dst_max_len, Error &result_error) {
2276 size_t total_cstr_len = 0;
2277 if (dst && dst_max_len) {
2278 result_error.Clear();
2279 // NULL out everything just to be safe
2280 memset(dst, 0, dst_max_len);
2281 Error error;
2282 addr_t curr_addr = addr;
2283 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2284 size_t bytes_left = dst_max_len - 1;
2285 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002286
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287 while (bytes_left > 0) {
2288 addr_t cache_line_bytes_left =
2289 cache_line_size - (curr_addr % cache_line_size);
2290 addr_t bytes_to_read =
2291 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2292 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 if (bytes_read == 0) {
2295 result_error = error;
2296 dst[total_cstr_len] = '\0';
2297 break;
2298 }
2299 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002300
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 total_cstr_len += len;
2302
2303 if (len < bytes_to_read)
2304 break;
2305
2306 curr_dst += bytes_read;
2307 curr_addr += bytes_read;
2308 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002309 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002310 } else {
2311 if (dst == nullptr)
2312 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002313 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314 result_error.Clear();
2315 }
2316 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002317}
2318
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2320 Error &error) {
2321 if (buf == nullptr || size == 0)
2322 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 size_t bytes_read = 0;
2325 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327 while (bytes_read < size) {
2328 const size_t curr_size = size - bytes_read;
2329 const size_t curr_bytes_read =
2330 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2331 bytes_read += curr_bytes_read;
2332 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2333 break;
2334 }
2335
2336 // Replace any software breakpoint opcodes that fall into this range back
2337 // into "buf" before we return
2338 if (bytes_read > 0)
2339 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2340 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341}
2342
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2344 size_t integer_byte_size,
2345 uint64_t fail_value,
2346 Error &error) {
2347 Scalar scalar;
2348 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2349 error))
2350 return scalar.ULongLong(fail_value);
2351 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002352}
2353
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2355 size_t integer_byte_size,
2356 int64_t fail_value, Error &error) {
2357 Scalar scalar;
2358 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2359 error))
2360 return scalar.SLongLong(fail_value);
2361 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002362}
2363
Kate Stoneb9c1b512016-09-06 20:57:50 +00002364addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Error &error) {
2365 Scalar scalar;
2366 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2367 error))
2368 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2369 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002370}
2371
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2373 Error &error) {
2374 Scalar scalar;
2375 const uint32_t addr_byte_size = GetAddressByteSize();
2376 if (addr_byte_size <= 4)
2377 scalar = (uint32_t)ptr_value;
2378 else
2379 scalar = ptr_value;
2380 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2381 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002382}
2383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2385 Error &error) {
2386 size_t bytes_written = 0;
2387 const uint8_t *bytes = (const uint8_t *)buf;
2388
2389 while (bytes_written < size) {
2390 const size_t curr_size = size - bytes_written;
2391 const size_t curr_bytes_written = DoWriteMemory(
2392 addr + bytes_written, bytes + bytes_written, curr_size, error);
2393 bytes_written += curr_bytes_written;
2394 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2395 break;
2396 }
2397 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398}
2399
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2401 Error &error) {
2402#if defined(ENABLE_MEMORY_CACHING)
2403 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002404#endif
2405
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406 if (buf == nullptr || size == 0)
2407 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002408
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002410
Kate Stoneb9c1b512016-09-06 20:57:50 +00002411 // We need to write any data that would go where any current software traps
2412 // (enabled software breakpoints) any software traps (breakpoints) that we
2413 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2418 bp_sites_in_range)) {
2419 // No breakpoint sites overlap
2420 if (bp_sites_in_range.IsEmpty())
2421 return WriteMemoryPrivate(addr, buf, size, error);
2422 else {
2423 const uint8_t *ubuf = (const uint8_t *)buf;
2424 uint64_t bytes_written = 0;
2425
2426 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2427 &error](BreakpointSite *bp) -> void {
2428
2429 if (error.Success()) {
2430 addr_t intersect_addr;
2431 size_t intersect_size;
2432 size_t opcode_offset;
2433 const bool intersects = bp->IntersectsRange(
2434 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2435 UNUSED_IF_ASSERT_DISABLED(intersects);
2436 assert(intersects);
2437 assert(addr <= intersect_addr && intersect_addr < addr + size);
2438 assert(addr < intersect_addr + intersect_size &&
2439 intersect_addr + intersect_size <= addr + size);
2440 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2441
2442 // Check for bytes before this breakpoint
2443 const addr_t curr_addr = addr + bytes_written;
2444 if (intersect_addr > curr_addr) {
2445 // There are some bytes before this breakpoint that we need to
2446 // just write to memory
2447 size_t curr_size = intersect_addr - curr_addr;
2448 size_t curr_bytes_written = WriteMemoryPrivate(
2449 curr_addr, ubuf + bytes_written, curr_size, error);
2450 bytes_written += curr_bytes_written;
2451 if (curr_bytes_written != curr_size) {
2452 // We weren't able to write all of the requested bytes, we
2453 // are done looping and will return the number of bytes that
2454 // we have written so far.
2455 if (error.Success())
2456 error.SetErrorToGenericError();
2457 }
2458 }
2459 // Now write any bytes that would cover up any software breakpoints
2460 // directly into the breakpoint opcode buffer
2461 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2462 ubuf + bytes_written, intersect_size);
2463 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002464 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002466
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 if (bytes_written < size)
2468 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2469 size - bytes_written, error);
2470 }
2471 } else {
2472 return WriteMemoryPrivate(addr, buf, size, error);
2473 }
2474
2475 // Write any remaining bytes after the last breakpoint if we have any left
2476 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002477}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002478
Kate Stoneb9c1b512016-09-06 20:57:50 +00002479size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2480 size_t byte_size, Error &error) {
2481 if (byte_size == UINT32_MAX)
2482 byte_size = scalar.GetByteSize();
2483 if (byte_size > 0) {
2484 uint8_t buf[32];
2485 const size_t mem_size =
2486 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2487 if (mem_size > 0)
2488 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002489 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 error.SetErrorString("failed to get scalar as memory data");
2491 } else {
2492 error.SetErrorString("invalid scalar value");
2493 }
2494 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002495}
2496
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2498 bool is_signed, Scalar &scalar,
2499 Error &error) {
2500 uint64_t uval = 0;
2501 if (byte_size == 0) {
2502 error.SetErrorString("byte size is zero");
2503 } else if (byte_size & (byte_size - 1)) {
2504 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2505 byte_size);
2506 } else if (byte_size <= sizeof(uval)) {
2507 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2508 if (bytes_read == byte_size) {
2509 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2510 GetAddressByteSize());
2511 lldb::offset_t offset = 0;
2512 if (byte_size <= 4)
2513 scalar = data.GetMaxU32(&offset, byte_size);
2514 else
2515 scalar = data.GetMaxU64(&offset, byte_size);
2516 if (is_signed)
2517 scalar.SignExtend(byte_size * 8);
2518 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002519 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520 } else {
2521 error.SetErrorStringWithFormat(
2522 "byte size of %u is too large for integer scalar type", byte_size);
2523 }
2524 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002525}
2526
Greg Claytond495c532011-05-17 03:37:42 +00002527#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002528addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2529 Error &error) {
2530 if (GetPrivateState() != eStateStopped)
2531 return LLDB_INVALID_ADDRESS;
2532
2533#if defined(USE_ALLOCATE_MEMORY_CACHE)
2534 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002535#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002536 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2537 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2538 if (log)
2539 log->Printf("Process::AllocateMemory(size=%" PRIu64
2540 ", permissions=%s) => 0x%16.16" PRIx64
2541 " (m_stop_id = %u m_memory_id = %u)",
2542 (uint64_t)size, GetPermissionsAsCString(permissions),
2543 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2544 m_mod_id.GetMemoryID());
2545 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002546#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547}
2548
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2550 Error &error) {
2551 addr_t return_addr = AllocateMemory(size, permissions, error);
2552 if (error.Success()) {
2553 std::string buffer(size, 0);
2554 WriteMemory(return_addr, buffer.c_str(), size, error);
2555 }
2556 return return_addr;
2557}
2558
2559bool Process::CanJIT() {
2560 if (m_can_jit == eCanJITDontKnow) {
2561 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2562 Error err;
2563
2564 uint64_t allocated_memory = AllocateMemory(
2565 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2566 err);
2567
2568 if (err.Success()) {
2569 m_can_jit = eCanJITYes;
2570 if (log)
2571 log->Printf("Process::%s pid %" PRIu64
2572 " allocation test passed, CanJIT () is true",
2573 __FUNCTION__, GetID());
2574 } else {
2575 m_can_jit = eCanJITNo;
2576 if (log)
2577 log->Printf("Process::%s pid %" PRIu64
2578 " allocation test failed, CanJIT () is false: %s",
2579 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002580 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581
2582 DeallocateMemory(allocated_memory);
2583 }
2584
2585 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002586}
2587
Kate Stoneb9c1b512016-09-06 20:57:50 +00002588void Process::SetCanJIT(bool can_jit) {
2589 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002590}
2591
Kate Stoneb9c1b512016-09-06 20:57:50 +00002592void Process::SetCanRunCode(bool can_run_code) {
2593 SetCanJIT(can_run_code);
2594 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002595}
2596
Kate Stoneb9c1b512016-09-06 20:57:50 +00002597Error Process::DeallocateMemory(addr_t ptr) {
2598 Error error;
2599#if defined(USE_ALLOCATE_MEMORY_CACHE)
2600 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2601 error.SetErrorStringWithFormat(
2602 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2603 }
Greg Claytond495c532011-05-17 03:37:42 +00002604#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605 error = DoDeallocateMemory(ptr);
2606
2607 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2608 if (log)
2609 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2610 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2611 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2612 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002613#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002614 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615}
2616
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2618 lldb::addr_t header_addr,
2619 size_t size_to_read) {
2620 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2621 if (log) {
2622 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2623 file_spec.GetPath().c_str());
2624 }
2625 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2626 if (module_sp) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627 Error error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002628 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2629 shared_from_this(), header_addr, error, size_to_read);
2630 if (objfile)
2631 return module_sp;
2632 }
2633 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002634}
2635
Kate Stoneb9c1b512016-09-06 20:57:50 +00002636bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2637 uint32_t &permissions) {
2638 MemoryRegionInfo range_info;
2639 permissions = 0;
2640 Error error(GetMemoryRegionInfo(load_addr, range_info));
2641 if (!error.Success())
2642 return false;
2643 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2644 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2645 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2646 return false;
2647 }
2648
2649 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2650 permissions |= lldb::ePermissionsReadable;
2651
2652 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2653 permissions |= lldb::ePermissionsWritable;
2654
2655 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2656 permissions |= lldb::ePermissionsExecutable;
2657
2658 return true;
2659}
2660
2661Error Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2662 Error error;
2663 error.SetErrorString("watchpoints are not supported");
2664 return error;
2665}
2666
2667Error Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2668 Error error;
2669 error.SetErrorString("watchpoints are not supported");
2670 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002671}
2672
2673StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002674Process::WaitForProcessStopPrivate(EventSP &event_sp,
2675 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 StateType state;
2677 // Now wait for the process to launch and return control to us, and then
2678 // call DidLaunch:
2679 while (true) {
2680 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002681 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002682
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683 if (StateIsStoppedState(state, false))
2684 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002685
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686 // If state is invalid, then we timed out
2687 if (state == eStateInvalid)
2688 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002689
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 if (event_sp)
2691 HandlePrivateEvent(event_sp);
2692 }
2693 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694}
2695
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696void Process::LoadOperatingSystemPlugin(bool flush) {
2697 if (flush)
2698 m_thread_list.Clear();
2699 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2700 if (flush)
2701 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002702}
2703
Kate Stoneb9c1b512016-09-06 20:57:50 +00002704Error Process::Launch(ProcessLaunchInfo &launch_info) {
2705 Error error;
2706 m_abi_sp.reset();
2707 m_dyld_ap.reset();
2708 m_jit_loaders_ap.reset();
2709 m_system_runtime_ap.reset();
2710 m_os_ap.reset();
2711 m_process_input_reader.reset();
2712 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 Module *exe_module = GetTarget().GetExecutableModulePointer();
2715 if (exe_module) {
2716 char local_exec_file_path[PATH_MAX];
2717 char platform_exec_file_path[PATH_MAX];
2718 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2719 sizeof(local_exec_file_path));
2720 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2721 sizeof(platform_exec_file_path));
2722 if (exe_module->GetFileSpec().Exists()) {
2723 // Install anything that might need to be installed prior to launching.
2724 // For host systems, this will do nothing, but if we are connected to a
2725 // remote platform it will install any needed binaries
2726 error = GetTarget().Install(&launch_info);
2727 if (error.Fail())
2728 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002729
Kate Stoneb9c1b512016-09-06 20:57:50 +00002730 if (PrivateStateThreadIsValid())
2731 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002732
Kate Stoneb9c1b512016-09-06 20:57:50 +00002733 error = WillLaunch(exe_module);
2734 if (error.Success()) {
2735 const bool restarted = false;
2736 SetPublicState(eStateLaunching, restarted);
2737 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738
Kate Stoneb9c1b512016-09-06 20:57:50 +00002739 if (m_public_run_lock.TrySetRunning()) {
2740 // Now launch using these arguments.
2741 error = DoLaunch(exe_module, launch_info);
2742 } else {
2743 // This shouldn't happen
2744 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746
Kate Stoneb9c1b512016-09-06 20:57:50 +00002747 if (error.Fail()) {
2748 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2749 SetID(LLDB_INVALID_PROCESS_ID);
2750 const char *error_string = error.AsCString();
2751 if (error_string == nullptr)
2752 error_string = "launch failed";
2753 SetExitStatus(-1, error_string);
2754 }
2755 } else {
2756 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002757 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002758
Kate Stoneb9c1b512016-09-06 20:57:50 +00002759 if (state == eStateInvalid || !event_sp) {
2760 // We were able to launch the process, but we failed to
2761 // catch the initial stop.
2762 error.SetErrorString("failed to catch stop after launch");
2763 SetExitStatus(0, "failed to catch stop after launch");
2764 Destroy(false);
2765 } else if (state == eStateStopped || state == eStateCrashed) {
2766 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002767
Kate Stoneb9c1b512016-09-06 20:57:50 +00002768 DynamicLoader *dyld = GetDynamicLoader();
2769 if (dyld)
2770 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002771
Kate Stoneb9c1b512016-09-06 20:57:50 +00002772 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002773
Kate Stoneb9c1b512016-09-06 20:57:50 +00002774 SystemRuntime *system_runtime = GetSystemRuntime();
2775 if (system_runtime)
2776 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002777
Greg Clayton29eeea02017-02-09 18:55:41 +00002778 if (!m_os_ap)
2779 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002780
Kate Stoneb9c1b512016-09-06 20:57:50 +00002781 // Note, the stop event was consumed above, but not handled. This
2782 // was done
2783 // to give DidLaunch a chance to run. The target is either stopped
2784 // or crashed.
2785 // Directly set the state. This is done to prevent a stop message
2786 // with a bunch
2787 // of spurious output on thread status, as well as not pop a
2788 // ProcessIOHandler.
2789 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002790
Kate Stoneb9c1b512016-09-06 20:57:50 +00002791 if (PrivateStateThreadIsValid())
2792 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002793 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002795
Kate Stoneb9c1b512016-09-06 20:57:50 +00002796 m_stop_info_override_callback =
2797 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002798
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 // Target was stopped at entry as was intended. Need to notify the
2800 // listeners
2801 // about it.
2802 if (state == eStateStopped &&
2803 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2804 HandlePrivateEvent(event_sp);
2805 } else if (state == eStateExited) {
2806 // We exited while trying to launch somehow. Don't call DidLaunch
2807 // as that's
2808 // not likely to work, and return an invalid pid.
2809 HandlePrivateEvent(event_sp);
2810 }
2811 }
2812 }
2813 } else {
2814 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2815 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002816 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 }
2818 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002819}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002820
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821Error Process::LoadCore() {
2822 Error error = DoLoadCore();
2823 if (error.Success()) {
2824 ListenerSP listener_sp(
2825 Listener::MakeListener("lldb.process.load_core_listener"));
2826 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002827
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 if (PrivateStateThreadIsValid())
2829 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002830 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002832
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002834 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002835 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002836
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002837 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002838
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002840 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002842
Greg Clayton29eeea02017-02-09 18:55:41 +00002843 if (!m_os_ap)
2844 LoadOperatingSystemPlugin(false);
2845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 // We successfully loaded a core file, now pretend we stopped so we can
2847 // show all of the threads in the core file and explore the crashed
2848 // state.
2849 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002850
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 // Wait indefinitely for a stopped event since we just posted one above...
2852 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00002853 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002854 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2855
2856 if (!StateIsStoppedState(state, false)) {
2857 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2858 if (log)
2859 log->Printf("Process::Halt() failed to stop, state is: %s",
2860 StateAsCString(state));
2861 error.SetErrorString(
2862 "Did not get stopped event after loading the core file.");
2863 }
2864 RestoreProcessEvents();
2865 }
2866 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002867}
2868
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869DynamicLoader *Process::GetDynamicLoader() {
2870 if (!m_dyld_ap)
2871 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2872 return m_dyld_ap.get();
2873}
2874
2875const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2876
2877JITLoaderList &Process::GetJITLoaders() {
2878 if (!m_jit_loaders_ap) {
2879 m_jit_loaders_ap.reset(new JITLoaderList());
2880 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2881 }
2882 return *m_jit_loaders_ap;
2883}
2884
2885SystemRuntime *Process::GetSystemRuntime() {
2886 if (!m_system_runtime_ap)
2887 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2888 return m_system_runtime_ap.get();
2889}
2890
2891Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2892 uint32_t exec_count)
2893 : NextEventAction(process), m_exec_count(exec_count) {
2894 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2895 if (log)
2896 log->Printf(
2897 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2898 __FUNCTION__, static_cast<void *>(process), exec_count);
2899}
2900
2901Process::NextEventAction::EventActionResult
2902Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2903 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2904
2905 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2906 if (log)
2907 log->Printf(
2908 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2909 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2910
2911 switch (state) {
2912 case eStateAttaching:
2913 return eEventActionSuccess;
2914
2915 case eStateRunning:
2916 case eStateConnected:
2917 return eEventActionRetry;
2918
2919 case eStateStopped:
2920 case eStateCrashed:
2921 // During attach, prior to sending the eStateStopped event,
2922 // lldb_private::Process subclasses must set the new process ID.
2923 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2924 // We don't want these events to be reported, so go set the ShouldReportStop
2925 // here:
2926 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2927
2928 if (m_exec_count > 0) {
2929 --m_exec_count;
2930
2931 if (log)
2932 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2933 "remaining exec count to %" PRIu32 ", requesting resume",
2934 __FUNCTION__, StateAsCString(state), m_exec_count);
2935
2936 RequestResume();
2937 return eEventActionRetry;
2938 } else {
2939 if (log)
2940 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2941 "execs expected to start, continuing with attach",
2942 __FUNCTION__, StateAsCString(state));
2943
2944 m_process->CompleteAttach();
2945 return eEventActionSuccess;
2946 }
2947 break;
2948
2949 default:
2950 case eStateExited:
2951 case eStateInvalid:
2952 break;
2953 }
2954
2955 m_exit_string.assign("No valid Process");
2956 return eEventActionExit;
2957}
2958
2959Process::NextEventAction::EventActionResult
2960Process::AttachCompletionHandler::HandleBeingInterrupted() {
2961 return eEventActionSuccess;
2962}
2963
2964const char *Process::AttachCompletionHandler::GetExitString() {
2965 return m_exit_string.c_str();
2966}
2967
2968ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2969 if (m_listener_sp)
2970 return m_listener_sp;
2971 else
2972 return debugger.GetListener();
2973}
2974
2975Error Process::Attach(ProcessAttachInfo &attach_info) {
2976 m_abi_sp.reset();
2977 m_process_input_reader.reset();
2978 m_dyld_ap.reset();
2979 m_jit_loaders_ap.reset();
2980 m_system_runtime_ap.reset();
2981 m_os_ap.reset();
2982 m_stop_info_override_callback = nullptr;
2983
2984 lldb::pid_t attach_pid = attach_info.GetProcessID();
2985 Error error;
2986 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2987 char process_name[PATH_MAX];
2988
2989 if (attach_info.GetExecutableFile().GetPath(process_name,
2990 sizeof(process_name))) {
2991 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2992
2993 if (wait_for_launch) {
2994 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2995 if (error.Success()) {
2996 if (m_public_run_lock.TrySetRunning()) {
2997 m_should_detach = true;
2998 const bool restarted = false;
2999 SetPublicState(eStateAttaching, restarted);
3000 // Now attach using these arguments.
3001 error = DoAttachToProcessWithName(process_name, attach_info);
3002 } else {
3003 // This shouldn't happen
3004 error.SetErrorString("failed to acquire process run lock");
3005 }
3006
3007 if (error.Fail()) {
3008 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3009 SetID(LLDB_INVALID_PROCESS_ID);
3010 if (error.AsCString() == nullptr)
3011 error.SetErrorString("attach failed");
3012
3013 SetExitStatus(-1, error.AsCString());
3014 }
3015 } else {
3016 SetNextEventAction(new Process::AttachCompletionHandler(
3017 this, attach_info.GetResumeCount()));
3018 StartPrivateStateThread();
3019 }
3020 return error;
3021 }
3022 } else {
3023 ProcessInstanceInfoList process_infos;
3024 PlatformSP platform_sp(GetTarget().GetPlatform());
3025
3026 if (platform_sp) {
3027 ProcessInstanceInfoMatch match_info;
3028 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00003029 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003030 platform_sp->FindProcesses(match_info, process_infos);
3031 const uint32_t num_matches = process_infos.GetSize();
3032 if (num_matches == 1) {
3033 attach_pid = process_infos.GetProcessIDAtIndex(0);
3034 // Fall through and attach using the above process ID
3035 } else {
3036 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3037 process_name, sizeof(process_name));
3038 if (num_matches > 1) {
3039 StreamString s;
3040 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3041 false);
3042 for (size_t i = 0; i < num_matches; i++) {
3043 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3044 s, platform_sp.get(), true, false);
3045 }
3046 error.SetErrorStringWithFormat(
3047 "more than one process named %s:\n%s", process_name,
3048 s.GetData());
3049 } else
3050 error.SetErrorStringWithFormat(
3051 "could not find a process named %s", process_name);
3052 }
3053 } else {
3054 error.SetErrorString(
3055 "invalid platform, can't find processes by name");
3056 return error;
3057 }
3058 }
3059 } else {
3060 error.SetErrorString("invalid process name");
3061 }
3062 }
3063
3064 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3065 error = WillAttachToProcessWithID(attach_pid);
3066 if (error.Success()) {
3067
3068 if (m_public_run_lock.TrySetRunning()) {
3069 // Now attach using these arguments.
3070 m_should_detach = true;
3071 const bool restarted = false;
3072 SetPublicState(eStateAttaching, restarted);
3073 error = DoAttachToProcessWithID(attach_pid, attach_info);
3074 } else {
3075 // This shouldn't happen
3076 error.SetErrorString("failed to acquire process run lock");
3077 }
3078
3079 if (error.Success()) {
3080 SetNextEventAction(new Process::AttachCompletionHandler(
3081 this, attach_info.GetResumeCount()));
3082 StartPrivateStateThread();
3083 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003084 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003085 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003086
Kate Stoneb9c1b512016-09-06 20:57:50 +00003087 const char *error_string = error.AsCString();
3088 if (error_string == nullptr)
3089 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003090
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 SetExitStatus(-1, error_string);
3092 }
Greg Claytonb766a732011-02-04 01:58:07 +00003093 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003094 }
3095 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003096}
3097
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098void Process::CompleteAttach() {
3099 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3100 LIBLLDB_LOG_TARGET));
3101 if (log)
3102 log->Printf("Process::%s()", __FUNCTION__);
3103
3104 // Let the process subclass figure out at much as it can about the process
3105 // before we go looking for a dynamic loader plug-in.
3106 ArchSpec process_arch;
3107 DidAttach(process_arch);
3108
3109 if (process_arch.IsValid()) {
3110 GetTarget().SetArchitecture(process_arch);
3111 if (log) {
3112 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3113 log->Printf("Process::%s replacing process architecture with DidAttach() "
3114 "architecture: %s",
3115 __FUNCTION__, triple_str ? triple_str : "<null>");
3116 }
3117 }
3118
3119 // We just attached. If we have a platform, ask it for the process
3120 // architecture, and if it isn't
3121 // the same as the one we've already set, switch architectures.
3122 PlatformSP platform_sp(GetTarget().GetPlatform());
3123 assert(platform_sp);
3124 if (platform_sp) {
3125 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3126 if (target_arch.IsValid() &&
3127 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3128 ArchSpec platform_arch;
3129 platform_sp =
3130 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3131 if (platform_sp) {
3132 GetTarget().SetPlatform(platform_sp);
3133 GetTarget().SetArchitecture(platform_arch);
3134 if (log)
3135 log->Printf("Process::%s switching platform to %s and architecture "
3136 "to %s based on info from attach",
3137 __FUNCTION__, platform_sp->GetName().AsCString(""),
3138 platform_arch.GetTriple().getTriple().c_str());
3139 }
3140 } else if (!process_arch.IsValid()) {
3141 ProcessInstanceInfo process_info;
3142 GetProcessInfo(process_info);
3143 const ArchSpec &process_arch = process_info.GetArchitecture();
3144 if (process_arch.IsValid() &&
3145 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3146 GetTarget().SetArchitecture(process_arch);
3147 if (log)
3148 log->Printf("Process::%s switching architecture to %s based on info "
3149 "the platform retrieved for pid %" PRIu64,
3150 __FUNCTION__,
3151 process_arch.GetTriple().getTriple().c_str(), GetID());
3152 }
3153 }
3154 }
3155
3156 // We have completed the attach, now it is time to find the dynamic loader
3157 // plug-in
3158 DynamicLoader *dyld = GetDynamicLoader();
3159 if (dyld) {
3160 dyld->DidAttach();
3161 if (log) {
3162 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3163 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3164 "executable is %s (using %s plugin)",
3165 __FUNCTION__,
3166 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3167 : "<none>",
3168 dyld->GetPluginName().AsCString("<unnamed>"));
3169 }
3170 }
3171
3172 GetJITLoaders().DidAttach();
3173
3174 SystemRuntime *system_runtime = GetSystemRuntime();
3175 if (system_runtime) {
3176 system_runtime->DidAttach();
3177 if (log) {
3178 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3179 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3180 "executable is %s (using %s plugin)",
3181 __FUNCTION__,
3182 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3183 : "<none>",
3184 system_runtime->GetPluginName().AsCString("<unnamed>"));
3185 }
3186 }
3187
Greg Clayton29eeea02017-02-09 18:55:41 +00003188 if (!m_os_ap)
3189 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003190 // Figure out which one is the executable, and set that in our target:
3191 const ModuleList &target_modules = GetTarget().GetImages();
3192 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3193 size_t num_modules = target_modules.GetSize();
3194 ModuleSP new_executable_module_sp;
3195
3196 for (size_t i = 0; i < num_modules; i++) {
3197 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3198 if (module_sp && module_sp->IsExecutable()) {
3199 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3200 new_executable_module_sp = module_sp;
3201 break;
3202 }
3203 }
3204 if (new_executable_module_sp) {
3205 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3206 if (log) {
3207 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3208 log->Printf(
3209 "Process::%s after looping through modules, target executable is %s",
3210 __FUNCTION__,
3211 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3212 : "<none>");
3213 }
3214 }
3215
3216 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3217}
3218
Zachary Turner31659452016-11-17 21:15:14 +00003219Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003220 m_abi_sp.reset();
3221 m_process_input_reader.reset();
3222
3223 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003224 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225
3226 Error error(DoConnectRemote(strm, remote_url));
3227 if (error.Success()) {
3228 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3229 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003230 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003231
3232 if (state == eStateStopped || state == eStateCrashed) {
3233 // If we attached and actually have a process on the other end, then
3234 // this ended up being the equivalent of an attach.
3235 CompleteAttach();
3236
3237 // This delays passing the stopped event to listeners till
3238 // CompleteAttach gets a chance to complete...
3239 HandlePrivateEvent(event_sp);
3240 }
3241 }
3242
3243 if (PrivateStateThreadIsValid())
3244 ResumePrivateStateThread();
3245 else
3246 StartPrivateStateThread();
3247 }
3248 return error;
3249}
3250
3251Error Process::PrivateResume() {
3252 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3253 LIBLLDB_LOG_STEP));
3254 if (log)
3255 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3256 "private state: %s",
3257 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3258 StateAsCString(m_private_state.GetValue()));
3259
3260 Error error(WillResume());
3261 // Tell the process it is about to resume before the thread list
3262 if (error.Success()) {
3263 // Now let the thread list know we are about to resume so it
3264 // can let all of our threads know that they are about to be
3265 // resumed. Threads will each be called with
3266 // Thread::WillResume(StateType) where StateType contains the state
3267 // that they are supposed to have when the process is resumed
3268 // (suspended/running/stepping). Threads should also check
3269 // their resume signal in lldb::Thread::GetResumeSignal()
3270 // to see if they are supposed to start back up with a signal.
3271 if (m_thread_list.WillResume()) {
3272 // Last thing, do the PreResumeActions.
3273 if (!RunPreResumeActions()) {
3274 error.SetErrorStringWithFormat(
3275 "Process::PrivateResume PreResumeActions failed, not resuming.");
3276 } else {
3277 m_mod_id.BumpResumeID();
3278 error = DoResume();
3279 if (error.Success()) {
3280 DidResume();
3281 m_thread_list.DidResume();
3282 if (log)
3283 log->Printf("Process thinks the process has resumed.");
3284 }
3285 }
3286 } else {
3287 // Somebody wanted to run without running (e.g. we were faking a step from
3288 // one frame of a set of inlined
3289 // frames that share the same PC to another.) So generate a continue & a
3290 // stopped event,
3291 // and let the world handle them.
3292 if (log)
3293 log->Printf(
3294 "Process::PrivateResume() asked to simulate a start & stop.");
3295
3296 SetPrivateState(eStateRunning);
3297 SetPrivateState(eStateStopped);
3298 }
3299 } else if (log)
3300 log->Printf("Process::PrivateResume() got an error \"%s\".",
3301 error.AsCString("<unknown error>"));
3302 return error;
3303}
3304
3305Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3306 if (!StateIsRunningState(m_public_state.GetValue()))
3307 return Error("Process is not running.");
3308
3309 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3310 // in case it was already set and some thread plan logic calls halt on its
3311 // own.
3312 m_clear_thread_plans_on_stop |= clear_thread_plans;
3313
3314 ListenerSP halt_listener_sp(
3315 Listener::MakeListener("lldb.process.halt_listener"));
3316 HijackProcessEvents(halt_listener_sp);
3317
3318 EventSP event_sp;
3319
3320 SendAsyncInterrupt();
3321
3322 if (m_public_state.GetValue() == eStateAttaching) {
3323 // Don't hijack and eat the eStateExited as the code that was doing
3324 // the attach will be waiting for this event...
3325 RestoreProcessEvents();
3326 SetExitStatus(SIGKILL, "Cancelled async attach.");
3327 Destroy(false);
Mehdi Aminic1edf562016-11-11 04:29:25 +00003328 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003329 }
3330
3331 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003332 StateType state = WaitForProcessToStop(
3333 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003334 RestoreProcessEvents();
3335
3336 if (state == eStateInvalid || !event_sp) {
3337 // We timed out and didn't get a stop event...
3338 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3339 }
3340
3341 BroadcastEvent(event_sp);
3342
Mehdi Aminic1edf562016-11-11 04:29:25 +00003343 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003344}
3345
3346Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3347 Error error;
3348
3349 // Check both the public & private states here. If we're hung evaluating an
3350 // expression, for instance, then
3351 // the public state will be stopped, but we still need to interrupt.
3352 if (m_public_state.GetValue() == eStateRunning ||
3353 m_private_state.GetValue() == eStateRunning) {
3354 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003355 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003356 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357
Kate Stoneb9c1b512016-09-06 20:57:50 +00003358 ListenerSP listener_sp(
3359 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3360 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361
Pavel Labath19da1f12015-12-07 12:36:52 +00003362 SendAsyncInterrupt();
3363
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003365 StateType state =
3366 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003367
Pavel Labath19da1f12015-12-07 12:36:52 +00003368 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003369
Kate Stoneb9c1b512016-09-06 20:57:50 +00003370 // If the process exited while we were waiting for it to stop, put the
3371 // exited event into
3372 // the shared pointer passed in and return. Our caller doesn't need to do
3373 // anything else, since
3374 // they don't have a process anymore...
3375
3376 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3377 if (log)
3378 log->Printf("Process::%s() Process exited while waiting to stop.",
3379 __FUNCTION__);
3380 return error;
3381 } else
3382 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3383
3384 if (state != eStateStopped) {
3385 if (log)
3386 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3387 StateAsCString(state));
3388 // If we really couldn't stop the process then we should just error out
3389 // here, but if the
3390 // lower levels just bobbled sending the event and we really are stopped,
3391 // then continue on.
3392 StateType private_state = m_private_state.GetValue();
3393 if (private_state != eStateStopped) {
3394 return Error("Attempt to stop the target in order to detach timed out. "
3395 "State = %s",
3396 StateAsCString(GetState()));
3397 }
3398 }
3399 }
3400 return error;
3401}
3402
3403Error Process::Detach(bool keep_stopped) {
3404 EventSP exit_event_sp;
3405 Error error;
3406 m_destroy_in_process = true;
3407
3408 error = WillDetach();
3409
3410 if (error.Success()) {
3411 if (DetachRequiresHalt()) {
3412 error = StopForDestroyOrDetach(exit_event_sp);
3413 if (!error.Success()) {
3414 m_destroy_in_process = false;
3415 return error;
3416 } else if (exit_event_sp) {
3417 // We shouldn't need to do anything else here. There's no process left
3418 // to detach from...
3419 StopPrivateStateThread();
3420 m_destroy_in_process = false;
3421 return error;
3422 }
3423 }
3424
3425 m_thread_list.DiscardThreadPlans();
3426 DisableAllBreakpointSites();
3427
3428 error = DoDetach(keep_stopped);
3429 if (error.Success()) {
3430 DidDetach();
3431 StopPrivateStateThread();
3432 } else {
3433 return error;
3434 }
3435 }
3436 m_destroy_in_process = false;
3437
3438 // If we exited when we were waiting for a process to stop, then
3439 // forward the event here so we don't lose the event
3440 if (exit_event_sp) {
3441 // Directly broadcast our exited event because we shut down our
3442 // private state thread above
3443 BroadcastEvent(exit_event_sp);
3444 }
3445
3446 // If we have been interrupted (to kill us) in the middle of running, we may
3447 // not end up propagating
3448 // the last events through the event system, in which case we might strand the
3449 // write lock. Unlock
3450 // it here so when we do to tear down the process we don't get an error
3451 // destroying the lock.
3452
3453 m_public_run_lock.SetStopped();
3454 return error;
3455}
3456
3457Error Process::Destroy(bool force_kill) {
3458
3459 // Tell ourselves we are in the process of destroying the process, so that we
3460 // don't do any unnecessary work
3461 // that might hinder the destruction. Remember to set this back to false when
3462 // we are done. That way if the attempt
3463 // failed and the process stays around for some reason it won't be in a
3464 // confused state.
3465
3466 if (force_kill)
3467 m_should_detach = false;
3468
3469 if (GetShouldDetach()) {
3470 // FIXME: This will have to be a process setting:
3471 bool keep_stopped = false;
3472 Detach(keep_stopped);
3473 }
3474
3475 m_destroy_in_process = true;
3476
3477 Error error(WillDestroy());
3478 if (error.Success()) {
3479 EventSP exit_event_sp;
3480 if (DestroyRequiresHalt()) {
3481 error = StopForDestroyOrDetach(exit_event_sp);
3482 }
3483
3484 if (m_public_state.GetValue() != eStateRunning) {
3485 // Ditch all thread plans, and remove all our breakpoints: in case we have
3486 // to restart the target to
3487 // kill it, we don't want it hitting a breakpoint...
3488 // Only do this if we've stopped, however, since if we didn't manage to
3489 // halt it above, then
3490 // we're not going to have much luck doing this now.
3491 m_thread_list.DiscardThreadPlans();
3492 DisableAllBreakpointSites();
3493 }
3494
3495 error = DoDestroy();
3496 if (error.Success()) {
3497 DidDestroy();
3498 StopPrivateStateThread();
3499 }
3500 m_stdio_communication.Disconnect();
3501 m_stdio_communication.StopReadThread();
3502 m_stdin_forward = false;
3503
3504 if (m_process_input_reader) {
3505 m_process_input_reader->SetIsDone(true);
3506 m_process_input_reader->Cancel();
3507 m_process_input_reader.reset();
3508 }
3509
3510 // If we exited when we were waiting for a process to stop, then
3511 // forward the event here so we don't lose the event
3512 if (exit_event_sp) {
3513 // Directly broadcast our exited event because we shut down our
3514 // private state thread above
3515 BroadcastEvent(exit_event_sp);
3516 }
3517
3518 // If we have been interrupted (to kill us) in the middle of running, we may
3519 // not end up propagating
3520 // the last events through the event system, in which case we might strand
3521 // the write lock. Unlock
3522 // it here so when we do to tear down the process we don't get an error
3523 // destroying the lock.
3524 m_public_run_lock.SetStopped();
3525 }
3526
3527 m_destroy_in_process = false;
3528
3529 return error;
3530}
3531
3532Error Process::Signal(int signal) {
3533 Error error(WillSignal());
3534 if (error.Success()) {
3535 error = DoSignal(signal);
3536 if (error.Success())
3537 DidSignal();
3538 }
3539 return error;
3540}
3541
3542void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3543 assert(signals_sp && "null signals_sp");
3544 m_unix_signals_sp = signals_sp;
3545}
3546
3547const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3548 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3549 return m_unix_signals_sp;
3550}
3551
3552lldb::ByteOrder Process::GetByteOrder() const {
3553 return GetTarget().GetArchitecture().GetByteOrder();
3554}
3555
3556uint32_t Process::GetAddressByteSize() const {
3557 return GetTarget().GetArchitecture().GetAddressByteSize();
3558}
3559
3560bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3561 const StateType state =
3562 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3563 bool return_value = true;
3564 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3565 LIBLLDB_LOG_PROCESS));
3566
3567 switch (state) {
3568 case eStateDetached:
3569 case eStateExited:
3570 case eStateUnloaded:
3571 m_stdio_communication.SynchronizeWithReadThread();
3572 m_stdio_communication.Disconnect();
3573 m_stdio_communication.StopReadThread();
3574 m_stdin_forward = false;
3575
3576 LLVM_FALLTHROUGH;
3577 case eStateConnected:
3578 case eStateAttaching:
3579 case eStateLaunching:
3580 // These events indicate changes in the state of the debugging session,
3581 // always report them.
3582 return_value = true;
3583 break;
3584 case eStateInvalid:
3585 // We stopped for no apparent reason, don't report it.
3586 return_value = false;
3587 break;
3588 case eStateRunning:
3589 case eStateStepping:
3590 // If we've started the target running, we handle the cases where we
3591 // are already running and where there is a transition from stopped to
3592 // running differently.
3593 // running -> running: Automatically suppress extra running events
3594 // stopped -> running: Report except when there is one or more no votes
3595 // and no yes votes.
3596 SynchronouslyNotifyStateChanged(state);
3597 if (m_force_next_event_delivery)
3598 return_value = true;
3599 else {
3600 switch (m_last_broadcast_state) {
3601 case eStateRunning:
3602 case eStateStepping:
3603 // We always suppress multiple runnings with no PUBLIC stop in between.
3604 return_value = false;
3605 break;
3606 default:
3607 // TODO: make this work correctly. For now always report
3608 // run if we aren't running so we don't miss any running
3609 // events. If I run the lldb/test/thread/a.out file and
3610 // break at main.cpp:58, run and hit the breakpoints on
3611 // multiple threads, then somehow during the stepping over
3612 // of all breakpoints no run gets reported.
3613
3614 // This is a transition from stop to run.
3615 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3616 case eVoteYes:
3617 case eVoteNoOpinion:
3618 return_value = true;
3619 break;
3620 case eVoteNo:
3621 return_value = false;
3622 break;
3623 }
3624 break;
3625 }
3626 }
3627 break;
3628 case eStateStopped:
3629 case eStateCrashed:
3630 case eStateSuspended:
3631 // We've stopped. First see if we're going to restart the target.
3632 // If we are going to stop, then we always broadcast the event.
3633 // If we aren't going to stop, let the thread plans decide if we're going to
3634 // report this event.
3635 // If no thread has an opinion, we don't report it.
3636
3637 m_stdio_communication.SynchronizeWithReadThread();
3638 RefreshStateAfterStop();
3639 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3640 if (log)
3641 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3642 "interrupt, state: %s",
3643 static_cast<void *>(event_ptr), StateAsCString(state));
3644 // Even though we know we are going to stop, we should let the threads
3645 // have a look at the stop,
3646 // so they can properly set their state.
3647 m_thread_list.ShouldStop(event_ptr);
3648 return_value = true;
3649 } else {
3650 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3651 bool should_resume = false;
3652
3653 // It makes no sense to ask "ShouldStop" if we've already been
3654 // restarted...
3655 // Asking the thread list is also not likely to go well, since we are
3656 // running again.
3657 // So in that case just report the event.
3658
3659 if (!was_restarted)
3660 should_resume = !m_thread_list.ShouldStop(event_ptr);
3661
3662 if (was_restarted || should_resume || m_resume_requested) {
3663 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3664 if (log)
3665 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3666 "%s was_restarted: %i stop_vote: %d.",
3667 should_resume, StateAsCString(state), was_restarted,
3668 stop_vote);
3669
3670 switch (stop_vote) {
3671 case eVoteYes:
3672 return_value = true;
3673 break;
3674 case eVoteNoOpinion:
3675 case eVoteNo:
3676 return_value = false;
3677 break;
3678 }
3679
3680 if (!was_restarted) {
3681 if (log)
3682 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3683 "from state: %s",
3684 static_cast<void *>(event_ptr), StateAsCString(state));
3685 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3686 PrivateResume();
3687 }
3688 } else {
3689 return_value = true;
3690 SynchronouslyNotifyStateChanged(state);
3691 }
3692 }
3693 break;
3694 }
3695
3696 // Forcing the next event delivery is a one shot deal. So reset it here.
3697 m_force_next_event_delivery = false;
3698
3699 // We do some coalescing of events (for instance two consecutive running
3700 // events get coalesced.)
3701 // But we only coalesce against events we actually broadcast. So we use
3702 // m_last_broadcast_state
3703 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3704 // purpose, as was originally done,
3705 // because the PublicState reflects the last event pulled off the queue, and
3706 // there may be several
3707 // events stacked up on the queue unserviced. So the PublicState may not
3708 // reflect the last broadcasted event
3709 // yet. m_last_broadcast_state gets updated here.
3710
3711 if (return_value)
3712 m_last_broadcast_state = state;
3713
3714 if (log)
3715 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3716 "broadcast state: %s - %s",
3717 static_cast<void *>(event_ptr), StateAsCString(state),
3718 StateAsCString(m_last_broadcast_state),
3719 return_value ? "YES" : "NO");
3720 return return_value;
3721}
3722
3723bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3724 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3725
3726 bool already_running = PrivateStateThreadIsValid();
3727 if (log)
3728 log->Printf("Process::%s()%s ", __FUNCTION__,
3729 already_running ? " already running"
3730 : " starting private state thread");
3731
3732 if (!is_secondary_thread && already_running)
3733 return true;
3734
3735 // Create a thread that watches our internal state and controls which
3736 // events make it to clients (into the DCProcess event queue).
3737 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003738 uint32_t max_len = llvm::get_max_thread_name_length();
3739 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003740 // On platforms with abbreviated thread name lengths, choose thread names
3741 // that fit within the limit.
3742 if (already_running)
3743 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3744 else
3745 snprintf(thread_name, sizeof(thread_name), "intern-state");
3746 } else {
3747 if (already_running)
3748 snprintf(thread_name, sizeof(thread_name),
3749 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3750 GetID());
3751 else
3752 snprintf(thread_name, sizeof(thread_name),
3753 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3754 }
3755
3756 // Create the private state thread, and start it running.
3757 PrivateStateThreadArgs *args_ptr =
3758 new PrivateStateThreadArgs(this, is_secondary_thread);
3759 m_private_state_thread =
3760 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3761 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3762 if (m_private_state_thread.IsJoinable()) {
3763 ResumePrivateStateThread();
3764 return true;
3765 } else
3766 return false;
3767}
3768
3769void Process::PausePrivateStateThread() {
3770 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3771}
3772
3773void Process::ResumePrivateStateThread() {
3774 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3775}
3776
3777void Process::StopPrivateStateThread() {
3778 if (m_private_state_thread.IsJoinable())
3779 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3780 else {
3781 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3782 if (log)
3783 log->Printf(
3784 "Went to stop the private state thread, but it was already invalid.");
3785 }
3786}
3787
3788void Process::ControlPrivateStateThread(uint32_t signal) {
3789 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3790
3791 assert(signal == eBroadcastInternalStateControlStop ||
3792 signal == eBroadcastInternalStateControlPause ||
3793 signal == eBroadcastInternalStateControlResume);
3794
3795 if (log)
3796 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3797
3798 // Signal the private state thread
3799 if (m_private_state_thread.IsJoinable()) {
3800 // Broadcast the event.
3801 // It is important to do this outside of the if below, because
3802 // it's possible that the thread state is invalid but that the
3803 // thread is waiting on a control event instead of simply being
3804 // on its way out (this should not happen, but it apparently can).
3805 if (log)
3806 log->Printf("Sending control event of type: %d.", signal);
3807 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3808 m_private_state_control_broadcaster.BroadcastEvent(signal,
3809 event_receipt_sp);
3810
3811 // Wait for the event receipt or for the private state thread to exit
3812 bool receipt_received = false;
3813 if (PrivateStateThreadIsValid()) {
3814 while (!receipt_received) {
3815 bool timed_out = false;
3816 // Check for a receipt for 2 seconds and then check if the private state
3817 // thread is still around.
3818 receipt_received = event_receipt_sp->WaitForEventReceived(
3819 std::chrono::seconds(2), &timed_out);
3820 if (!receipt_received) {
3821 // Check if the private state thread is still around. If it isn't then
3822 // we are done waiting
3823 if (!PrivateStateThreadIsValid())
3824 break; // Private state thread exited or is exiting, we are done
3825 }
3826 }
3827 }
3828
3829 if (signal == eBroadcastInternalStateControlStop) {
3830 thread_result_t result = NULL;
3831 m_private_state_thread.Join(&result);
3832 m_private_state_thread.Reset();
3833 }
3834 } else {
3835 if (log)
3836 log->Printf(
3837 "Private state thread already dead, no need to signal it to stop.");
3838 }
3839}
3840
3841void Process::SendAsyncInterrupt() {
3842 if (PrivateStateThreadIsValid())
3843 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3844 nullptr);
3845 else
3846 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3847}
3848
3849void Process::HandlePrivateEvent(EventSP &event_sp) {
3850 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3851 m_resume_requested = false;
3852
3853 const StateType new_state =
3854 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3855
3856 // First check to see if anybody wants a shot at this event:
3857 if (m_next_event_action_ap) {
3858 NextEventAction::EventActionResult action_result =
3859 m_next_event_action_ap->PerformAction(event_sp);
3860 if (log)
3861 log->Printf("Ran next event action, result was %d.", action_result);
3862
3863 switch (action_result) {
3864 case NextEventAction::eEventActionSuccess:
3865 SetNextEventAction(nullptr);
3866 break;
3867
3868 case NextEventAction::eEventActionRetry:
3869 break;
3870
3871 case NextEventAction::eEventActionExit:
3872 // Handle Exiting Here. If we already got an exited event,
3873 // we should just propagate it. Otherwise, swallow this event,
3874 // and set our state to exit so the next event will kill us.
3875 if (new_state != eStateExited) {
3876 // FIXME: should cons up an exited event, and discard this one.
3877 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3878 SetNextEventAction(nullptr);
3879 return;
3880 }
3881 SetNextEventAction(nullptr);
3882 break;
3883 }
3884 }
3885
3886 // See if we should broadcast this state to external clients?
3887 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3888
3889 if (should_broadcast) {
3890 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3891 if (log) {
3892 log->Printf("Process::%s (pid = %" PRIu64
3893 ") broadcasting new state %s (old state %s) to %s",
3894 __FUNCTION__, GetID(), StateAsCString(new_state),
3895 StateAsCString(GetState()),
3896 is_hijacked ? "hijacked" : "public");
3897 }
3898 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3899 if (StateIsRunningState(new_state)) {
3900 // Only push the input handler if we aren't fowarding events,
3901 // as this means the curses GUI is in use...
3902 // Or don't push it if we are launching since it will come up stopped.
3903 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3904 new_state != eStateLaunching && new_state != eStateAttaching) {
3905 PushProcessIOHandler();
3906 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3907 eBroadcastAlways);
3908 if (log)
3909 log->Printf("Process::%s updated m_iohandler_sync to %d",
3910 __FUNCTION__, m_iohandler_sync.GetValue());
3911 }
3912 } else if (StateIsStoppedState(new_state, false)) {
3913 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3914 // If the lldb_private::Debugger is handling the events, we don't
3915 // want to pop the process IOHandler here, we want to do it when
3916 // we receive the stopped event so we can carefully control when
3917 // the process IOHandler is popped because when we stop we want to
3918 // display some text stating how and why we stopped, then maybe some
3919 // process/thread/frame info, and then we want the "(lldb) " prompt
3920 // to show up. If we pop the process IOHandler here, then we will
3921 // cause the command interpreter to become the top IOHandler after
3922 // the process pops off and it will update its prompt right away...
3923 // See the Debugger.cpp file where it calls the function as
3924 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3925 // Otherwise we end up getting overlapping "(lldb) " prompts and
3926 // garbled output.
3927 //
3928 // If we aren't handling the events in the debugger (which is indicated
3929 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3930 // are hijacked, then we always pop the process IO handler manually.
3931 // Hijacking happens when the internal process state thread is running
3932 // thread plans, or when commands want to run in synchronous mode
3933 // and they call "process->WaitForProcessToStop()". An example of
3934 // something
3935 // that will hijack the events is a simple expression:
3936 //
3937 // (lldb) expr (int)puts("hello")
3938 //
3939 // This will cause the internal process state thread to resume and halt
3940 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3941 // events) and we do need the IO handler to be pushed and popped
3942 // correctly.
3943
3944 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3945 PopProcessIOHandler();
3946 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003947 }
3948
3949 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003950 } else {
3951 if (log) {
3952 log->Printf(
3953 "Process::%s (pid = %" PRIu64
3954 ") suppressing state %s (old state %s): should_broadcast == false",
3955 __FUNCTION__, GetID(), StateAsCString(new_state),
3956 StateAsCString(GetState()));
3957 }
3958 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003959}
3960
Kate Stoneb9c1b512016-09-06 20:57:50 +00003961Error Process::HaltPrivate() {
3962 EventSP event_sp;
3963 Error error(WillHalt());
3964 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003965 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003966
3967 // Ask the process subclass to actually halt our process
3968 bool caused_stop;
3969 error = DoHalt(caused_stop);
3970
3971 DidHalt();
3972 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003973}
3974
Kate Stoneb9c1b512016-09-06 20:57:50 +00003975thread_result_t Process::PrivateStateThread(void *arg) {
3976 std::unique_ptr<PrivateStateThreadArgs> args_up(
3977 static_cast<PrivateStateThreadArgs *>(arg));
3978 thread_result_t result =
3979 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3980 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981}
3982
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3984 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003985
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3987 if (log)
3988 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3989 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003990
Kate Stoneb9c1b512016-09-06 20:57:50 +00003991 bool exit_now = false;
3992 bool interrupt_requested = false;
3993 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003994 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003995 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003996 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3997 if (log)
3998 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3999 ") got a control event: %d",
4000 __FUNCTION__, static_cast<void *>(this), GetID(),
4001 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004002
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003 switch (event_sp->GetType()) {
4004 case eBroadcastInternalStateControlStop:
4005 exit_now = true;
4006 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004007
Kate Stoneb9c1b512016-09-06 20:57:50 +00004008 case eBroadcastInternalStateControlPause:
4009 control_only = true;
4010 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012 case eBroadcastInternalStateControlResume:
4013 control_only = false;
4014 break;
4015 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016
Kate Stoneb9c1b512016-09-06 20:57:50 +00004017 continue;
4018 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4019 if (m_public_state.GetValue() == eStateAttaching) {
4020 if (log)
4021 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4022 ") woke up with an interrupt while attaching - "
4023 "forwarding interrupt.",
4024 __FUNCTION__, static_cast<void *>(this), GetID());
4025 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4026 } else if (StateIsRunningState(m_last_broadcast_state)) {
4027 if (log)
4028 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4029 ") woke up with an interrupt - Halting.",
4030 __FUNCTION__, static_cast<void *>(this), GetID());
4031 Error error = HaltPrivate();
4032 if (error.Fail() && log)
4033 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4034 ") failed to halt the process: %s",
4035 __FUNCTION__, static_cast<void *>(this), GetID(),
4036 error.AsCString());
4037 // Halt should generate a stopped event. Make a note of the fact that we
4038 // were
4039 // doing the interrupt, so we can set the interrupted flag after we
4040 // receive the
4041 // event. We deliberately set this to true even if HaltPrivate failed,
4042 // so that we
4043 // can interrupt on the next natural stop.
4044 interrupt_requested = true;
4045 } else {
4046 // This can happen when someone (e.g. Process::Halt) sees that we are
4047 // running and
4048 // sends an interrupt request, but the process actually stops before we
4049 // receive
4050 // it. In that case, we can just ignore the request. We use
4051 // m_last_broadcast_state, because the Stopped event may not have been
4052 // popped of
4053 // the event queue yet, which is when the public state gets updated.
4054 if (log)
4055 log->Printf(
4056 "Process::%s ignoring interrupt as we have already stopped.",
4057 __FUNCTION__);
4058 }
4059 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004060 }
4061
Kate Stoneb9c1b512016-09-06 20:57:50 +00004062 const StateType internal_state =
4063 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004064
Kate Stoneb9c1b512016-09-06 20:57:50 +00004065 if (internal_state != eStateInvalid) {
4066 if (m_clear_thread_plans_on_stop &&
4067 StateIsStoppedState(internal_state, true)) {
4068 m_clear_thread_plans_on_stop = false;
4069 m_thread_list.DiscardThreadPlans();
4070 }
4071
4072 if (interrupt_requested) {
4073 if (StateIsStoppedState(internal_state, true)) {
4074 // We requested the interrupt, so mark this as such in the stop event
4075 // so
4076 // clients can tell an interrupted process from a natural stop
4077 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4078 interrupt_requested = false;
4079 } else if (log) {
4080 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4081 "state '%s' received.",
4082 __FUNCTION__, StateAsCString(internal_state));
4083 }
4084 }
4085
4086 HandlePrivateEvent(event_sp);
4087 }
4088
4089 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4090 internal_state == eStateDetached) {
4091 if (log)
4092 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4093 ") about to exit with internal state %s...",
4094 __FUNCTION__, static_cast<void *>(this), GetID(),
4095 StateAsCString(internal_state));
4096
4097 break;
4098 }
4099 }
4100
4101 // Verify log is still enabled before attempting to write to it...
4102 if (log)
4103 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4104 __FUNCTION__, static_cast<void *>(this), GetID());
4105
4106 // If we are a secondary thread, then the primary thread we are working for
4107 // will have already
4108 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4109 // don't
4110 // try to change it on the way out.
4111 if (!is_secondary_thread)
4112 m_public_run_lock.SetStopped();
4113 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004114}
4115
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004116//------------------------------------------------------------------
4117// Process Event Data
4118//------------------------------------------------------------------
4119
Kate Stoneb9c1b512016-09-06 20:57:50 +00004120Process::ProcessEventData::ProcessEventData()
4121 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4122 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004123
Kate Stoneb9c1b512016-09-06 20:57:50 +00004124Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4125 StateType state)
4126 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4127 m_update_state(0), m_interrupted(false) {
4128 if (process_sp)
4129 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004130}
4131
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004132Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004133
Kate Stoneb9c1b512016-09-06 20:57:50 +00004134const ConstString &Process::ProcessEventData::GetFlavorString() {
4135 static ConstString g_flavor("Process::ProcessEventData");
4136 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004137}
4138
Kate Stoneb9c1b512016-09-06 20:57:50 +00004139const ConstString &Process::ProcessEventData::GetFlavor() const {
4140 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004141}
4142
Kate Stoneb9c1b512016-09-06 20:57:50 +00004143void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4144 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004145
Kate Stoneb9c1b512016-09-06 20:57:50 +00004146 if (!process_sp)
4147 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004148
Kate Stoneb9c1b512016-09-06 20:57:50 +00004149 // This function gets called twice for each event, once when the event gets
4150 // pulled
4151 // off of the private process event queue, and then any number of times, first
4152 // when it gets pulled off of
4153 // the public event queue, then other times when we're pretending that this is
4154 // where we stopped at the
4155 // end of expression evaluation. m_update_state is used to distinguish these
4156 // three cases; it is 0 when we're just pulling it off for private handling,
4157 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4158 // command handling then.
4159 if (m_update_state != 1)
4160 return;
4161
4162 process_sp->SetPublicState(
4163 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4164
Jason Molendab3a3cd12016-12-08 06:27:29 +00004165 if (m_state == eStateStopped && !m_restarted) {
4166 // Let process subclasses know we are about to do a public stop and
4167 // do anything they might need to in order to speed up register and
4168 // memory accesses.
4169 process_sp->WillPublicStop();
4170 }
4171
Kate Stoneb9c1b512016-09-06 20:57:50 +00004172 // If this is a halt event, even if the halt stopped with some reason other
4173 // than a plain interrupt (e.g. we had
4174 // already stopped for a breakpoint when the halt request came through) don't
4175 // do the StopInfo actions, as they may
4176 // end up restarting the process.
4177 if (m_interrupted)
4178 return;
4179
4180 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4181 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004182 ThreadList &curr_thread_list = process_sp->GetThreadList();
4183 uint32_t num_threads = curr_thread_list.GetSize();
4184 uint32_t idx;
4185
4186 // The actions might change one of the thread's stop_info's opinions about
4187 // whether we should
4188 // stop the process, so we need to query that as we go.
4189
4190 // One other complication here, is that we try to catch any case where the
4191 // target has run (except for expressions)
4192 // and immediately exit, but if we get that wrong (which is possible) then
4193 // the thread list might have changed, and
4194 // that would cause our iteration here to crash. We could make a copy of
4195 // the thread list, but we'd really like
4196 // to also know if it has changed at all, so we make up a vector of the
4197 // thread ID's and check what we get back
4198 // against this list & bag out if anything differs.
4199 std::vector<uint32_t> thread_index_array(num_threads);
4200 for (idx = 0; idx < num_threads; ++idx)
4201 thread_index_array[idx] =
4202 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4203
4204 // Use this to track whether we should continue from here. We will only
4205 // continue the target running if
4206 // no thread says we should stop. Of course if some thread's PerformAction
4207 // actually sets the target running,
4208 // then it doesn't matter what the other threads say...
4209
4210 bool still_should_stop = false;
4211
4212 // Sometimes - for instance if we have a bug in the stub we are talking to,
4213 // we stop but no thread has a
4214 // valid stop reason. In that case we should just stop, because we have no
4215 // way of telling what the right
4216 // thing to do is, and it's better to let the user decide than continue
4217 // behind their backs.
4218
4219 bool does_anybody_have_an_opinion = false;
4220
4221 for (idx = 0; idx < num_threads; ++idx) {
4222 curr_thread_list = process_sp->GetThreadList();
4223 if (curr_thread_list.GetSize() != num_threads) {
4224 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4225 LIBLLDB_LOG_PROCESS));
4226 if (log)
4227 log->Printf(
4228 "Number of threads changed from %u to %u while processing event.",
4229 num_threads, curr_thread_list.GetSize());
4230 break;
4231 }
4232
4233 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4234
4235 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4236 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4237 LIBLLDB_LOG_PROCESS));
4238 if (log)
4239 log->Printf("The thread at position %u changed from %u to %u while "
4240 "processing event.",
4241 idx, thread_index_array[idx], thread_sp->GetIndexID());
4242 break;
4243 }
4244
4245 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4246 if (stop_info_sp && stop_info_sp->IsValid()) {
4247 does_anybody_have_an_opinion = true;
4248 bool this_thread_wants_to_stop;
4249 if (stop_info_sp->GetOverrideShouldStop()) {
4250 this_thread_wants_to_stop =
4251 stop_info_sp->GetOverriddenShouldStopValue();
4252 } else {
4253 stop_info_sp->PerformAction(event_ptr);
4254 // The stop action might restart the target. If it does, then we want
4255 // to mark that in the
4256 // event so that whoever is receiving it will know to wait for the
4257 // running event and reflect
4258 // that state appropriately.
4259 // We also need to stop processing actions, since they aren't
4260 // expecting the target to be running.
4261
4262 // FIXME: we might have run.
4263 if (stop_info_sp->HasTargetRunSinceMe()) {
4264 SetRestarted(true);
4265 break;
4266 }
4267
4268 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004269 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004270
4271 if (!still_should_stop)
4272 still_should_stop = this_thread_wants_to_stop;
4273 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004274 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004275
4276 if (!GetRestarted()) {
4277 if (!still_should_stop && does_anybody_have_an_opinion) {
4278 // We've been asked to continue, so do that here.
4279 SetRestarted(true);
4280 // Use the public resume method here, since this is just
4281 // extending a public resume.
4282 process_sp->PrivateResume();
4283 } else {
4284 // If we didn't restart, run the Stop Hooks here:
4285 // They might also restart the target, so watch for that.
4286 process_sp->GetTarget().RunStopHooks();
4287 if (process_sp->GetPrivateState() == eStateRunning)
4288 SetRestarted(true);
4289 }
4290 }
4291 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004292}
4293
Kate Stoneb9c1b512016-09-06 20:57:50 +00004294void Process::ProcessEventData::Dump(Stream *s) const {
4295 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004296
Kate Stoneb9c1b512016-09-06 20:57:50 +00004297 if (process_sp)
4298 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4299 static_cast<void *>(process_sp.get()), process_sp->GetID());
4300 else
4301 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004302
Kate Stoneb9c1b512016-09-06 20:57:50 +00004303 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004304}
4305
4306const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004307Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4308 if (event_ptr) {
4309 const EventData *event_data = event_ptr->GetData();
4310 if (event_data &&
4311 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4312 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4313 }
4314 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004315}
4316
4317ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004318Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4319 ProcessSP process_sp;
4320 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4321 if (data)
4322 process_sp = data->GetProcessSP();
4323 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004324}
4325
Kate Stoneb9c1b512016-09-06 20:57:50 +00004326StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4327 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4328 if (data == nullptr)
4329 return eStateInvalid;
4330 else
4331 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004332}
4333
Kate Stoneb9c1b512016-09-06 20:57:50 +00004334bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4335 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4336 if (data == nullptr)
4337 return false;
4338 else
4339 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004340}
4341
Kate Stoneb9c1b512016-09-06 20:57:50 +00004342void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4343 bool new_value) {
4344 ProcessEventData *data =
4345 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4346 if (data != nullptr)
4347 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348}
4349
Jim Ingham0161b492013-02-09 01:29:05 +00004350size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004351Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4352 ProcessEventData *data =
4353 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4354 if (data != nullptr)
4355 return data->GetNumRestartedReasons();
4356 else
4357 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004358}
4359
4360const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004361Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4362 size_t idx) {
4363 ProcessEventData *data =
4364 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4365 if (data != nullptr)
4366 return data->GetRestartedReasonAtIndex(idx);
4367 else
4368 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004369}
4370
Kate Stoneb9c1b512016-09-06 20:57:50 +00004371void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4372 const char *reason) {
4373 ProcessEventData *data =
4374 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4375 if (data != nullptr)
4376 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004377}
4378
Kate Stoneb9c1b512016-09-06 20:57:50 +00004379bool Process::ProcessEventData::GetInterruptedFromEvent(
4380 const Event *event_ptr) {
4381 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4382 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004383 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004384 else
4385 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004386}
4387
Kate Stoneb9c1b512016-09-06 20:57:50 +00004388void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4389 bool new_value) {
4390 ProcessEventData *data =
4391 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4392 if (data != nullptr)
4393 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004394}
4395
Kate Stoneb9c1b512016-09-06 20:57:50 +00004396bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4397 ProcessEventData *data =
4398 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4399 if (data) {
4400 data->SetUpdateStateOnRemoval();
4401 return true;
4402 }
4403 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004404}
4405
Kate Stoneb9c1b512016-09-06 20:57:50 +00004406lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4407
4408void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4409 exe_ctx.SetTargetPtr(&GetTarget());
4410 exe_ctx.SetProcessPtr(this);
4411 exe_ctx.SetThreadPtr(nullptr);
4412 exe_ctx.SetFramePtr(nullptr);
4413}
4414
4415// uint32_t
4416// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4417// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004418//{
4419// return 0;
4420//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004421//
4422// ArchSpec
4423// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004424//{
4425// return Host::GetArchSpecForExistingProcess (pid);
4426//}
4427//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004428// ArchSpec
4429// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004430//{
4431// return Host::GetArchSpecForExistingProcess (process_name);
4432//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004433
Kate Stoneb9c1b512016-09-06 20:57:50 +00004434void Process::AppendSTDOUT(const char *s, size_t len) {
4435 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4436 m_stdout_data.append(s, len);
4437 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4438 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004439}
4440
Kate Stoneb9c1b512016-09-06 20:57:50 +00004441void Process::AppendSTDERR(const char *s, size_t len) {
4442 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4443 m_stderr_data.append(s, len);
4444 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4445 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004446}
4447
Kate Stoneb9c1b512016-09-06 20:57:50 +00004448void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4449 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4450 m_profile_data.push_back(one_profile_data);
4451 BroadcastEventIfUnique(eBroadcastBitProfileData,
4452 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004453}
4454
Kate Stoneb9c1b512016-09-06 20:57:50 +00004455void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4456 const StructuredDataPluginSP &plugin_sp) {
4457 BroadcastEvent(
4458 eBroadcastBitStructuredData,
4459 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004460}
4461
4462StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004463Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4464 auto find_it = m_structured_data_plugin_map.find(type_name);
4465 if (find_it != m_structured_data_plugin_map.end())
4466 return find_it->second;
4467 else
4468 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004469}
4470
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4472 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4473 if (m_profile_data.empty())
4474 return 0;
4475
4476 std::string &one_profile_data = m_profile_data.front();
4477 size_t bytes_available = one_profile_data.size();
4478 if (bytes_available > 0) {
4479 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4480 if (log)
4481 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4482 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4483 if (bytes_available > buf_size) {
4484 memcpy(buf, one_profile_data.c_str(), buf_size);
4485 one_profile_data.erase(0, buf_size);
4486 bytes_available = buf_size;
4487 } else {
4488 memcpy(buf, one_profile_data.c_str(), bytes_available);
4489 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004490 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004491 }
4492 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004493}
4494
Greg Clayton93e86192011-11-13 04:45:22 +00004495//------------------------------------------------------------------
4496// Process STDIO
4497//------------------------------------------------------------------
4498
Kate Stoneb9c1b512016-09-06 20:57:50 +00004499size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4500 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4501 size_t bytes_available = m_stdout_data.size();
4502 if (bytes_available > 0) {
4503 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4504 if (log)
4505 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4506 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4507 if (bytes_available > buf_size) {
4508 memcpy(buf, m_stdout_data.c_str(), buf_size);
4509 m_stdout_data.erase(0, buf_size);
4510 bytes_available = buf_size;
4511 } else {
4512 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4513 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004515 }
4516 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004517}
4518
Kate Stoneb9c1b512016-09-06 20:57:50 +00004519size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4520 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4521 size_t bytes_available = m_stderr_data.size();
4522 if (bytes_available > 0) {
4523 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4524 if (log)
4525 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4526 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4527 if (bytes_available > buf_size) {
4528 memcpy(buf, m_stderr_data.c_str(), buf_size);
4529 m_stderr_data.erase(0, buf_size);
4530 bytes_available = buf_size;
4531 } else {
4532 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4533 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004534 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004535 }
4536 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004537}
4538
Kate Stoneb9c1b512016-09-06 20:57:50 +00004539void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4540 size_t src_len) {
4541 Process *process = (Process *)baton;
4542 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004543}
4544
Kate Stoneb9c1b512016-09-06 20:57:50 +00004545class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004546public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004547 IOHandlerProcessSTDIO(Process *process, int write_fd)
4548 : IOHandler(process->GetTarget().GetDebugger(),
4549 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004550 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004551 m_pipe.CreateNew(false);
4552 m_read_file.SetDescriptor(GetInputFD(), false);
4553 }
4554
4555 ~IOHandlerProcessSTDIO() override = default;
4556
4557 // Each IOHandler gets to run until it is done. It should read data
4558 // from the "in" and place output into "out" and "err and return
4559 // when done.
4560 void Run() override {
4561 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4562 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4563 SetIsDone(true);
4564 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004565 }
4566
Kate Stoneb9c1b512016-09-06 20:57:50 +00004567 SetIsDone(false);
4568 const int read_fd = m_read_file.GetDescriptor();
4569 TerminalState terminal_state;
4570 terminal_state.Save(read_fd, false);
4571 Terminal terminal(read_fd);
4572 terminal.SetCanonical(false);
4573 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004574// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004575#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004576 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4577 m_is_running = true;
4578 while (!GetIsDone()) {
4579 SelectHelper select_helper;
4580 select_helper.FDSetRead(read_fd);
4581 select_helper.FDSetRead(pipe_read_fd);
4582 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004583
Kate Stoneb9c1b512016-09-06 20:57:50 +00004584 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004585 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004586 } else {
4587 char ch = 0;
4588 size_t n;
4589 if (select_helper.FDIsSetRead(read_fd)) {
4590 n = 1;
4591 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4592 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4593 SetIsDone(true);
4594 } else
4595 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004596 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004597 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4598 size_t bytes_read;
4599 // Consume the interrupt byte
4600 Error error = m_pipe.Read(&ch, 1, bytes_read);
4601 if (error.Success()) {
4602 switch (ch) {
4603 case 'q':
4604 SetIsDone(true);
4605 break;
4606 case 'i':
4607 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004608 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004609 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004611 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004613 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004614 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004615 m_is_running = false;
4616#endif
4617 terminal_state.Restore();
4618 }
4619
4620 void Cancel() override {
4621 SetIsDone(true);
4622 // Only write to our pipe to cancel if we are in
4623 // IOHandlerProcessSTDIO::Run().
4624 // We can end up with a python command that is being run from the command
4625 // interpreter:
4626 //
4627 // (lldb) step_process_thousands_of_times
4628 //
4629 // In this case the command interpreter will be in the middle of handling
4630 // the command and if the process pushes and pops the IOHandler thousands
4631 // of times, we can end up writing to m_pipe without ever consuming the
4632 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4633 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4634 if (m_is_running) {
4635 char ch = 'q'; // Send 'q' for quit
4636 size_t bytes_written = 0;
4637 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004638 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004639 }
4640
4641 bool Interrupt() override {
4642 // Do only things that are safe to do in an interrupt context (like in
4643 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4644 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4645 // that was written to the pipe and then call
4646 // m_process->SendAsyncInterrupt()
4647 // from a much safer location in code.
4648 if (m_active) {
4649 char ch = 'i'; // Send 'i' for interrupt
4650 size_t bytes_written = 0;
4651 Error result = m_pipe.Write(&ch, 1, bytes_written);
4652 return result.Success();
4653 } else {
4654 // This IOHandler might be pushed on the stack, but not being run
4655 // currently
4656 // so do the right thing if we aren't actively watching for STDIN by
4657 // sending
4658 // the interrupt to the process. Otherwise the write to the pipe above
4659 // would
4660 // do nothing. This can happen when the command interpreter is running and
4661 // gets a "expression ...". It will be on the IOHandler thread and sending
4662 // the input is complete to the delegate which will cause the expression
4663 // to
4664 // run, which will push the process IO handler, but not run it.
4665
4666 if (StateIsRunningState(m_process->GetState())) {
4667 m_process->SendAsyncInterrupt();
4668 return true;
4669 }
4670 }
4671 return false;
4672 }
4673
4674 void GotEOF() override {}
4675
Greg Clayton44d93782014-01-27 23:43:24 +00004676protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004677 Process *m_process;
4678 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4679 File m_write_file; // Write to this file (usually the master pty for getting
4680 // io to debuggee)
4681 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004682 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004683};
4684
Kate Stoneb9c1b512016-09-06 20:57:50 +00004685void Process::SetSTDIOFileDescriptor(int fd) {
4686 // First set up the Read Thread for reading/handling process I/O
4687
4688 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4689 new ConnectionFileDescriptor(fd, true));
4690
4691 if (conn_ap) {
4692 m_stdio_communication.SetConnection(conn_ap.release());
4693 if (m_stdio_communication.IsConnected()) {
4694 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4695 STDIOReadThreadBytesReceived, this);
4696 m_stdio_communication.StartReadThread();
4697
4698 // Now read thread is set up, set up input reader.
4699
4700 if (!m_process_input_reader)
4701 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004702 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004703 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004704}
4705
Kate Stoneb9c1b512016-09-06 20:57:50 +00004706bool Process::ProcessIOHandlerIsActive() {
4707 IOHandlerSP io_handler_sp(m_process_input_reader);
4708 if (io_handler_sp)
4709 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4710 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004711}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712bool Process::PushProcessIOHandler() {
4713 IOHandlerSP io_handler_sp(m_process_input_reader);
4714 if (io_handler_sp) {
4715 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4716 if (log)
4717 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004718
Kate Stoneb9c1b512016-09-06 20:57:50 +00004719 io_handler_sp->SetIsDone(false);
4720 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4721 return true;
4722 }
4723 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004724}
4725
Kate Stoneb9c1b512016-09-06 20:57:50 +00004726bool Process::PopProcessIOHandler() {
4727 IOHandlerSP io_handler_sp(m_process_input_reader);
4728 if (io_handler_sp)
4729 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4730 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004731}
4732
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004733// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004735
Kate Stoneb9c1b512016-09-06 20:57:50 +00004736void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004737
Kate Stoneb9c1b512016-09-06 20:57:50 +00004738namespace {
4739// RestorePlanState is used to record the "is private", "is master" and "okay to
4740// discard" fields of
4741// the plan we are running, and reset it on Clean or on destruction.
4742// It will only reset the state once, so you can call Clean and then monkey with
4743// the state and it
4744// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004745
Kate Stoneb9c1b512016-09-06 20:57:50 +00004746class RestorePlanState {
4747public:
4748 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4749 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4750 if (m_thread_plan_sp) {
4751 m_private = m_thread_plan_sp->GetPrivate();
4752 m_is_master = m_thread_plan_sp->IsMasterPlan();
4753 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4754 }
4755 }
4756
4757 ~RestorePlanState() { Clean(); }
4758
4759 void Clean() {
4760 if (!m_already_reset && m_thread_plan_sp) {
4761 m_already_reset = true;
4762 m_thread_plan_sp->SetPrivate(m_private);
4763 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4764 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4765 }
4766 }
4767
4768private:
4769 lldb::ThreadPlanSP m_thread_plan_sp;
4770 bool m_already_reset;
4771 bool m_private;
4772 bool m_is_master;
4773 bool m_okay_to_discard;
4774};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004775} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004776
Pavel Labath2ce22162016-12-01 10:57:30 +00004777static microseconds
4778GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4779 const milliseconds default_one_thread_timeout(250);
4780
4781 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004782 if (!options.GetTimeout()) {
4783 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4784 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004785 }
4786
4787 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004788 if (options.GetOneThreadTimeout())
4789 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004790
4791 // Otherwise use half the total timeout, bounded by the
4792 // default_one_thread_timeout.
4793 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004794 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004795}
4796
4797static Timeout<std::micro>
4798GetExpressionTimeout(const EvaluateExpressionOptions &options,
4799 bool before_first_timeout) {
4800 // If we are going to run all threads the whole time, or if we are only
4801 // going to run one thread, we can just return the overall timeout.
4802 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004803 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004804
4805 if (before_first_timeout)
4806 return GetOneThreadExpressionTimeout(options);
4807
Pavel Labath43d35412016-12-06 11:24:51 +00004808 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004809 return llvm::None;
4810 else
Pavel Labath43d35412016-12-06 11:24:51 +00004811 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004812}
4813
Jim Ingham1624a2d2014-05-05 02:26:40 +00004814ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004815Process::RunThreadPlan(ExecutionContext &exe_ctx,
4816 lldb::ThreadPlanSP &thread_plan_sp,
4817 const EvaluateExpressionOptions &options,
4818 DiagnosticManager &diagnostic_manager) {
4819 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004820
Kate Stoneb9c1b512016-09-06 20:57:50 +00004821 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4822
4823 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004824 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004825 eDiagnosticSeverityError,
4826 "RunThreadPlan called with empty thread plan.");
4827 return eExpressionSetupError;
4828 }
4829
4830 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004831 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004832 eDiagnosticSeverityError,
4833 "RunThreadPlan called with an invalid thread plan.");
4834 return eExpressionSetupError;
4835 }
4836
4837 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004838 diagnostic_manager.PutString(eDiagnosticSeverityError,
4839 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004840 return eExpressionSetupError;
4841 }
4842
4843 Thread *thread = exe_ctx.GetThreadPtr();
4844 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004845 diagnostic_manager.PutString(eDiagnosticSeverityError,
4846 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004847 return eExpressionSetupError;
4848 }
4849
4850 // We need to change some of the thread plan attributes for the thread plan
4851 // runner. This will restore them
4852 // when we are done:
4853
4854 RestorePlanState thread_plan_restorer(thread_plan_sp);
4855
4856 // We rely on the thread plan we are running returning "PlanCompleted" if when
4857 // it successfully completes.
4858 // For that to be true the plan can't be private - since private plans
4859 // suppress themselves in the
4860 // GetCompletedPlan call.
4861
4862 thread_plan_sp->SetPrivate(false);
4863
4864 // The plans run with RunThreadPlan also need to be terminal master plans or
4865 // when they are done we will end
4866 // up asking the plan above us whether we should stop, which may give the
4867 // wrong answer.
4868
4869 thread_plan_sp->SetIsMasterPlan(true);
4870 thread_plan_sp->SetOkayToDiscard(false);
4871
4872 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004873 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004874 eDiagnosticSeverityError,
4875 "RunThreadPlan called while the private state was not stopped.");
4876 return eExpressionSetupError;
4877 }
4878
4879 // Save the thread & frame from the exe_ctx for restoration after we run
4880 const uint32_t thread_idx_id = thread->GetIndexID();
4881 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4882 if (!selected_frame_sp) {
4883 thread->SetSelectedFrame(nullptr);
4884 selected_frame_sp = thread->GetSelectedFrame();
4885 if (!selected_frame_sp) {
4886 diagnostic_manager.Printf(
4887 eDiagnosticSeverityError,
4888 "RunThreadPlan called without a selected frame on thread %d",
4889 thread_idx_id);
4890 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004891 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004892 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004893
Pavel Labath2ce22162016-12-01 10:57:30 +00004894 // Make sure the timeout values make sense. The one thread timeout needs to be
4895 // smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004896 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4897 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004898 diagnostic_manager.PutString(eDiagnosticSeverityError,
4899 "RunThreadPlan called with one thread "
4900 "timeout greater than total timeout");
4901 return eExpressionSetupError;
4902 }
4903
Kate Stoneb9c1b512016-09-06 20:57:50 +00004904 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004905
Kate Stoneb9c1b512016-09-06 20:57:50 +00004906 // N.B. Running the target may unset the currently selected thread and frame.
4907 // We don't want to do that either,
4908 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004909
Kate Stoneb9c1b512016-09-06 20:57:50 +00004910 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004911
Kate Stoneb9c1b512016-09-06 20:57:50 +00004912 uint32_t selected_tid;
4913 StackID selected_stack_id;
4914 if (selected_thread_sp) {
4915 selected_tid = selected_thread_sp->GetIndexID();
4916 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4917 } else {
4918 selected_tid = LLDB_INVALID_THREAD_ID;
4919 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004920
Kate Stoneb9c1b512016-09-06 20:57:50 +00004921 HostThread backup_private_state_thread;
4922 lldb::StateType old_state = eStateInvalid;
4923 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004924
Kate Stoneb9c1b512016-09-06 20:57:50 +00004925 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4926 LIBLLDB_LOG_PROCESS));
4927 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4928 // Yikes, we are running on the private state thread! So we can't wait for
4929 // public events on this thread, since
4930 // we are the thread that is generating public events.
4931 // The simplest thing to do is to spin up a temporary thread to handle
4932 // private state thread events while
4933 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004934 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004935 log->Printf("Running thread plan on private state thread, spinning up "
4936 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004937
Kate Stoneb9c1b512016-09-06 20:57:50 +00004938 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004939
Kate Stoneb9c1b512016-09-06 20:57:50 +00004940 // One other bit of business: we want to run just this thread plan and
4941 // anything it pushes, and then stop,
4942 // returning control here.
4943 // But in the normal course of things, the plan above us on the stack would
4944 // be given a shot at the stop
4945 // event before deciding to stop, and we don't want that. So we insert a
4946 // "stopper" base plan on the stack
4947 // before the plan we want to run. Since base plans always stop and return
4948 // control to the user, that will
4949 // do just what we want.
4950 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4951 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4952 // Have to make sure our public state is stopped, since otherwise the
4953 // reporting logic below doesn't work correctly.
4954 old_state = m_public_state.GetValue();
4955 m_public_state.SetValueNoLock(eStateStopped);
4956
4957 // Now spin up the private state thread:
4958 StartPrivateStateThread(true);
4959 }
4960
4961 thread->QueueThreadPlan(
4962 thread_plan_sp, false); // This used to pass "true" does that make sense?
4963
4964 if (options.GetDebug()) {
4965 // In this case, we aren't actually going to run, we just want to stop right
4966 // away.
4967 // Flush this thread so we will refetch the stacks and show the correct
4968 // backtrace.
4969 // FIXME: To make this prettier we should invent some stop reason for this,
4970 // but that
4971 // is only cosmetic, and this functionality is only of use to lldb
4972 // developers who can
4973 // live with not pretty...
4974 thread->Flush();
4975 return eExpressionStoppedForDebug;
4976 }
4977
4978 ListenerSP listener_sp(
4979 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4980
4981 lldb::EventSP event_to_broadcast_sp;
4982
4983 {
4984 // This process event hijacker Hijacks the Public events and its destructor
4985 // makes sure that the process events get
4986 // restored on exit to the function.
4987 //
4988 // If the event needs to propagate beyond the hijacker (e.g., the process
4989 // exits during execution), then the event
4990 // is put into event_to_broadcast_sp for rebroadcasting.
4991
4992 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4993
4994 if (log) {
4995 StreamString s;
4996 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4997 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4998 " to run thread plan \"%s\".",
4999 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00005000 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005001
5002 bool got_event;
5003 lldb::EventSP event_sp;
5004 lldb::StateType stop_state = lldb::eStateInvalid;
5005
5006 bool before_first_timeout = true; // This is set to false the first time
5007 // that we have to halt the target.
5008 bool do_resume = true;
5009 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010
5011 // This is just for accounting:
5012 uint32_t num_resumes = 0;
5013
Kate Stoneb9c1b512016-09-06 20:57:50 +00005014 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005015 // going to run one thread, then we don't need the first timeout. So we
5016 // pretend we are after the first timeout already.
5017 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005018 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005019
Kate Stoneb9c1b512016-09-06 20:57:50 +00005020 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005021 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5022 options.GetStopOthers(), options.GetTryAllThreads(),
5023 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005024
5025 // This isn't going to work if there are unfetched events on the queue.
5026 // Are there cases where we might want to run the remaining events here, and
5027 // then try to
5028 // call the function? That's probably being too tricky for our own good.
5029
5030 Event *other_events = listener_sp->PeekAtNextEvent();
5031 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005032 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033 eDiagnosticSeverityError,
5034 "RunThreadPlan called with pending events on the queue.");
5035 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005036 }
5037
Kate Stoneb9c1b512016-09-06 20:57:50 +00005038 // We also need to make sure that the next event is delivered. We might be
5039 // calling a function as part of
5040 // a thread plan, in which case the last delivered event could be the
5041 // running event, and we don't want
5042 // event coalescing to cause us to lose OUR running event...
5043 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005044
Kate Stoneb9c1b512016-09-06 20:57:50 +00005045// This while loop must exit out the bottom, there's cleanup that we need to do
5046// when we are done.
5047// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005048
Kate Stoneb9c1b512016-09-06 20:57:50 +00005049#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5050 // It's pretty much impossible to write test cases for things like:
5051 // One thread timeout expires, I go to halt, but the process already stopped
5052 // on the function call stop breakpoint. Turning on this define will make
5053 // us not
5054 // fetch the first event till after the halt. So if you run a quick
5055 // function, it will have
5056 // completed, and the completion event will be waiting, when you interrupt
5057 // for halt.
5058 // The expression evaluation should still succeed.
5059 bool miss_first_event = true;
5060#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005061 while (true) {
5062 // We usually want to resume the process if we get to the top of the loop.
5063 // The only exception is if we get two running events with no intervening
5064 // stop, which can happen, we will just wait for then next stop event.
5065 if (log)
5066 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5067 "before_first_timeout: %i.",
5068 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005069
Kate Stoneb9c1b512016-09-06 20:57:50 +00005070 if (do_resume || handle_running_event) {
5071 // Do the initial resume and wait for the running event before going
5072 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005073
Kate Stoneb9c1b512016-09-06 20:57:50 +00005074 if (do_resume) {
5075 num_resumes++;
5076 Error resume_error = PrivateResume();
5077 if (!resume_error.Success()) {
5078 diagnostic_manager.Printf(
5079 eDiagnosticSeverityError,
5080 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5081 resume_error.AsCString());
5082 return_value = eExpressionSetupError;
5083 break;
5084 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005085 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005086
Pavel Labathd35031e12016-11-30 10:41:42 +00005087 got_event =
5088 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005089 if (!got_event) {
5090 if (log)
5091 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5092 "resume %" PRIu32 ", exiting.",
5093 num_resumes);
5094
5095 diagnostic_manager.Printf(eDiagnosticSeverityError,
5096 "didn't get any event after resume %" PRIu32
5097 ", exiting.",
5098 num_resumes);
5099 return_value = eExpressionSetupError;
5100 break;
5101 }
5102
5103 stop_state =
5104 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5105
5106 if (stop_state != eStateRunning) {
5107 bool restarted = false;
5108
5109 if (stop_state == eStateStopped) {
5110 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5111 event_sp.get());
5112 if (log)
5113 log->Printf(
5114 "Process::RunThreadPlan(): didn't get running event after "
5115 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5116 "handle_running_event: %i).",
5117 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5118 handle_running_event);
5119 }
5120
5121 if (restarted) {
5122 // This is probably an overabundance of caution, I don't think I
5123 // should ever get a stopped & restarted
5124 // event here. But if I do, the best thing is to Halt and then get
5125 // out of here.
5126 const bool clear_thread_plans = false;
5127 const bool use_run_lock = false;
5128 Halt(clear_thread_plans, use_run_lock);
5129 }
5130
5131 diagnostic_manager.Printf(
5132 eDiagnosticSeverityError,
5133 "didn't get running event after initial resume, got %s instead.",
5134 StateAsCString(stop_state));
5135 return_value = eExpressionSetupError;
5136 break;
5137 }
5138
5139 if (log)
5140 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5141 // We need to call the function synchronously, so spin waiting for it to
5142 // return.
5143 // If we get interrupted while executing, we're going to lose our
5144 // context, and
5145 // won't be able to gather the result at this point.
5146 // We set the timeout AFTER the resume, since the resume takes some time
5147 // and we
5148 // don't want to charge that to the timeout.
5149 } else {
5150 if (log)
5151 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5152 }
5153
Kate Stoneb9c1b512016-09-06 20:57:50 +00005154 do_resume = true;
5155 handle_running_event = true;
5156
5157 // Now wait for the process to stop again:
5158 event_sp.reset();
5159
Pavel Labath2ce22162016-12-01 10:57:30 +00005160 Timeout<std::micro> timeout =
5161 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005162 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005163 if (timeout) {
5164 auto now = system_clock::now();
5165 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5166 "endpoint is %s",
5167 llvm::to_string(now).c_str(),
5168 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005169 } else {
5170 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005171 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005172 }
5173
5174#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5175 // See comment above...
5176 if (miss_first_event) {
5177 usleep(1000);
5178 miss_first_event = false;
5179 got_event = false;
5180 } else
5181#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005182 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005183
5184 if (got_event) {
5185 if (event_sp) {
5186 bool keep_going = false;
5187 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5188 const bool clear_thread_plans = false;
5189 const bool use_run_lock = false;
5190 Halt(clear_thread_plans, use_run_lock);
5191 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005192 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5193 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005194 if (log)
5195 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5196 "eBroadcastBitInterrupted, exiting.");
5197 break;
5198 } else {
5199 stop_state =
5200 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5201 if (log)
5202 log->Printf(
5203 "Process::RunThreadPlan(): in while loop, got event: %s.",
5204 StateAsCString(stop_state));
5205
5206 switch (stop_state) {
5207 case lldb::eStateStopped: {
5208 // We stopped, figure out what we are going to do now.
5209 ThreadSP thread_sp =
5210 GetThreadList().FindThreadByIndexID(thread_idx_id);
5211 if (!thread_sp) {
5212 // Ooh, our thread has vanished. Unlikely that this was
5213 // successful execution...
5214 if (log)
5215 log->Printf("Process::RunThreadPlan(): execution completed "
5216 "but our thread (index-id=%u) has vanished.",
5217 thread_idx_id);
5218 return_value = eExpressionInterrupted;
5219 } else {
5220 // If we were restarted, we just need to go back up to fetch
5221 // another event.
5222 if (Process::ProcessEventData::GetRestartedFromEvent(
5223 event_sp.get())) {
5224 if (log) {
5225 log->Printf("Process::RunThreadPlan(): Got a stop and "
5226 "restart, so we'll continue waiting.");
5227 }
5228 keep_going = true;
5229 do_resume = false;
5230 handle_running_event = true;
5231 } else {
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005232 ThreadPlanSP plan = thread->GetCompletedPlan();
5233 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005234
Kate Stoneb9c1b512016-09-06 20:57:50 +00005235 if (log)
5236 log->PutCString("Process::RunThreadPlan(): execution "
5237 "completed successfully.");
5238
5239 // Restore the plan state so it will get reported as
5240 // intended when we are done.
5241 thread_plan_restorer.Clean();
5242
5243 return_value = eExpressionCompleted;
5244 } else {
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005245 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005246 // Something restarted the target, so just wait for it to
5247 // stop for real.
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005248 if (stop_info_sp &&
5249 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005250 if (log)
5251 log->Printf("Process::RunThreadPlan() stopped for "
5252 "breakpoint: %s.",
5253 stop_info_sp->GetDescription());
5254 return_value = eExpressionHitBreakpoint;
5255 if (!options.DoesIgnoreBreakpoints()) {
5256 // Restore the plan state and then force Private to
5257 // false. We are
5258 // going to stop because of this plan so we need it to
5259 // become a public
5260 // plan or it won't report correctly when we continue to
5261 // its termination
5262 // later on.
5263 thread_plan_restorer.Clean();
5264 if (thread_plan_sp)
5265 thread_plan_sp->SetPrivate(false);
5266 event_to_broadcast_sp = event_sp;
5267 }
5268 } else {
5269 if (log)
5270 log->PutCString("Process::RunThreadPlan(): thread plan "
5271 "didn't successfully complete.");
5272 if (!options.DoesUnwindOnError())
5273 event_to_broadcast_sp = event_sp;
5274 return_value = eExpressionInterrupted;
5275 }
5276 }
5277 }
5278 }
5279 } break;
5280
5281 case lldb::eStateRunning:
5282 // This shouldn't really happen, but sometimes we do get two
5283 // running events without an
5284 // intervening stop, and in that case we should just go back to
5285 // waiting for the stop.
5286 do_resume = false;
5287 keep_going = true;
5288 handle_running_event = false;
5289 break;
5290
5291 default:
5292 if (log)
5293 log->Printf("Process::RunThreadPlan(): execution stopped with "
5294 "unexpected state: %s.",
5295 StateAsCString(stop_state));
5296
5297 if (stop_state == eStateExited)
5298 event_to_broadcast_sp = event_sp;
5299
Zachary Turnere2411fa2016-11-12 19:12:56 +00005300 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005301 eDiagnosticSeverityError,
5302 "execution stopped with unexpected state.");
5303 return_value = eExpressionInterrupted;
5304 break;
5305 }
5306 }
5307
5308 if (keep_going)
5309 continue;
5310 else
5311 break;
5312 } else {
5313 if (log)
5314 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5315 "the event pointer was null. How odd...");
5316 return_value = eExpressionInterrupted;
5317 break;
5318 }
5319 } else {
5320 // If we didn't get an event that means we've timed out...
5321 // We will interrupt the process here. Depending on what we were asked
5322 // to do we will
5323 // either exit, or try with all threads running for the same timeout.
5324
5325 if (log) {
5326 if (options.GetTryAllThreads()) {
5327 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005328 LLDB_LOG(log,
5329 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005330 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005331 LLDB_LOG(log, "Restarting function with all threads enabled and "
5332 "timeout: {0} timed out, abandoning execution.",
5333 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005334 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005335 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5336 "abandoning execution.",
5337 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005338 }
5339
5340 // It is possible that between the time we issued the Halt, and we get
5341 // around to calling Halt the target
5342 // could have stopped. That's fine, Halt will figure that out and send
5343 // the appropriate Stopped event.
5344 // BUT it is also possible that we stopped & restarted (e.g. hit a
5345 // signal with "stop" set to false.) In
5346 // that case, we'll get the stopped & restarted event, and we should go
5347 // back to waiting for the Halt's
5348 // stopped event. That's what this while loop does.
5349
5350 bool back_to_top = true;
5351 uint32_t try_halt_again = 0;
5352 bool do_halt = true;
5353 const uint32_t num_retries = 5;
5354 while (try_halt_again < num_retries) {
5355 Error halt_error;
5356 if (do_halt) {
5357 if (log)
5358 log->Printf("Process::RunThreadPlan(): Running Halt.");
5359 const bool clear_thread_plans = false;
5360 const bool use_run_lock = false;
5361 Halt(clear_thread_plans, use_run_lock);
5362 }
5363 if (halt_error.Success()) {
5364 if (log)
5365 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5366
Pavel Labathd35031e12016-11-30 10:41:42 +00005367 got_event =
5368 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005369
5370 if (got_event) {
5371 stop_state =
5372 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5373 if (log) {
5374 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5375 StateAsCString(stop_state));
5376 if (stop_state == lldb::eStateStopped &&
5377 Process::ProcessEventData::GetInterruptedFromEvent(
5378 event_sp.get()))
5379 log->PutCString(" Event was the Halt interruption event.");
5380 }
5381
5382 if (stop_state == lldb::eStateStopped) {
5383 // Between the time we initiated the Halt and the time we
5384 // delivered it, the process could have
5385 // already finished its job. Check that here:
5386
5387 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5388 if (log)
5389 log->PutCString("Process::RunThreadPlan(): Even though we "
5390 "timed out, the call plan was done. "
5391 "Exiting wait loop.");
5392 return_value = eExpressionCompleted;
5393 back_to_top = false;
5394 break;
5395 }
5396
5397 if (Process::ProcessEventData::GetRestartedFromEvent(
5398 event_sp.get())) {
5399 if (log)
5400 log->PutCString("Process::RunThreadPlan(): Went to halt "
5401 "but got a restarted event, there must be "
5402 "an un-restarted stopped event so try "
5403 "again... "
5404 "Exiting wait loop.");
5405 try_halt_again++;
5406 do_halt = false;
5407 continue;
5408 }
5409
5410 if (!options.GetTryAllThreads()) {
5411 if (log)
5412 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5413 "was false, we stopped so now we're "
5414 "quitting.");
5415 return_value = eExpressionInterrupted;
5416 back_to_top = false;
5417 break;
5418 }
5419
5420 if (before_first_timeout) {
5421 // Set all the other threads to run, and return to the top of
5422 // the loop, which will continue;
5423 before_first_timeout = false;
5424 thread_plan_sp->SetStopOthers(false);
5425 if (log)
5426 log->PutCString(
5427 "Process::RunThreadPlan(): about to resume.");
5428
5429 back_to_top = true;
5430 break;
5431 } else {
5432 // Running all threads failed, so return Interrupted.
5433 if (log)
5434 log->PutCString("Process::RunThreadPlan(): running all "
5435 "threads timed out.");
5436 return_value = eExpressionInterrupted;
5437 back_to_top = false;
5438 break;
5439 }
5440 }
5441 } else {
5442 if (log)
5443 log->PutCString("Process::RunThreadPlan(): halt said it "
5444 "succeeded, but I got no event. "
5445 "I'm getting out of here passing Interrupted.");
5446 return_value = eExpressionInterrupted;
5447 back_to_top = false;
5448 break;
5449 }
5450 } else {
5451 try_halt_again++;
5452 continue;
5453 }
5454 }
5455
5456 if (!back_to_top || try_halt_again > num_retries)
5457 break;
5458 else
5459 continue;
5460 }
5461 } // END WAIT LOOP
5462
5463 // If we had to start up a temporary private state thread to run this thread
5464 // plan, shut it down now.
5465 if (backup_private_state_thread.IsJoinable()) {
5466 StopPrivateStateThread();
5467 Error error;
5468 m_private_state_thread = backup_private_state_thread;
5469 if (stopper_base_plan_sp) {
5470 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5471 }
5472 if (old_state != eStateInvalid)
5473 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005474 }
5475
Kate Stoneb9c1b512016-09-06 20:57:50 +00005476 if (return_value != eExpressionCompleted && log) {
5477 // Print a backtrace into the log so we can figure out where we are:
5478 StreamString s;
5479 s.PutCString("Thread state after unsuccessful completion: \n");
5480 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005481 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005483 // Restore the thread state if we are going to discard the plan execution.
5484 // There are three cases where this
5485 // could happen:
5486 // 1) The execution successfully completed
5487 // 2) We hit a breakpoint, and ignore_breakpoints was true
5488 // 3) We got some other error, and discard_on_error was true
5489 bool should_unwind = (return_value == eExpressionInterrupted &&
5490 options.DoesUnwindOnError()) ||
5491 (return_value == eExpressionHitBreakpoint &&
5492 options.DoesIgnoreBreakpoints());
5493
5494 if (return_value == eExpressionCompleted || should_unwind) {
5495 thread_plan_sp->RestoreThreadState();
5496 }
5497
5498 // Now do some processing on the results of the run:
5499 if (return_value == eExpressionInterrupted ||
5500 return_value == eExpressionHitBreakpoint) {
5501 if (log) {
5502 StreamString s;
5503 if (event_sp)
5504 event_sp->Dump(&s);
5505 else {
5506 log->PutCString("Process::RunThreadPlan(): Stop event that "
5507 "interrupted us is NULL.");
5508 }
5509
5510 StreamString ts;
5511
5512 const char *event_explanation = nullptr;
5513
5514 do {
5515 if (!event_sp) {
5516 event_explanation = "<no event>";
5517 break;
5518 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5519 event_explanation = "<user interrupt>";
5520 break;
5521 } else {
5522 const Process::ProcessEventData *event_data =
5523 Process::ProcessEventData::GetEventDataFromEvent(
5524 event_sp.get());
5525
5526 if (!event_data) {
5527 event_explanation = "<no event data>";
5528 break;
5529 }
5530
5531 Process *process = event_data->GetProcessSP().get();
5532
5533 if (!process) {
5534 event_explanation = "<no process>";
5535 break;
5536 }
5537
5538 ThreadList &thread_list = process->GetThreadList();
5539
5540 uint32_t num_threads = thread_list.GetSize();
5541 uint32_t thread_index;
5542
5543 ts.Printf("<%u threads> ", num_threads);
5544
5545 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5546 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5547
5548 if (!thread) {
5549 ts.Printf("<?> ");
5550 continue;
5551 }
5552
5553 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5554 RegisterContext *register_context =
5555 thread->GetRegisterContext().get();
5556
5557 if (register_context)
5558 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5559 else
5560 ts.Printf("[ip unknown] ");
5561
5562 // Show the private stop info here, the public stop info will be
5563 // from the last natural stop.
5564 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5565 if (stop_info_sp) {
5566 const char *stop_desc = stop_info_sp->GetDescription();
5567 if (stop_desc)
5568 ts.PutCString(stop_desc);
5569 }
5570 ts.Printf(">");
5571 }
5572
5573 event_explanation = ts.GetData();
5574 }
5575 } while (0);
5576
5577 if (event_explanation)
5578 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5579 s.GetData(), event_explanation);
5580 else
5581 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5582 s.GetData());
5583 }
5584
5585 if (should_unwind) {
5586 if (log)
5587 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5588 "discarding thread plans up to %p.",
5589 static_cast<void *>(thread_plan_sp.get()));
5590 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5591 } else {
5592 if (log)
5593 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5594 "plan: %p not discarding.",
5595 static_cast<void *>(thread_plan_sp.get()));
5596 }
5597 } else if (return_value == eExpressionSetupError) {
5598 if (log)
5599 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5600
5601 if (options.DoesUnwindOnError()) {
5602 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5603 }
5604 } else {
5605 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5606 if (log)
5607 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5608 return_value = eExpressionCompleted;
5609 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5610 if (log)
5611 log->PutCString(
5612 "Process::RunThreadPlan(): thread plan was discarded");
5613 return_value = eExpressionDiscarded;
5614 } else {
5615 if (log)
5616 log->PutCString(
5617 "Process::RunThreadPlan(): thread plan stopped in mid course");
5618 if (options.DoesUnwindOnError() && thread_plan_sp) {
5619 if (log)
5620 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5621 "'cause unwind_on_error is set.");
5622 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5623 }
5624 }
5625 }
5626
5627 // Thread we ran the function in may have gone away because we ran the
5628 // target
5629 // Check that it's still there, and if it is put it back in the context.
5630 // Also restore the
5631 // frame in the context if it is still present.
5632 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5633 if (thread) {
5634 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5635 }
5636
5637 // Also restore the current process'es selected frame & thread, since this
5638 // function calling may
5639 // be done behind the user's back.
5640
5641 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5642 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5643 selected_stack_id.IsValid()) {
5644 // We were able to restore the selected thread, now restore the frame:
5645 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5646 StackFrameSP old_frame_sp =
5647 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5648 selected_stack_id);
5649 if (old_frame_sp)
5650 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5651 old_frame_sp.get());
5652 }
5653 }
5654 }
5655
5656 // If the process exited during the run of the thread plan, notify everyone.
5657
5658 if (event_to_broadcast_sp) {
5659 if (log)
5660 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5661 BroadcastEvent(event_to_broadcast_sp);
5662 }
5663
5664 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005665}
5666
Kate Stoneb9c1b512016-09-06 20:57:50 +00005667const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5668 const char *result_name;
5669
5670 switch (result) {
5671 case eExpressionCompleted:
5672 result_name = "eExpressionCompleted";
5673 break;
5674 case eExpressionDiscarded:
5675 result_name = "eExpressionDiscarded";
5676 break;
5677 case eExpressionInterrupted:
5678 result_name = "eExpressionInterrupted";
5679 break;
5680 case eExpressionHitBreakpoint:
5681 result_name = "eExpressionHitBreakpoint";
5682 break;
5683 case eExpressionSetupError:
5684 result_name = "eExpressionSetupError";
5685 break;
5686 case eExpressionParseError:
5687 result_name = "eExpressionParseError";
5688 break;
5689 case eExpressionResultUnavailable:
5690 result_name = "eExpressionResultUnavailable";
5691 break;
5692 case eExpressionTimedOut:
5693 result_name = "eExpressionTimedOut";
5694 break;
5695 case eExpressionStoppedForDebug:
5696 result_name = "eExpressionStoppedForDebug";
5697 break;
5698 }
5699 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005700}
5701
Kate Stoneb9c1b512016-09-06 20:57:50 +00005702void Process::GetStatus(Stream &strm) {
5703 const StateType state = GetState();
5704 if (StateIsStoppedState(state, false)) {
5705 if (state == eStateExited) {
5706 int exit_status = GetExitStatus();
5707 const char *exit_description = GetExitDescription();
5708 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5709 GetID(), exit_status, exit_status,
5710 exit_description ? exit_description : "");
5711 } else {
5712 if (state == eStateConnected)
5713 strm.Printf("Connected to remote target.\n");
5714 else
5715 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5716 }
5717 } else {
5718 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5719 }
Pavel Labatha933d512016-04-05 13:07:16 +00005720}
5721
Kate Stoneb9c1b512016-09-06 20:57:50 +00005722size_t Process::GetThreadStatus(Stream &strm,
5723 bool only_threads_with_stop_reason,
5724 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005725 uint32_t num_frames_with_source,
5726 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005727 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005728
Kate Stoneb9c1b512016-09-06 20:57:50 +00005729 // You can't hold the thread list lock while calling Thread::GetStatus. That
5730 // very well might run code (e.g. if we need it
5731 // to get return values or arguments.) For that to work the process has to be
5732 // able to acquire it. So instead copy the thread
5733 // ID's, and look them up one by one:
5734
5735 uint32_t num_threads;
5736 std::vector<lldb::tid_t> thread_id_array;
5737 // Scope for thread list locker;
5738 {
5739 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5740 ThreadList &curr_thread_list = GetThreadList();
5741 num_threads = curr_thread_list.GetSize();
5742 uint32_t idx;
5743 thread_id_array.resize(num_threads);
5744 for (idx = 0; idx < num_threads; ++idx)
5745 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5746 }
5747
5748 for (uint32_t i = 0; i < num_threads; i++) {
5749 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5750 if (thread_sp) {
5751 if (only_threads_with_stop_reason) {
5752 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5753 if (!stop_info_sp || !stop_info_sp->IsValid())
5754 continue;
5755 }
5756 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005757 num_frames_with_source,
5758 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005759 ++num_thread_infos_dumped;
5760 } else {
5761 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5762 if (log)
5763 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5764 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005765 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005766 }
5767 return num_thread_infos_dumped;
5768}
5769
5770void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5771 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5772}
5773
5774bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5775 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5776 region.GetByteSize());
5777}
5778
5779void Process::AddPreResumeAction(PreResumeActionCallback callback,
5780 void *baton) {
5781 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5782}
5783
5784bool Process::RunPreResumeActions() {
5785 bool result = true;
5786 while (!m_pre_resume_actions.empty()) {
5787 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5788 m_pre_resume_actions.pop_back();
5789 bool this_result = action.callback(action.baton);
5790 if (result)
5791 result = this_result;
5792 }
5793 return result;
5794}
5795
5796void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5797
Jim Inghamffd91752016-10-20 22:50:00 +00005798void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5799{
5800 PreResumeCallbackAndBaton element(callback, baton);
5801 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5802 if (found_iter != m_pre_resume_actions.end())
5803 {
5804 m_pre_resume_actions.erase(found_iter);
5805 }
5806}
5807
Kate Stoneb9c1b512016-09-06 20:57:50 +00005808ProcessRunLock &Process::GetRunLock() {
5809 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5810 return m_private_run_lock;
5811 else
5812 return m_public_run_lock;
5813}
5814
5815void Process::Flush() {
5816 m_thread_list.Flush();
5817 m_extended_thread_list.Flush();
5818 m_extended_thread_stop_id = 0;
5819 m_queue_list.Clear();
5820 m_queue_list_stop_id = 0;
5821}
5822
5823void Process::DidExec() {
5824 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5825 if (log)
5826 log->Printf("Process::%s()", __FUNCTION__);
5827
5828 Target &target = GetTarget();
5829 target.CleanupProcess();
5830 target.ClearModules(false);
5831 m_dynamic_checkers_ap.reset();
5832 m_abi_sp.reset();
5833 m_system_runtime_ap.reset();
5834 m_os_ap.reset();
5835 m_dyld_ap.reset();
5836 m_jit_loaders_ap.reset();
5837 m_image_tokens.clear();
5838 m_allocated_memory_cache.Clear();
5839 m_language_runtimes.clear();
5840 m_instrumentation_runtimes.clear();
5841 m_thread_list.DiscardThreadPlans();
5842 m_memory_cache.Clear(true);
5843 m_stop_info_override_callback = nullptr;
5844 DoDidExec();
5845 CompleteAttach();
5846 // Flush the process (threads and all stack frames) after running
5847 // CompleteAttach()
5848 // in case the dynamic loader loaded things in new locations.
5849 Flush();
5850
5851 // After we figure out what was loaded/unloaded in CompleteAttach,
5852 // we need to let the target know so it can do any cleanup it needs to.
5853 target.DidExec();
5854}
5855
5856addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5857 if (address == nullptr) {
5858 error.SetErrorString("Invalid address argument");
5859 return LLDB_INVALID_ADDRESS;
5860 }
5861
5862 addr_t function_addr = LLDB_INVALID_ADDRESS;
5863
5864 addr_t addr = address->GetLoadAddress(&GetTarget());
5865 std::map<addr_t, addr_t>::const_iterator iter =
5866 m_resolved_indirect_addresses.find(addr);
5867 if (iter != m_resolved_indirect_addresses.end()) {
5868 function_addr = (*iter).second;
5869 } else {
5870 if (!InferiorCall(this, address, function_addr)) {
5871 Symbol *symbol = address->CalculateSymbolContextSymbol();
5872 error.SetErrorStringWithFormat(
5873 "Unable to call resolver for indirect function %s",
5874 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5875 function_addr = LLDB_INVALID_ADDRESS;
5876 } else {
5877 m_resolved_indirect_addresses.insert(
5878 std::pair<addr_t, addr_t>(addr, function_addr));
5879 }
5880 }
5881 return function_addr;
5882}
5883
5884void Process::ModulesDidLoad(ModuleList &module_list) {
5885 SystemRuntime *sys_runtime = GetSystemRuntime();
5886 if (sys_runtime) {
5887 sys_runtime->ModulesDidLoad(module_list);
5888 }
5889
5890 GetJITLoaders().ModulesDidLoad(module_list);
5891
5892 // Give runtimes a chance to be created.
5893 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5894 m_instrumentation_runtimes);
5895
5896 // Tell runtimes about new modules.
5897 for (auto pos = m_instrumentation_runtimes.begin();
5898 pos != m_instrumentation_runtimes.end(); ++pos) {
5899 InstrumentationRuntimeSP runtime = pos->second;
5900 runtime->ModulesDidLoad(module_list);
5901 }
5902
5903 // Let any language runtimes we have already created know
5904 // about the modules that loaded.
5905
5906 // Iterate over a copy of this language runtime list in case
5907 // the language runtime ModulesDidLoad somehow causes the language
5908 // riuntime to be unloaded.
5909 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5910 for (const auto &pair : language_runtimes) {
5911 // We must check language_runtime_sp to make sure it is not
5912 // nullptr as we might cache the fact that we didn't have a
5913 // language runtime for a language.
5914 LanguageRuntimeSP language_runtime_sp = pair.second;
5915 if (language_runtime_sp)
5916 language_runtime_sp->ModulesDidLoad(module_list);
5917 }
5918
5919 // If we don't have an operating system plug-in, try to load one since
5920 // loading shared libraries might cause a new one to try and load
5921 if (!m_os_ap)
5922 LoadOperatingSystemPlugin(false);
5923
5924 // Give structured-data plugins a chance to see the modified modules.
5925 for (auto pair : m_structured_data_plugin_map) {
5926 if (pair.second)
5927 pair.second->ModulesDidLoad(*this, module_list);
5928 }
5929}
5930
5931void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5932 const char *fmt, ...) {
5933 bool print_warning = true;
5934
5935 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5936 if (!stream_sp)
5937 return;
5938 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5939 return;
5940 }
5941
5942 if (repeat_key != nullptr) {
5943 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5944 if (it == m_warnings_issued.end()) {
5945 m_warnings_issued[warning_type] = WarningsPointerSet();
5946 m_warnings_issued[warning_type].insert(repeat_key);
5947 } else {
5948 if (it->second.find(repeat_key) != it->second.end()) {
5949 print_warning = false;
5950 } else {
5951 it->second.insert(repeat_key);
5952 }
5953 }
5954 }
5955
5956 if (print_warning) {
5957 va_list args;
5958 va_start(args, fmt);
5959 stream_sp->PrintfVarArg(fmt, args);
5960 va_end(args);
5961 }
5962}
5963
5964void Process::PrintWarningOptimization(const SymbolContext &sc) {
5965 if (GetWarningsOptimization() && sc.module_sp &&
5966 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5967 sc.function->GetIsOptimized()) {
5968 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5969 "%s was compiled with optimization - stepping may behave "
5970 "oddly; variables may not be available.\n",
5971 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5972 }
5973}
5974
5975bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5976 info.Clear();
5977
5978 PlatformSP platform_sp = GetTarget().GetPlatform();
5979 if (!platform_sp)
5980 return false;
5981
5982 return platform_sp->GetProcessInfo(GetID(), info);
5983}
5984
5985ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5986 ThreadCollectionSP threads;
5987
5988 const MemoryHistorySP &memory_history =
5989 MemoryHistory::FindPlugin(shared_from_this());
5990
5991 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005992 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005993 }
5994
5995 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
5996
5997 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005998}
Kuba Brecka63927542014-10-11 01:59:32 +00005999
6000InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006001Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6002 InstrumentationRuntimeCollection::iterator pos;
6003 pos = m_instrumentation_runtimes.find(type);
6004 if (pos == m_instrumentation_runtimes.end()) {
6005 return InstrumentationRuntimeSP();
6006 } else
6007 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006008}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006009
Kate Stoneb9c1b512016-09-06 20:57:50 +00006010bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6011 const ArchSpec &arch, ModuleSpec &module_spec) {
6012 module_spec.Clear();
6013 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006014}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006015
Kate Stoneb9c1b512016-09-06 20:57:50 +00006016size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6017 m_image_tokens.push_back(image_ptr);
6018 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006019}
6020
Kate Stoneb9c1b512016-09-06 20:57:50 +00006021lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6022 if (token < m_image_tokens.size())
6023 return m_image_tokens[token];
6024 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006025}
6026
Kate Stoneb9c1b512016-09-06 20:57:50 +00006027void Process::ResetImageToken(size_t token) {
6028 if (token < m_image_tokens.size())
6029 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006030}
Jason Molendafd4cea52016-01-08 21:40:11 +00006031
6032Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006033Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6034 AddressRange range_bounds) {
6035 Target &target = GetTarget();
6036 DisassemblerSP disassembler_sp;
6037 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006038
Kate Stoneb9c1b512016-09-06 20:57:50 +00006039 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006040
Kate Stoneb9c1b512016-09-06 20:57:50 +00006041 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006042 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006043 if (!default_stop_addr.IsValid())
6044 return retval;
6045
6046 ExecutionContext exe_ctx(this);
6047 const char *plugin_name = nullptr;
6048 const char *flavor = nullptr;
6049 const bool prefer_file_cache = true;
6050 disassembler_sp = Disassembler::DisassembleRange(
6051 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6052 prefer_file_cache);
6053 if (disassembler_sp)
6054 insn_list = &disassembler_sp->GetInstructionList();
6055
6056 if (insn_list == nullptr) {
6057 return retval;
6058 }
6059
6060 size_t insn_offset =
6061 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6062 if (insn_offset == UINT32_MAX) {
6063 return retval;
6064 }
6065
6066 uint32_t branch_index =
6067 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6068 if (branch_index == UINT32_MAX) {
6069 return retval;
6070 }
6071
6072 if (branch_index > insn_offset) {
6073 Address next_branch_insn_address =
6074 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6075 if (next_branch_insn_address.IsValid() &&
6076 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6077 retval = next_branch_insn_address;
6078 }
6079 }
6080
6081 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006082}
Howard Hellyerad007562016-07-07 08:21:28 +00006083
Kate Stoneb9c1b512016-09-06 20:57:50 +00006084Error Process::GetMemoryRegions(
6085 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006086
Kate Stoneb9c1b512016-09-06 20:57:50 +00006087 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006088
Kate Stoneb9c1b512016-09-06 20:57:50 +00006089 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006090
Kate Stoneb9c1b512016-09-06 20:57:50 +00006091 region_list.clear();
6092 do {
6093 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6094 error = GetMemoryRegionInfo(range_end, *region_info);
6095 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6096 if (error.Fail()) {
6097 region_list.clear();
6098 break;
Todd Fiala75930012016-08-19 04:21:48 +00006099 }
6100
Kate Stoneb9c1b512016-09-06 20:57:50 +00006101 range_end = region_info->GetRange().GetRangeEnd();
6102 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6103 region_list.push_back(region_info);
6104 }
6105 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006106
Kate Stoneb9c1b512016-09-06 20:57:50 +00006107 return error;
6108}
6109
6110Error Process::ConfigureStructuredData(
6111 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6112 // If you get this, the Process-derived class needs to implement a method
6113 // to enable an already-reported asynchronous structured data feature.
6114 // See ProcessGDBRemote for an example implementation over gdb-remote.
6115 return Error("unimplemented");
6116}
6117
6118void Process::MapSupportedStructuredDataPlugins(
6119 const StructuredData::Array &supported_type_names) {
6120 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6121
6122 // Bail out early if there are no type names to map.
6123 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006124 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006125 log->Printf("Process::%s(): no structured data types supported",
6126 __FUNCTION__);
6127 return;
6128 }
Todd Fiala75930012016-08-19 04:21:48 +00006129
Kate Stoneb9c1b512016-09-06 20:57:50 +00006130 // Convert StructuredData type names to ConstString instances.
6131 std::set<ConstString> const_type_names;
6132
6133 if (log)
6134 log->Printf("Process::%s(): the process supports the following async "
6135 "structured data types:",
6136 __FUNCTION__);
6137
6138 supported_type_names.ForEach(
6139 [&const_type_names, &log](StructuredData::Object *object) {
6140 if (!object) {
6141 // Invalid - shouldn't be null objects in the array.
6142 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006143 }
6144
6145 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006146 if (!type_name) {
6147 // Invalid format - all type names should be strings.
6148 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006149 }
6150
6151 const_type_names.insert(ConstString(type_name->GetValue()));
6152 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006153 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006154 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006155 });
Todd Fiala75930012016-08-19 04:21:48 +00006156
Kate Stoneb9c1b512016-09-06 20:57:50 +00006157 // For each StructuredDataPlugin, if the plugin handles any of the
6158 // types in the supported_type_names, map that type name to that plugin.
6159 uint32_t plugin_index = 0;
6160 for (auto create_instance =
6161 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6162 plugin_index);
6163 create_instance && !const_type_names.empty(); ++plugin_index) {
6164 // Create the plugin.
6165 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6166 if (!plugin_sp) {
6167 // This plugin doesn't think it can work with the process.
6168 // Move on to the next.
6169 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006170 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006171
6172 // For any of the remaining type names, map any that this plugin
6173 // supports.
6174 std::vector<ConstString> names_to_remove;
6175 for (auto &type_name : const_type_names) {
6176 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6177 m_structured_data_plugin_map.insert(
6178 std::make_pair(type_name, plugin_sp));
6179 names_to_remove.push_back(type_name);
6180 if (log)
6181 log->Printf("Process::%s(): using plugin %s for type name "
6182 "%s",
6183 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6184 type_name.GetCString());
6185 }
6186 }
6187
6188 // Remove the type names that were consumed by this plugin.
6189 for (auto &type_name : names_to_remove)
6190 const_type_names.erase(type_name);
6191 }
Todd Fiala75930012016-08-19 04:21:48 +00006192}
6193
Kate Stoneb9c1b512016-09-06 20:57:50 +00006194bool Process::RouteAsyncStructuredData(
6195 const StructuredData::ObjectSP object_sp) {
6196 // Nothing to do if there's no data.
6197 if (!object_sp)
6198 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006199
Kate Stoneb9c1b512016-09-06 20:57:50 +00006200 // The contract is this must be a dictionary, so we can look up the
6201 // routing key via the top-level 'type' string value within the dictionary.
6202 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6203 if (!dictionary)
6204 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006205
Kate Stoneb9c1b512016-09-06 20:57:50 +00006206 // Grab the async structured type name (i.e. the feature/plugin name).
6207 ConstString type_name;
6208 if (!dictionary->GetValueForKeyAsString("type", type_name))
6209 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006210
Kate Stoneb9c1b512016-09-06 20:57:50 +00006211 // Check if there's a plugin registered for this type name.
6212 auto find_it = m_structured_data_plugin_map.find(type_name);
6213 if (find_it == m_structured_data_plugin_map.end()) {
6214 // We don't have a mapping for this structured data type.
6215 return false;
6216 }
Todd Fiala75930012016-08-19 04:21:48 +00006217
Kate Stoneb9c1b512016-09-06 20:57:50 +00006218 // Route the structured data to the plugin.
6219 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6220 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006221}