blob: e2006f4bbc3832181ac8af5e03288efd9d6fe1ca [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
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002781 // We successfully launched the process and stopped,
2782 // now it the right time to set up signal filters before resuming.
2783 UpdateAutomaticSignalFiltering();
2784
Kate Stoneb9c1b512016-09-06 20:57:50 +00002785 // Note, the stop event was consumed above, but not handled. This
2786 // was done
2787 // to give DidLaunch a chance to run. The target is either stopped
2788 // or crashed.
2789 // Directly set the state. This is done to prevent a stop message
2790 // with a bunch
2791 // of spurious output on thread status, as well as not pop a
2792 // ProcessIOHandler.
2793 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002794
Kate Stoneb9c1b512016-09-06 20:57:50 +00002795 if (PrivateStateThreadIsValid())
2796 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002797 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002798 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002799
Kate Stoneb9c1b512016-09-06 20:57:50 +00002800 m_stop_info_override_callback =
2801 GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 // Target was stopped at entry as was intended. Need to notify the
2804 // listeners
2805 // about it.
2806 if (state == eStateStopped &&
2807 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2808 HandlePrivateEvent(event_sp);
2809 } else if (state == eStateExited) {
2810 // We exited while trying to launch somehow. Don't call DidLaunch
2811 // as that's
2812 // not likely to work, and return an invalid pid.
2813 HandlePrivateEvent(event_sp);
2814 }
2815 }
2816 }
2817 } else {
2818 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2819 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002820 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 }
2822 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002823}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824
Kate Stoneb9c1b512016-09-06 20:57:50 +00002825Error Process::LoadCore() {
2826 Error error = DoLoadCore();
2827 if (error.Success()) {
2828 ListenerSP listener_sp(
2829 Listener::MakeListener("lldb.process.load_core_listener"));
2830 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002831
Kate Stoneb9c1b512016-09-06 20:57:50 +00002832 if (PrivateStateThreadIsValid())
2833 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002834 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002835 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002836
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002838 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002839 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002840
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002841 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002844 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002846
Greg Clayton29eeea02017-02-09 18:55:41 +00002847 if (!m_os_ap)
2848 LoadOperatingSystemPlugin(false);
2849
Kate Stoneb9c1b512016-09-06 20:57:50 +00002850 // We successfully loaded a core file, now pretend we stopped so we can
2851 // show all of the threads in the core file and explore the crashed
2852 // state.
2853 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002854
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 // Wait indefinitely for a stopped event since we just posted one above...
2856 lldb::EventSP event_sp;
Pavel Labathd35031e12016-11-30 10:41:42 +00002857 listener_sp->GetEvent(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2859
2860 if (!StateIsStoppedState(state, false)) {
2861 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2862 if (log)
2863 log->Printf("Process::Halt() failed to stop, state is: %s",
2864 StateAsCString(state));
2865 error.SetErrorString(
2866 "Did not get stopped event after loading the core file.");
2867 }
2868 RestoreProcessEvents();
2869 }
2870 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002871}
2872
Kate Stoneb9c1b512016-09-06 20:57:50 +00002873DynamicLoader *Process::GetDynamicLoader() {
2874 if (!m_dyld_ap)
2875 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2876 return m_dyld_ap.get();
2877}
2878
2879const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2880
2881JITLoaderList &Process::GetJITLoaders() {
2882 if (!m_jit_loaders_ap) {
2883 m_jit_loaders_ap.reset(new JITLoaderList());
2884 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2885 }
2886 return *m_jit_loaders_ap;
2887}
2888
2889SystemRuntime *Process::GetSystemRuntime() {
2890 if (!m_system_runtime_ap)
2891 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2892 return m_system_runtime_ap.get();
2893}
2894
2895Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2896 uint32_t exec_count)
2897 : NextEventAction(process), m_exec_count(exec_count) {
2898 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2899 if (log)
2900 log->Printf(
2901 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2902 __FUNCTION__, static_cast<void *>(process), exec_count);
2903}
2904
2905Process::NextEventAction::EventActionResult
2906Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2907 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2908
2909 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2910 if (log)
2911 log->Printf(
2912 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2913 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2914
2915 switch (state) {
2916 case eStateAttaching:
2917 return eEventActionSuccess;
2918
2919 case eStateRunning:
2920 case eStateConnected:
2921 return eEventActionRetry;
2922
2923 case eStateStopped:
2924 case eStateCrashed:
2925 // During attach, prior to sending the eStateStopped event,
2926 // lldb_private::Process subclasses must set the new process ID.
2927 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2928 // We don't want these events to be reported, so go set the ShouldReportStop
2929 // here:
2930 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2931
2932 if (m_exec_count > 0) {
2933 --m_exec_count;
2934
2935 if (log)
2936 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2937 "remaining exec count to %" PRIu32 ", requesting resume",
2938 __FUNCTION__, StateAsCString(state), m_exec_count);
2939
2940 RequestResume();
2941 return eEventActionRetry;
2942 } else {
2943 if (log)
2944 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2945 "execs expected to start, continuing with attach",
2946 __FUNCTION__, StateAsCString(state));
2947
2948 m_process->CompleteAttach();
2949 return eEventActionSuccess;
2950 }
2951 break;
2952
2953 default:
2954 case eStateExited:
2955 case eStateInvalid:
2956 break;
2957 }
2958
2959 m_exit_string.assign("No valid Process");
2960 return eEventActionExit;
2961}
2962
2963Process::NextEventAction::EventActionResult
2964Process::AttachCompletionHandler::HandleBeingInterrupted() {
2965 return eEventActionSuccess;
2966}
2967
2968const char *Process::AttachCompletionHandler::GetExitString() {
2969 return m_exit_string.c_str();
2970}
2971
2972ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2973 if (m_listener_sp)
2974 return m_listener_sp;
2975 else
2976 return debugger.GetListener();
2977}
2978
2979Error Process::Attach(ProcessAttachInfo &attach_info) {
2980 m_abi_sp.reset();
2981 m_process_input_reader.reset();
2982 m_dyld_ap.reset();
2983 m_jit_loaders_ap.reset();
2984 m_system_runtime_ap.reset();
2985 m_os_ap.reset();
2986 m_stop_info_override_callback = nullptr;
2987
2988 lldb::pid_t attach_pid = attach_info.GetProcessID();
2989 Error error;
2990 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2991 char process_name[PATH_MAX];
2992
2993 if (attach_info.GetExecutableFile().GetPath(process_name,
2994 sizeof(process_name))) {
2995 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2996
2997 if (wait_for_launch) {
2998 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2999 if (error.Success()) {
3000 if (m_public_run_lock.TrySetRunning()) {
3001 m_should_detach = true;
3002 const bool restarted = false;
3003 SetPublicState(eStateAttaching, restarted);
3004 // Now attach using these arguments.
3005 error = DoAttachToProcessWithName(process_name, attach_info);
3006 } else {
3007 // This shouldn't happen
3008 error.SetErrorString("failed to acquire process run lock");
3009 }
3010
3011 if (error.Fail()) {
3012 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3013 SetID(LLDB_INVALID_PROCESS_ID);
3014 if (error.AsCString() == nullptr)
3015 error.SetErrorString("attach failed");
3016
3017 SetExitStatus(-1, error.AsCString());
3018 }
3019 } else {
3020 SetNextEventAction(new Process::AttachCompletionHandler(
3021 this, attach_info.GetResumeCount()));
3022 StartPrivateStateThread();
3023 }
3024 return error;
3025 }
3026 } else {
3027 ProcessInstanceInfoList process_infos;
3028 PlatformSP platform_sp(GetTarget().GetPlatform());
3029
3030 if (platform_sp) {
3031 ProcessInstanceInfoMatch match_info;
3032 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00003033 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003034 platform_sp->FindProcesses(match_info, process_infos);
3035 const uint32_t num_matches = process_infos.GetSize();
3036 if (num_matches == 1) {
3037 attach_pid = process_infos.GetProcessIDAtIndex(0);
3038 // Fall through and attach using the above process ID
3039 } else {
3040 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3041 process_name, sizeof(process_name));
3042 if (num_matches > 1) {
3043 StreamString s;
3044 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3045 false);
3046 for (size_t i = 0; i < num_matches; i++) {
3047 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3048 s, platform_sp.get(), true, false);
3049 }
3050 error.SetErrorStringWithFormat(
3051 "more than one process named %s:\n%s", process_name,
3052 s.GetData());
3053 } else
3054 error.SetErrorStringWithFormat(
3055 "could not find a process named %s", process_name);
3056 }
3057 } else {
3058 error.SetErrorString(
3059 "invalid platform, can't find processes by name");
3060 return error;
3061 }
3062 }
3063 } else {
3064 error.SetErrorString("invalid process name");
3065 }
3066 }
3067
3068 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3069 error = WillAttachToProcessWithID(attach_pid);
3070 if (error.Success()) {
3071
3072 if (m_public_run_lock.TrySetRunning()) {
3073 // Now attach using these arguments.
3074 m_should_detach = true;
3075 const bool restarted = false;
3076 SetPublicState(eStateAttaching, restarted);
3077 error = DoAttachToProcessWithID(attach_pid, attach_info);
3078 } else {
3079 // This shouldn't happen
3080 error.SetErrorString("failed to acquire process run lock");
3081 }
3082
3083 if (error.Success()) {
3084 SetNextEventAction(new Process::AttachCompletionHandler(
3085 this, attach_info.GetResumeCount()));
3086 StartPrivateStateThread();
3087 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003088 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003089 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003090
Kate Stoneb9c1b512016-09-06 20:57:50 +00003091 const char *error_string = error.AsCString();
3092 if (error_string == nullptr)
3093 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003094
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 SetExitStatus(-1, error_string);
3096 }
Greg Claytonb766a732011-02-04 01:58:07 +00003097 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003098 }
3099 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003100}
3101
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102void Process::CompleteAttach() {
3103 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3104 LIBLLDB_LOG_TARGET));
3105 if (log)
3106 log->Printf("Process::%s()", __FUNCTION__);
3107
3108 // Let the process subclass figure out at much as it can about the process
3109 // before we go looking for a dynamic loader plug-in.
3110 ArchSpec process_arch;
3111 DidAttach(process_arch);
3112
3113 if (process_arch.IsValid()) {
3114 GetTarget().SetArchitecture(process_arch);
3115 if (log) {
3116 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3117 log->Printf("Process::%s replacing process architecture with DidAttach() "
3118 "architecture: %s",
3119 __FUNCTION__, triple_str ? triple_str : "<null>");
3120 }
3121 }
3122
3123 // We just attached. If we have a platform, ask it for the process
3124 // architecture, and if it isn't
3125 // the same as the one we've already set, switch architectures.
3126 PlatformSP platform_sp(GetTarget().GetPlatform());
3127 assert(platform_sp);
3128 if (platform_sp) {
3129 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3130 if (target_arch.IsValid() &&
3131 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3132 ArchSpec platform_arch;
3133 platform_sp =
3134 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3135 if (platform_sp) {
3136 GetTarget().SetPlatform(platform_sp);
3137 GetTarget().SetArchitecture(platform_arch);
3138 if (log)
3139 log->Printf("Process::%s switching platform to %s and architecture "
3140 "to %s based on info from attach",
3141 __FUNCTION__, platform_sp->GetName().AsCString(""),
3142 platform_arch.GetTriple().getTriple().c_str());
3143 }
3144 } else if (!process_arch.IsValid()) {
3145 ProcessInstanceInfo process_info;
3146 GetProcessInfo(process_info);
3147 const ArchSpec &process_arch = process_info.GetArchitecture();
3148 if (process_arch.IsValid() &&
3149 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3150 GetTarget().SetArchitecture(process_arch);
3151 if (log)
3152 log->Printf("Process::%s switching architecture to %s based on info "
3153 "the platform retrieved for pid %" PRIu64,
3154 __FUNCTION__,
3155 process_arch.GetTriple().getTriple().c_str(), GetID());
3156 }
3157 }
3158 }
3159
3160 // We have completed the attach, now it is time to find the dynamic loader
3161 // plug-in
3162 DynamicLoader *dyld = GetDynamicLoader();
3163 if (dyld) {
3164 dyld->DidAttach();
3165 if (log) {
3166 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3167 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3168 "executable is %s (using %s plugin)",
3169 __FUNCTION__,
3170 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3171 : "<none>",
3172 dyld->GetPluginName().AsCString("<unnamed>"));
3173 }
3174 }
3175
3176 GetJITLoaders().DidAttach();
3177
3178 SystemRuntime *system_runtime = GetSystemRuntime();
3179 if (system_runtime) {
3180 system_runtime->DidAttach();
3181 if (log) {
3182 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3183 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3184 "executable is %s (using %s plugin)",
3185 __FUNCTION__,
3186 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3187 : "<none>",
3188 system_runtime->GetPluginName().AsCString("<unnamed>"));
3189 }
3190 }
3191
Greg Clayton29eeea02017-02-09 18:55:41 +00003192 if (!m_os_ap)
3193 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003194 // Figure out which one is the executable, and set that in our target:
3195 const ModuleList &target_modules = GetTarget().GetImages();
3196 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3197 size_t num_modules = target_modules.GetSize();
3198 ModuleSP new_executable_module_sp;
3199
3200 for (size_t i = 0; i < num_modules; i++) {
3201 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3202 if (module_sp && module_sp->IsExecutable()) {
3203 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3204 new_executable_module_sp = module_sp;
3205 break;
3206 }
3207 }
3208 if (new_executable_module_sp) {
3209 GetTarget().SetExecutableModule(new_executable_module_sp, false);
3210 if (log) {
3211 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3212 log->Printf(
3213 "Process::%s after looping through modules, target executable is %s",
3214 __FUNCTION__,
3215 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3216 : "<none>");
3217 }
3218 }
3219
3220 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
3221}
3222
Zachary Turner31659452016-11-17 21:15:14 +00003223Error Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003224 m_abi_sp.reset();
3225 m_process_input_reader.reset();
3226
3227 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003228 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003229
3230 Error error(DoConnectRemote(strm, remote_url));
3231 if (error.Success()) {
3232 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3233 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003234 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003235
3236 if (state == eStateStopped || state == eStateCrashed) {
3237 // If we attached and actually have a process on the other end, then
3238 // this ended up being the equivalent of an attach.
3239 CompleteAttach();
3240
3241 // This delays passing the stopped event to listeners till
3242 // CompleteAttach gets a chance to complete...
3243 HandlePrivateEvent(event_sp);
3244 }
3245 }
3246
3247 if (PrivateStateThreadIsValid())
3248 ResumePrivateStateThread();
3249 else
3250 StartPrivateStateThread();
3251 }
3252 return error;
3253}
3254
3255Error Process::PrivateResume() {
3256 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3257 LIBLLDB_LOG_STEP));
3258 if (log)
3259 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3260 "private state: %s",
3261 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3262 StateAsCString(m_private_state.GetValue()));
3263
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003264 // If signals handing status changed we might want to update
3265 // our signal filters before resuming.
3266 UpdateAutomaticSignalFiltering();
3267
Kate Stoneb9c1b512016-09-06 20:57:50 +00003268 Error error(WillResume());
3269 // Tell the process it is about to resume before the thread list
3270 if (error.Success()) {
3271 // Now let the thread list know we are about to resume so it
3272 // can let all of our threads know that they are about to be
3273 // resumed. Threads will each be called with
3274 // Thread::WillResume(StateType) where StateType contains the state
3275 // that they are supposed to have when the process is resumed
3276 // (suspended/running/stepping). Threads should also check
3277 // their resume signal in lldb::Thread::GetResumeSignal()
3278 // to see if they are supposed to start back up with a signal.
3279 if (m_thread_list.WillResume()) {
3280 // Last thing, do the PreResumeActions.
3281 if (!RunPreResumeActions()) {
3282 error.SetErrorStringWithFormat(
3283 "Process::PrivateResume PreResumeActions failed, not resuming.");
3284 } else {
3285 m_mod_id.BumpResumeID();
3286 error = DoResume();
3287 if (error.Success()) {
3288 DidResume();
3289 m_thread_list.DidResume();
3290 if (log)
3291 log->Printf("Process thinks the process has resumed.");
3292 }
3293 }
3294 } else {
3295 // Somebody wanted to run without running (e.g. we were faking a step from
3296 // one frame of a set of inlined
3297 // frames that share the same PC to another.) So generate a continue & a
3298 // stopped event,
3299 // and let the world handle them.
3300 if (log)
3301 log->Printf(
3302 "Process::PrivateResume() asked to simulate a start & stop.");
3303
3304 SetPrivateState(eStateRunning);
3305 SetPrivateState(eStateStopped);
3306 }
3307 } else if (log)
3308 log->Printf("Process::PrivateResume() got an error \"%s\".",
3309 error.AsCString("<unknown error>"));
3310 return error;
3311}
3312
3313Error Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3314 if (!StateIsRunningState(m_public_state.GetValue()))
3315 return Error("Process is not running.");
3316
3317 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3318 // in case it was already set and some thread plan logic calls halt on its
3319 // own.
3320 m_clear_thread_plans_on_stop |= clear_thread_plans;
3321
3322 ListenerSP halt_listener_sp(
3323 Listener::MakeListener("lldb.process.halt_listener"));
3324 HijackProcessEvents(halt_listener_sp);
3325
3326 EventSP event_sp;
3327
3328 SendAsyncInterrupt();
3329
3330 if (m_public_state.GetValue() == eStateAttaching) {
3331 // Don't hijack and eat the eStateExited as the code that was doing
3332 // the attach will be waiting for this event...
3333 RestoreProcessEvents();
3334 SetExitStatus(SIGKILL, "Cancelled async attach.");
3335 Destroy(false);
Mehdi Aminic1edf562016-11-11 04:29:25 +00003336 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337 }
3338
3339 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003340 StateType state = WaitForProcessToStop(
3341 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003342 RestoreProcessEvents();
3343
3344 if (state == eStateInvalid || !event_sp) {
3345 // We timed out and didn't get a stop event...
3346 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3347 }
3348
3349 BroadcastEvent(event_sp);
3350
Mehdi Aminic1edf562016-11-11 04:29:25 +00003351 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003352}
3353
3354Error Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3355 Error error;
3356
3357 // Check both the public & private states here. If we're hung evaluating an
3358 // expression, for instance, then
3359 // the public state will be stopped, but we still need to interrupt.
3360 if (m_public_state.GetValue() == eStateRunning ||
3361 m_private_state.GetValue() == eStateRunning) {
3362 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365
Kate Stoneb9c1b512016-09-06 20:57:50 +00003366 ListenerSP listener_sp(
3367 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3368 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369
Pavel Labath19da1f12015-12-07 12:36:52 +00003370 SendAsyncInterrupt();
3371
Kate Stoneb9c1b512016-09-06 20:57:50 +00003372 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003373 StateType state =
3374 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003375
Pavel Labath19da1f12015-12-07 12:36:52 +00003376 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003377
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378 // If the process exited while we were waiting for it to stop, put the
3379 // exited event into
3380 // the shared pointer passed in and return. Our caller doesn't need to do
3381 // anything else, since
3382 // they don't have a process anymore...
3383
3384 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3385 if (log)
3386 log->Printf("Process::%s() Process exited while waiting to stop.",
3387 __FUNCTION__);
3388 return error;
3389 } else
3390 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3391
3392 if (state != eStateStopped) {
3393 if (log)
3394 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3395 StateAsCString(state));
3396 // If we really couldn't stop the process then we should just error out
3397 // here, but if the
3398 // lower levels just bobbled sending the event and we really are stopped,
3399 // then continue on.
3400 StateType private_state = m_private_state.GetValue();
3401 if (private_state != eStateStopped) {
3402 return Error("Attempt to stop the target in order to detach timed out. "
3403 "State = %s",
3404 StateAsCString(GetState()));
3405 }
3406 }
3407 }
3408 return error;
3409}
3410
3411Error Process::Detach(bool keep_stopped) {
3412 EventSP exit_event_sp;
3413 Error error;
3414 m_destroy_in_process = true;
3415
3416 error = WillDetach();
3417
3418 if (error.Success()) {
3419 if (DetachRequiresHalt()) {
3420 error = StopForDestroyOrDetach(exit_event_sp);
3421 if (!error.Success()) {
3422 m_destroy_in_process = false;
3423 return error;
3424 } else if (exit_event_sp) {
3425 // We shouldn't need to do anything else here. There's no process left
3426 // to detach from...
3427 StopPrivateStateThread();
3428 m_destroy_in_process = false;
3429 return error;
3430 }
3431 }
3432
3433 m_thread_list.DiscardThreadPlans();
3434 DisableAllBreakpointSites();
3435
3436 error = DoDetach(keep_stopped);
3437 if (error.Success()) {
3438 DidDetach();
3439 StopPrivateStateThread();
3440 } else {
3441 return error;
3442 }
3443 }
3444 m_destroy_in_process = false;
3445
3446 // If we exited when we were waiting for a process to stop, then
3447 // forward the event here so we don't lose the event
3448 if (exit_event_sp) {
3449 // Directly broadcast our exited event because we shut down our
3450 // private state thread above
3451 BroadcastEvent(exit_event_sp);
3452 }
3453
3454 // If we have been interrupted (to kill us) in the middle of running, we may
3455 // not end up propagating
3456 // the last events through the event system, in which case we might strand the
3457 // write lock. Unlock
3458 // it here so when we do to tear down the process we don't get an error
3459 // destroying the lock.
3460
3461 m_public_run_lock.SetStopped();
3462 return error;
3463}
3464
3465Error Process::Destroy(bool force_kill) {
3466
3467 // Tell ourselves we are in the process of destroying the process, so that we
3468 // don't do any unnecessary work
3469 // that might hinder the destruction. Remember to set this back to false when
3470 // we are done. That way if the attempt
3471 // failed and the process stays around for some reason it won't be in a
3472 // confused state.
3473
3474 if (force_kill)
3475 m_should_detach = false;
3476
3477 if (GetShouldDetach()) {
3478 // FIXME: This will have to be a process setting:
3479 bool keep_stopped = false;
3480 Detach(keep_stopped);
3481 }
3482
3483 m_destroy_in_process = true;
3484
3485 Error error(WillDestroy());
3486 if (error.Success()) {
3487 EventSP exit_event_sp;
3488 if (DestroyRequiresHalt()) {
3489 error = StopForDestroyOrDetach(exit_event_sp);
3490 }
3491
3492 if (m_public_state.GetValue() != eStateRunning) {
3493 // Ditch all thread plans, and remove all our breakpoints: in case we have
3494 // to restart the target to
3495 // kill it, we don't want it hitting a breakpoint...
3496 // Only do this if we've stopped, however, since if we didn't manage to
3497 // halt it above, then
3498 // we're not going to have much luck doing this now.
3499 m_thread_list.DiscardThreadPlans();
3500 DisableAllBreakpointSites();
3501 }
3502
3503 error = DoDestroy();
3504 if (error.Success()) {
3505 DidDestroy();
3506 StopPrivateStateThread();
3507 }
3508 m_stdio_communication.Disconnect();
3509 m_stdio_communication.StopReadThread();
3510 m_stdin_forward = false;
3511
3512 if (m_process_input_reader) {
3513 m_process_input_reader->SetIsDone(true);
3514 m_process_input_reader->Cancel();
3515 m_process_input_reader.reset();
3516 }
3517
3518 // If we exited when we were waiting for a process to stop, then
3519 // forward the event here so we don't lose the event
3520 if (exit_event_sp) {
3521 // Directly broadcast our exited event because we shut down our
3522 // private state thread above
3523 BroadcastEvent(exit_event_sp);
3524 }
3525
3526 // If we have been interrupted (to kill us) in the middle of running, we may
3527 // not end up propagating
3528 // the last events through the event system, in which case we might strand
3529 // the write lock. Unlock
3530 // it here so when we do to tear down the process we don't get an error
3531 // destroying the lock.
3532 m_public_run_lock.SetStopped();
3533 }
3534
3535 m_destroy_in_process = false;
3536
3537 return error;
3538}
3539
3540Error Process::Signal(int signal) {
3541 Error error(WillSignal());
3542 if (error.Success()) {
3543 error = DoSignal(signal);
3544 if (error.Success())
3545 DidSignal();
3546 }
3547 return error;
3548}
3549
3550void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3551 assert(signals_sp && "null signals_sp");
3552 m_unix_signals_sp = signals_sp;
3553}
3554
3555const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3556 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3557 return m_unix_signals_sp;
3558}
3559
3560lldb::ByteOrder Process::GetByteOrder() const {
3561 return GetTarget().GetArchitecture().GetByteOrder();
3562}
3563
3564uint32_t Process::GetAddressByteSize() const {
3565 return GetTarget().GetArchitecture().GetAddressByteSize();
3566}
3567
3568bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3569 const StateType state =
3570 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3571 bool return_value = true;
3572 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3573 LIBLLDB_LOG_PROCESS));
3574
3575 switch (state) {
3576 case eStateDetached:
3577 case eStateExited:
3578 case eStateUnloaded:
3579 m_stdio_communication.SynchronizeWithReadThread();
3580 m_stdio_communication.Disconnect();
3581 m_stdio_communication.StopReadThread();
3582 m_stdin_forward = false;
3583
3584 LLVM_FALLTHROUGH;
3585 case eStateConnected:
3586 case eStateAttaching:
3587 case eStateLaunching:
3588 // These events indicate changes in the state of the debugging session,
3589 // always report them.
3590 return_value = true;
3591 break;
3592 case eStateInvalid:
3593 // We stopped for no apparent reason, don't report it.
3594 return_value = false;
3595 break;
3596 case eStateRunning:
3597 case eStateStepping:
3598 // If we've started the target running, we handle the cases where we
3599 // are already running and where there is a transition from stopped to
3600 // running differently.
3601 // running -> running: Automatically suppress extra running events
3602 // stopped -> running: Report except when there is one or more no votes
3603 // and no yes votes.
3604 SynchronouslyNotifyStateChanged(state);
3605 if (m_force_next_event_delivery)
3606 return_value = true;
3607 else {
3608 switch (m_last_broadcast_state) {
3609 case eStateRunning:
3610 case eStateStepping:
3611 // We always suppress multiple runnings with no PUBLIC stop in between.
3612 return_value = false;
3613 break;
3614 default:
3615 // TODO: make this work correctly. For now always report
3616 // run if we aren't running so we don't miss any running
3617 // events. If I run the lldb/test/thread/a.out file and
3618 // break at main.cpp:58, run and hit the breakpoints on
3619 // multiple threads, then somehow during the stepping over
3620 // of all breakpoints no run gets reported.
3621
3622 // This is a transition from stop to run.
3623 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3624 case eVoteYes:
3625 case eVoteNoOpinion:
3626 return_value = true;
3627 break;
3628 case eVoteNo:
3629 return_value = false;
3630 break;
3631 }
3632 break;
3633 }
3634 }
3635 break;
3636 case eStateStopped:
3637 case eStateCrashed:
3638 case eStateSuspended:
3639 // We've stopped. First see if we're going to restart the target.
3640 // If we are going to stop, then we always broadcast the event.
3641 // If we aren't going to stop, let the thread plans decide if we're going to
3642 // report this event.
3643 // If no thread has an opinion, we don't report it.
3644
3645 m_stdio_communication.SynchronizeWithReadThread();
3646 RefreshStateAfterStop();
3647 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3648 if (log)
3649 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3650 "interrupt, state: %s",
3651 static_cast<void *>(event_ptr), StateAsCString(state));
3652 // Even though we know we are going to stop, we should let the threads
3653 // have a look at the stop,
3654 // so they can properly set their state.
3655 m_thread_list.ShouldStop(event_ptr);
3656 return_value = true;
3657 } else {
3658 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3659 bool should_resume = false;
3660
3661 // It makes no sense to ask "ShouldStop" if we've already been
3662 // restarted...
3663 // Asking the thread list is also not likely to go well, since we are
3664 // running again.
3665 // So in that case just report the event.
3666
3667 if (!was_restarted)
3668 should_resume = !m_thread_list.ShouldStop(event_ptr);
3669
3670 if (was_restarted || should_resume || m_resume_requested) {
3671 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3672 if (log)
3673 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3674 "%s was_restarted: %i stop_vote: %d.",
3675 should_resume, StateAsCString(state), was_restarted,
3676 stop_vote);
3677
3678 switch (stop_vote) {
3679 case eVoteYes:
3680 return_value = true;
3681 break;
3682 case eVoteNoOpinion:
3683 case eVoteNo:
3684 return_value = false;
3685 break;
3686 }
3687
3688 if (!was_restarted) {
3689 if (log)
3690 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3691 "from state: %s",
3692 static_cast<void *>(event_ptr), StateAsCString(state));
3693 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3694 PrivateResume();
3695 }
3696 } else {
3697 return_value = true;
3698 SynchronouslyNotifyStateChanged(state);
3699 }
3700 }
3701 break;
3702 }
3703
3704 // Forcing the next event delivery is a one shot deal. So reset it here.
3705 m_force_next_event_delivery = false;
3706
3707 // We do some coalescing of events (for instance two consecutive running
3708 // events get coalesced.)
3709 // But we only coalesce against events we actually broadcast. So we use
3710 // m_last_broadcast_state
3711 // to track that. NB - you can't use "m_public_state.GetValue()" for that
3712 // purpose, as was originally done,
3713 // because the PublicState reflects the last event pulled off the queue, and
3714 // there may be several
3715 // events stacked up on the queue unserviced. So the PublicState may not
3716 // reflect the last broadcasted event
3717 // yet. m_last_broadcast_state gets updated here.
3718
3719 if (return_value)
3720 m_last_broadcast_state = state;
3721
3722 if (log)
3723 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3724 "broadcast state: %s - %s",
3725 static_cast<void *>(event_ptr), StateAsCString(state),
3726 StateAsCString(m_last_broadcast_state),
3727 return_value ? "YES" : "NO");
3728 return return_value;
3729}
3730
3731bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3732 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3733
3734 bool already_running = PrivateStateThreadIsValid();
3735 if (log)
3736 log->Printf("Process::%s()%s ", __FUNCTION__,
3737 already_running ? " already running"
3738 : " starting private state thread");
3739
3740 if (!is_secondary_thread && already_running)
3741 return true;
3742
3743 // Create a thread that watches our internal state and controls which
3744 // events make it to clients (into the DCProcess event queue).
3745 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003746 uint32_t max_len = llvm::get_max_thread_name_length();
3747 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003748 // On platforms with abbreviated thread name lengths, choose thread names
3749 // that fit within the limit.
3750 if (already_running)
3751 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3752 else
3753 snprintf(thread_name, sizeof(thread_name), "intern-state");
3754 } else {
3755 if (already_running)
3756 snprintf(thread_name, sizeof(thread_name),
3757 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3758 GetID());
3759 else
3760 snprintf(thread_name, sizeof(thread_name),
3761 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3762 }
3763
3764 // Create the private state thread, and start it running.
3765 PrivateStateThreadArgs *args_ptr =
3766 new PrivateStateThreadArgs(this, is_secondary_thread);
3767 m_private_state_thread =
3768 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3769 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3770 if (m_private_state_thread.IsJoinable()) {
3771 ResumePrivateStateThread();
3772 return true;
3773 } else
3774 return false;
3775}
3776
3777void Process::PausePrivateStateThread() {
3778 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3779}
3780
3781void Process::ResumePrivateStateThread() {
3782 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3783}
3784
3785void Process::StopPrivateStateThread() {
3786 if (m_private_state_thread.IsJoinable())
3787 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3788 else {
3789 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3790 if (log)
3791 log->Printf(
3792 "Went to stop the private state thread, but it was already invalid.");
3793 }
3794}
3795
3796void Process::ControlPrivateStateThread(uint32_t signal) {
3797 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3798
3799 assert(signal == eBroadcastInternalStateControlStop ||
3800 signal == eBroadcastInternalStateControlPause ||
3801 signal == eBroadcastInternalStateControlResume);
3802
3803 if (log)
3804 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3805
3806 // Signal the private state thread
3807 if (m_private_state_thread.IsJoinable()) {
3808 // Broadcast the event.
3809 // It is important to do this outside of the if below, because
3810 // it's possible that the thread state is invalid but that the
3811 // thread is waiting on a control event instead of simply being
3812 // on its way out (this should not happen, but it apparently can).
3813 if (log)
3814 log->Printf("Sending control event of type: %d.", signal);
3815 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3816 m_private_state_control_broadcaster.BroadcastEvent(signal,
3817 event_receipt_sp);
3818
3819 // Wait for the event receipt or for the private state thread to exit
3820 bool receipt_received = false;
3821 if (PrivateStateThreadIsValid()) {
3822 while (!receipt_received) {
3823 bool timed_out = false;
3824 // Check for a receipt for 2 seconds and then check if the private state
3825 // thread is still around.
3826 receipt_received = event_receipt_sp->WaitForEventReceived(
3827 std::chrono::seconds(2), &timed_out);
3828 if (!receipt_received) {
3829 // Check if the private state thread is still around. If it isn't then
3830 // we are done waiting
3831 if (!PrivateStateThreadIsValid())
3832 break; // Private state thread exited or is exiting, we are done
3833 }
3834 }
3835 }
3836
3837 if (signal == eBroadcastInternalStateControlStop) {
3838 thread_result_t result = NULL;
3839 m_private_state_thread.Join(&result);
3840 m_private_state_thread.Reset();
3841 }
3842 } else {
3843 if (log)
3844 log->Printf(
3845 "Private state thread already dead, no need to signal it to stop.");
3846 }
3847}
3848
3849void Process::SendAsyncInterrupt() {
3850 if (PrivateStateThreadIsValid())
3851 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3852 nullptr);
3853 else
3854 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3855}
3856
3857void Process::HandlePrivateEvent(EventSP &event_sp) {
3858 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3859 m_resume_requested = false;
3860
3861 const StateType new_state =
3862 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3863
3864 // First check to see if anybody wants a shot at this event:
3865 if (m_next_event_action_ap) {
3866 NextEventAction::EventActionResult action_result =
3867 m_next_event_action_ap->PerformAction(event_sp);
3868 if (log)
3869 log->Printf("Ran next event action, result was %d.", action_result);
3870
3871 switch (action_result) {
3872 case NextEventAction::eEventActionSuccess:
3873 SetNextEventAction(nullptr);
3874 break;
3875
3876 case NextEventAction::eEventActionRetry:
3877 break;
3878
3879 case NextEventAction::eEventActionExit:
3880 // Handle Exiting Here. If we already got an exited event,
3881 // we should just propagate it. Otherwise, swallow this event,
3882 // and set our state to exit so the next event will kill us.
3883 if (new_state != eStateExited) {
3884 // FIXME: should cons up an exited event, and discard this one.
3885 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3886 SetNextEventAction(nullptr);
3887 return;
3888 }
3889 SetNextEventAction(nullptr);
3890 break;
3891 }
3892 }
3893
3894 // See if we should broadcast this state to external clients?
3895 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3896
3897 if (should_broadcast) {
3898 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3899 if (log) {
3900 log->Printf("Process::%s (pid = %" PRIu64
3901 ") broadcasting new state %s (old state %s) to %s",
3902 __FUNCTION__, GetID(), StateAsCString(new_state),
3903 StateAsCString(GetState()),
3904 is_hijacked ? "hijacked" : "public");
3905 }
3906 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3907 if (StateIsRunningState(new_state)) {
3908 // Only push the input handler if we aren't fowarding events,
3909 // as this means the curses GUI is in use...
3910 // Or don't push it if we are launching since it will come up stopped.
3911 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3912 new_state != eStateLaunching && new_state != eStateAttaching) {
3913 PushProcessIOHandler();
3914 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3915 eBroadcastAlways);
3916 if (log)
3917 log->Printf("Process::%s updated m_iohandler_sync to %d",
3918 __FUNCTION__, m_iohandler_sync.GetValue());
3919 }
3920 } else if (StateIsStoppedState(new_state, false)) {
3921 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3922 // If the lldb_private::Debugger is handling the events, we don't
3923 // want to pop the process IOHandler here, we want to do it when
3924 // we receive the stopped event so we can carefully control when
3925 // the process IOHandler is popped because when we stop we want to
3926 // display some text stating how and why we stopped, then maybe some
3927 // process/thread/frame info, and then we want the "(lldb) " prompt
3928 // to show up. If we pop the process IOHandler here, then we will
3929 // cause the command interpreter to become the top IOHandler after
3930 // the process pops off and it will update its prompt right away...
3931 // See the Debugger.cpp file where it calls the function as
3932 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3933 // Otherwise we end up getting overlapping "(lldb) " prompts and
3934 // garbled output.
3935 //
3936 // If we aren't handling the events in the debugger (which is indicated
3937 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3938 // are hijacked, then we always pop the process IO handler manually.
3939 // Hijacking happens when the internal process state thread is running
3940 // thread plans, or when commands want to run in synchronous mode
3941 // and they call "process->WaitForProcessToStop()". An example of
3942 // something
3943 // that will hijack the events is a simple expression:
3944 //
3945 // (lldb) expr (int)puts("hello")
3946 //
3947 // This will cause the internal process state thread to resume and halt
3948 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3949 // events) and we do need the IO handler to be pushed and popped
3950 // correctly.
3951
3952 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3953 PopProcessIOHandler();
3954 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003955 }
3956
3957 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003958 } else {
3959 if (log) {
3960 log->Printf(
3961 "Process::%s (pid = %" PRIu64
3962 ") suppressing state %s (old state %s): should_broadcast == false",
3963 __FUNCTION__, GetID(), StateAsCString(new_state),
3964 StateAsCString(GetState()));
3965 }
3966 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003967}
3968
Kate Stoneb9c1b512016-09-06 20:57:50 +00003969Error Process::HaltPrivate() {
3970 EventSP event_sp;
3971 Error error(WillHalt());
3972 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003973 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003974
3975 // Ask the process subclass to actually halt our process
3976 bool caused_stop;
3977 error = DoHalt(caused_stop);
3978
3979 DidHalt();
3980 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003981}
3982
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983thread_result_t Process::PrivateStateThread(void *arg) {
3984 std::unique_ptr<PrivateStateThreadArgs> args_up(
3985 static_cast<PrivateStateThreadArgs *>(arg));
3986 thread_result_t result =
3987 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3988 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989}
3990
Kate Stoneb9c1b512016-09-06 20:57:50 +00003991thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3992 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003993
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3995 if (log)
3996 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3997 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003998
Kate Stoneb9c1b512016-09-06 20:57:50 +00003999 bool exit_now = false;
4000 bool interrupt_requested = false;
4001 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00004002 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00004003 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004004 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4005 if (log)
4006 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4007 ") got a control event: %d",
4008 __FUNCTION__, static_cast<void *>(this), GetID(),
4009 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00004010
Kate Stoneb9c1b512016-09-06 20:57:50 +00004011 switch (event_sp->GetType()) {
4012 case eBroadcastInternalStateControlStop:
4013 exit_now = true;
4014 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004015
Kate Stoneb9c1b512016-09-06 20:57:50 +00004016 case eBroadcastInternalStateControlPause:
4017 control_only = true;
4018 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004019
Kate Stoneb9c1b512016-09-06 20:57:50 +00004020 case eBroadcastInternalStateControlResume:
4021 control_only = false;
4022 break;
4023 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004024
Kate Stoneb9c1b512016-09-06 20:57:50 +00004025 continue;
4026 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4027 if (m_public_state.GetValue() == eStateAttaching) {
4028 if (log)
4029 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4030 ") woke up with an interrupt while attaching - "
4031 "forwarding interrupt.",
4032 __FUNCTION__, static_cast<void *>(this), GetID());
4033 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4034 } else if (StateIsRunningState(m_last_broadcast_state)) {
4035 if (log)
4036 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4037 ") woke up with an interrupt - Halting.",
4038 __FUNCTION__, static_cast<void *>(this), GetID());
4039 Error error = HaltPrivate();
4040 if (error.Fail() && log)
4041 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4042 ") failed to halt the process: %s",
4043 __FUNCTION__, static_cast<void *>(this), GetID(),
4044 error.AsCString());
4045 // Halt should generate a stopped event. Make a note of the fact that we
4046 // were
4047 // doing the interrupt, so we can set the interrupted flag after we
4048 // receive the
4049 // event. We deliberately set this to true even if HaltPrivate failed,
4050 // so that we
4051 // can interrupt on the next natural stop.
4052 interrupt_requested = true;
4053 } else {
4054 // This can happen when someone (e.g. Process::Halt) sees that we are
4055 // running and
4056 // sends an interrupt request, but the process actually stops before we
4057 // receive
4058 // it. In that case, we can just ignore the request. We use
4059 // m_last_broadcast_state, because the Stopped event may not have been
4060 // popped of
4061 // the event queue yet, which is when the public state gets updated.
4062 if (log)
4063 log->Printf(
4064 "Process::%s ignoring interrupt as we have already stopped.",
4065 __FUNCTION__);
4066 }
4067 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004068 }
4069
Kate Stoneb9c1b512016-09-06 20:57:50 +00004070 const StateType internal_state =
4071 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004072
Kate Stoneb9c1b512016-09-06 20:57:50 +00004073 if (internal_state != eStateInvalid) {
4074 if (m_clear_thread_plans_on_stop &&
4075 StateIsStoppedState(internal_state, true)) {
4076 m_clear_thread_plans_on_stop = false;
4077 m_thread_list.DiscardThreadPlans();
4078 }
4079
4080 if (interrupt_requested) {
4081 if (StateIsStoppedState(internal_state, true)) {
4082 // We requested the interrupt, so mark this as such in the stop event
4083 // so
4084 // clients can tell an interrupted process from a natural stop
4085 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4086 interrupt_requested = false;
4087 } else if (log) {
4088 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4089 "state '%s' received.",
4090 __FUNCTION__, StateAsCString(internal_state));
4091 }
4092 }
4093
4094 HandlePrivateEvent(event_sp);
4095 }
4096
4097 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4098 internal_state == eStateDetached) {
4099 if (log)
4100 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4101 ") about to exit with internal state %s...",
4102 __FUNCTION__, static_cast<void *>(this), GetID(),
4103 StateAsCString(internal_state));
4104
4105 break;
4106 }
4107 }
4108
4109 // Verify log is still enabled before attempting to write to it...
4110 if (log)
4111 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4112 __FUNCTION__, static_cast<void *>(this), GetID());
4113
4114 // If we are a secondary thread, then the primary thread we are working for
4115 // will have already
4116 // acquired the public_run_lock, and isn't done with what it was doing yet, so
4117 // don't
4118 // try to change it on the way out.
4119 if (!is_secondary_thread)
4120 m_public_run_lock.SetStopped();
4121 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004122}
4123
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004124//------------------------------------------------------------------
4125// Process Event Data
4126//------------------------------------------------------------------
4127
Kate Stoneb9c1b512016-09-06 20:57:50 +00004128Process::ProcessEventData::ProcessEventData()
4129 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4130 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131
Kate Stoneb9c1b512016-09-06 20:57:50 +00004132Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4133 StateType state)
4134 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4135 m_update_state(0), m_interrupted(false) {
4136 if (process_sp)
4137 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004138}
4139
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004140Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004141
Kate Stoneb9c1b512016-09-06 20:57:50 +00004142const ConstString &Process::ProcessEventData::GetFlavorString() {
4143 static ConstString g_flavor("Process::ProcessEventData");
4144 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145}
4146
Kate Stoneb9c1b512016-09-06 20:57:50 +00004147const ConstString &Process::ProcessEventData::GetFlavor() const {
4148 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149}
4150
Kate Stoneb9c1b512016-09-06 20:57:50 +00004151void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4152 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004153
Kate Stoneb9c1b512016-09-06 20:57:50 +00004154 if (!process_sp)
4155 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004156
Kate Stoneb9c1b512016-09-06 20:57:50 +00004157 // This function gets called twice for each event, once when the event gets
4158 // pulled
4159 // off of the private process event queue, and then any number of times, first
4160 // when it gets pulled off of
4161 // the public event queue, then other times when we're pretending that this is
4162 // where we stopped at the
4163 // end of expression evaluation. m_update_state is used to distinguish these
4164 // three cases; it is 0 when we're just pulling it off for private handling,
4165 // and > 1 for expression evaluation, and we don't want to do the breakpoint
4166 // command handling then.
4167 if (m_update_state != 1)
4168 return;
4169
4170 process_sp->SetPublicState(
4171 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4172
Jason Molendab3a3cd12016-12-08 06:27:29 +00004173 if (m_state == eStateStopped && !m_restarted) {
4174 // Let process subclasses know we are about to do a public stop and
4175 // do anything they might need to in order to speed up register and
4176 // memory accesses.
4177 process_sp->WillPublicStop();
4178 }
4179
Kate Stoneb9c1b512016-09-06 20:57:50 +00004180 // If this is a halt event, even if the halt stopped with some reason other
4181 // than a plain interrupt (e.g. we had
4182 // already stopped for a breakpoint when the halt request came through) don't
4183 // do the StopInfo actions, as they may
4184 // end up restarting the process.
4185 if (m_interrupted)
4186 return;
4187
4188 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4189 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004190 ThreadList &curr_thread_list = process_sp->GetThreadList();
4191 uint32_t num_threads = curr_thread_list.GetSize();
4192 uint32_t idx;
4193
4194 // The actions might change one of the thread's stop_info's opinions about
4195 // whether we should
4196 // stop the process, so we need to query that as we go.
4197
4198 // One other complication here, is that we try to catch any case where the
4199 // target has run (except for expressions)
4200 // and immediately exit, but if we get that wrong (which is possible) then
4201 // the thread list might have changed, and
4202 // that would cause our iteration here to crash. We could make a copy of
4203 // the thread list, but we'd really like
4204 // to also know if it has changed at all, so we make up a vector of the
4205 // thread ID's and check what we get back
4206 // against this list & bag out if anything differs.
4207 std::vector<uint32_t> thread_index_array(num_threads);
4208 for (idx = 0; idx < num_threads; ++idx)
4209 thread_index_array[idx] =
4210 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4211
4212 // Use this to track whether we should continue from here. We will only
4213 // continue the target running if
4214 // no thread says we should stop. Of course if some thread's PerformAction
4215 // actually sets the target running,
4216 // then it doesn't matter what the other threads say...
4217
4218 bool still_should_stop = false;
4219
4220 // Sometimes - for instance if we have a bug in the stub we are talking to,
4221 // we stop but no thread has a
4222 // valid stop reason. In that case we should just stop, because we have no
4223 // way of telling what the right
4224 // thing to do is, and it's better to let the user decide than continue
4225 // behind their backs.
4226
4227 bool does_anybody_have_an_opinion = false;
4228
4229 for (idx = 0; idx < num_threads; ++idx) {
4230 curr_thread_list = process_sp->GetThreadList();
4231 if (curr_thread_list.GetSize() != num_threads) {
4232 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4233 LIBLLDB_LOG_PROCESS));
4234 if (log)
4235 log->Printf(
4236 "Number of threads changed from %u to %u while processing event.",
4237 num_threads, curr_thread_list.GetSize());
4238 break;
4239 }
4240
4241 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4242
4243 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4244 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4245 LIBLLDB_LOG_PROCESS));
4246 if (log)
4247 log->Printf("The thread at position %u changed from %u to %u while "
4248 "processing event.",
4249 idx, thread_index_array[idx], thread_sp->GetIndexID());
4250 break;
4251 }
4252
4253 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4254 if (stop_info_sp && stop_info_sp->IsValid()) {
4255 does_anybody_have_an_opinion = true;
4256 bool this_thread_wants_to_stop;
4257 if (stop_info_sp->GetOverrideShouldStop()) {
4258 this_thread_wants_to_stop =
4259 stop_info_sp->GetOverriddenShouldStopValue();
4260 } else {
4261 stop_info_sp->PerformAction(event_ptr);
4262 // The stop action might restart the target. If it does, then we want
4263 // to mark that in the
4264 // event so that whoever is receiving it will know to wait for the
4265 // running event and reflect
4266 // that state appropriately.
4267 // We also need to stop processing actions, since they aren't
4268 // expecting the target to be running.
4269
4270 // FIXME: we might have run.
4271 if (stop_info_sp->HasTargetRunSinceMe()) {
4272 SetRestarted(true);
4273 break;
4274 }
4275
4276 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004277 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004278
4279 if (!still_should_stop)
4280 still_should_stop = this_thread_wants_to_stop;
4281 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004282 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004283
4284 if (!GetRestarted()) {
4285 if (!still_should_stop && does_anybody_have_an_opinion) {
4286 // We've been asked to continue, so do that here.
4287 SetRestarted(true);
4288 // Use the public resume method here, since this is just
4289 // extending a public resume.
4290 process_sp->PrivateResume();
4291 } else {
4292 // If we didn't restart, run the Stop Hooks here:
4293 // They might also restart the target, so watch for that.
4294 process_sp->GetTarget().RunStopHooks();
4295 if (process_sp->GetPrivateState() == eStateRunning)
4296 SetRestarted(true);
4297 }
4298 }
4299 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004300}
4301
Kate Stoneb9c1b512016-09-06 20:57:50 +00004302void Process::ProcessEventData::Dump(Stream *s) const {
4303 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004304
Kate Stoneb9c1b512016-09-06 20:57:50 +00004305 if (process_sp)
4306 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4307 static_cast<void *>(process_sp.get()), process_sp->GetID());
4308 else
4309 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004310
Kate Stoneb9c1b512016-09-06 20:57:50 +00004311 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004312}
4313
4314const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004315Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4316 if (event_ptr) {
4317 const EventData *event_data = event_ptr->GetData();
4318 if (event_data &&
4319 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4320 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4321 }
4322 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004323}
4324
4325ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004326Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4327 ProcessSP process_sp;
4328 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4329 if (data)
4330 process_sp = data->GetProcessSP();
4331 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004332}
4333
Kate Stoneb9c1b512016-09-06 20:57:50 +00004334StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4335 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4336 if (data == nullptr)
4337 return eStateInvalid;
4338 else
4339 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004340}
4341
Kate Stoneb9c1b512016-09-06 20:57:50 +00004342bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4343 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4344 if (data == nullptr)
4345 return false;
4346 else
4347 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348}
4349
Kate Stoneb9c1b512016-09-06 20:57:50 +00004350void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4351 bool new_value) {
4352 ProcessEventData *data =
4353 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4354 if (data != nullptr)
4355 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004356}
4357
Jim Ingham0161b492013-02-09 01:29:05 +00004358size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004359Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4360 ProcessEventData *data =
4361 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4362 if (data != nullptr)
4363 return data->GetNumRestartedReasons();
4364 else
4365 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004366}
4367
4368const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004369Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4370 size_t idx) {
4371 ProcessEventData *data =
4372 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4373 if (data != nullptr)
4374 return data->GetRestartedReasonAtIndex(idx);
4375 else
4376 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004377}
4378
Kate Stoneb9c1b512016-09-06 20:57:50 +00004379void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4380 const char *reason) {
4381 ProcessEventData *data =
4382 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4383 if (data != nullptr)
4384 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004385}
4386
Kate Stoneb9c1b512016-09-06 20:57:50 +00004387bool Process::ProcessEventData::GetInterruptedFromEvent(
4388 const Event *event_ptr) {
4389 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4390 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004392 else
4393 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004394}
4395
Kate Stoneb9c1b512016-09-06 20:57:50 +00004396void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4397 bool new_value) {
4398 ProcessEventData *data =
4399 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4400 if (data != nullptr)
4401 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004402}
4403
Kate Stoneb9c1b512016-09-06 20:57:50 +00004404bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4405 ProcessEventData *data =
4406 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4407 if (data) {
4408 data->SetUpdateStateOnRemoval();
4409 return true;
4410 }
4411 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004412}
4413
Kate Stoneb9c1b512016-09-06 20:57:50 +00004414lldb::TargetSP Process::CalculateTarget() { return m_target_sp.lock(); }
4415
4416void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4417 exe_ctx.SetTargetPtr(&GetTarget());
4418 exe_ctx.SetProcessPtr(this);
4419 exe_ctx.SetThreadPtr(nullptr);
4420 exe_ctx.SetFramePtr(nullptr);
4421}
4422
4423// uint32_t
4424// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4425// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004426//{
4427// return 0;
4428//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004429//
4430// ArchSpec
4431// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004432//{
4433// return Host::GetArchSpecForExistingProcess (pid);
4434//}
4435//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004436// ArchSpec
4437// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004438//{
4439// return Host::GetArchSpecForExistingProcess (process_name);
4440//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004441
Kate Stoneb9c1b512016-09-06 20:57:50 +00004442void Process::AppendSTDOUT(const char *s, size_t len) {
4443 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4444 m_stdout_data.append(s, len);
4445 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4446 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004447}
4448
Kate Stoneb9c1b512016-09-06 20:57:50 +00004449void Process::AppendSTDERR(const char *s, size_t len) {
4450 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4451 m_stderr_data.append(s, len);
4452 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4453 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004454}
4455
Kate Stoneb9c1b512016-09-06 20:57:50 +00004456void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4457 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4458 m_profile_data.push_back(one_profile_data);
4459 BroadcastEventIfUnique(eBroadcastBitProfileData,
4460 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004461}
4462
Kate Stoneb9c1b512016-09-06 20:57:50 +00004463void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4464 const StructuredDataPluginSP &plugin_sp) {
4465 BroadcastEvent(
4466 eBroadcastBitStructuredData,
4467 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004468}
4469
4470StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004471Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4472 auto find_it = m_structured_data_plugin_map.find(type_name);
4473 if (find_it != m_structured_data_plugin_map.end())
4474 return find_it->second;
4475 else
4476 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004477}
4478
Kate Stoneb9c1b512016-09-06 20:57:50 +00004479size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Error &error) {
4480 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4481 if (m_profile_data.empty())
4482 return 0;
4483
4484 std::string &one_profile_data = m_profile_data.front();
4485 size_t bytes_available = one_profile_data.size();
4486 if (bytes_available > 0) {
4487 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4488 if (log)
4489 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4490 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4491 if (bytes_available > buf_size) {
4492 memcpy(buf, one_profile_data.c_str(), buf_size);
4493 one_profile_data.erase(0, buf_size);
4494 bytes_available = buf_size;
4495 } else {
4496 memcpy(buf, one_profile_data.c_str(), bytes_available);
4497 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004498 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004499 }
4500 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004501}
4502
Greg Clayton93e86192011-11-13 04:45:22 +00004503//------------------------------------------------------------------
4504// Process STDIO
4505//------------------------------------------------------------------
4506
Kate Stoneb9c1b512016-09-06 20:57:50 +00004507size_t Process::GetSTDOUT(char *buf, size_t buf_size, Error &error) {
4508 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4509 size_t bytes_available = m_stdout_data.size();
4510 if (bytes_available > 0) {
4511 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4512 if (log)
4513 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4514 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4515 if (bytes_available > buf_size) {
4516 memcpy(buf, m_stdout_data.c_str(), buf_size);
4517 m_stdout_data.erase(0, buf_size);
4518 bytes_available = buf_size;
4519 } else {
4520 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4521 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004522 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004523 }
4524 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004525}
4526
Kate Stoneb9c1b512016-09-06 20:57:50 +00004527size_t Process::GetSTDERR(char *buf, size_t buf_size, Error &error) {
4528 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4529 size_t bytes_available = m_stderr_data.size();
4530 if (bytes_available > 0) {
4531 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4532 if (log)
4533 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4534 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4535 if (bytes_available > buf_size) {
4536 memcpy(buf, m_stderr_data.c_str(), buf_size);
4537 m_stderr_data.erase(0, buf_size);
4538 bytes_available = buf_size;
4539 } else {
4540 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4541 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004542 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004543 }
4544 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004545}
4546
Kate Stoneb9c1b512016-09-06 20:57:50 +00004547void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4548 size_t src_len) {
4549 Process *process = (Process *)baton;
4550 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004551}
4552
Kate Stoneb9c1b512016-09-06 20:57:50 +00004553class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004554public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004555 IOHandlerProcessSTDIO(Process *process, int write_fd)
4556 : IOHandler(process->GetTarget().GetDebugger(),
4557 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004558 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004559 m_pipe.CreateNew(false);
4560 m_read_file.SetDescriptor(GetInputFD(), false);
4561 }
4562
4563 ~IOHandlerProcessSTDIO() override = default;
4564
4565 // Each IOHandler gets to run until it is done. It should read data
4566 // from the "in" and place output into "out" and "err and return
4567 // when done.
4568 void Run() override {
4569 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4570 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4571 SetIsDone(true);
4572 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004573 }
4574
Kate Stoneb9c1b512016-09-06 20:57:50 +00004575 SetIsDone(false);
4576 const int read_fd = m_read_file.GetDescriptor();
4577 TerminalState terminal_state;
4578 terminal_state.Save(read_fd, false);
4579 Terminal terminal(read_fd);
4580 terminal.SetCanonical(false);
4581 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004582// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004583#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004584 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4585 m_is_running = true;
4586 while (!GetIsDone()) {
4587 SelectHelper select_helper;
4588 select_helper.FDSetRead(read_fd);
4589 select_helper.FDSetRead(pipe_read_fd);
4590 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004591
Kate Stoneb9c1b512016-09-06 20:57:50 +00004592 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004593 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004594 } else {
4595 char ch = 0;
4596 size_t n;
4597 if (select_helper.FDIsSetRead(read_fd)) {
4598 n = 1;
4599 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4600 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4601 SetIsDone(true);
4602 } else
4603 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004604 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004605 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4606 size_t bytes_read;
4607 // Consume the interrupt byte
4608 Error error = m_pipe.Read(&ch, 1, bytes_read);
4609 if (error.Success()) {
4610 switch (ch) {
4611 case 'q':
4612 SetIsDone(true);
4613 break;
4614 case 'i':
4615 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004616 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004617 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004618 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004619 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004620 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004621 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004622 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004623 m_is_running = false;
4624#endif
4625 terminal_state.Restore();
4626 }
4627
4628 void Cancel() override {
4629 SetIsDone(true);
4630 // Only write to our pipe to cancel if we are in
4631 // IOHandlerProcessSTDIO::Run().
4632 // We can end up with a python command that is being run from the command
4633 // interpreter:
4634 //
4635 // (lldb) step_process_thousands_of_times
4636 //
4637 // In this case the command interpreter will be in the middle of handling
4638 // the command and if the process pushes and pops the IOHandler thousands
4639 // of times, we can end up writing to m_pipe without ever consuming the
4640 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4641 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4642 if (m_is_running) {
4643 char ch = 'q'; // Send 'q' for quit
4644 size_t bytes_written = 0;
4645 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004646 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004647 }
4648
4649 bool Interrupt() override {
4650 // Do only things that are safe to do in an interrupt context (like in
4651 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4652 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4653 // that was written to the pipe and then call
4654 // m_process->SendAsyncInterrupt()
4655 // from a much safer location in code.
4656 if (m_active) {
4657 char ch = 'i'; // Send 'i' for interrupt
4658 size_t bytes_written = 0;
4659 Error result = m_pipe.Write(&ch, 1, bytes_written);
4660 return result.Success();
4661 } else {
4662 // This IOHandler might be pushed on the stack, but not being run
4663 // currently
4664 // so do the right thing if we aren't actively watching for STDIN by
4665 // sending
4666 // the interrupt to the process. Otherwise the write to the pipe above
4667 // would
4668 // do nothing. This can happen when the command interpreter is running and
4669 // gets a "expression ...". It will be on the IOHandler thread and sending
4670 // the input is complete to the delegate which will cause the expression
4671 // to
4672 // run, which will push the process IO handler, but not run it.
4673
4674 if (StateIsRunningState(m_process->GetState())) {
4675 m_process->SendAsyncInterrupt();
4676 return true;
4677 }
4678 }
4679 return false;
4680 }
4681
4682 void GotEOF() override {}
4683
Greg Clayton44d93782014-01-27 23:43:24 +00004684protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004685 Process *m_process;
4686 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4687 File m_write_file; // Write to this file (usually the master pty for getting
4688 // io to debuggee)
4689 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004690 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004691};
4692
Kate Stoneb9c1b512016-09-06 20:57:50 +00004693void Process::SetSTDIOFileDescriptor(int fd) {
4694 // First set up the Read Thread for reading/handling process I/O
4695
4696 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4697 new ConnectionFileDescriptor(fd, true));
4698
4699 if (conn_ap) {
4700 m_stdio_communication.SetConnection(conn_ap.release());
4701 if (m_stdio_communication.IsConnected()) {
4702 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4703 STDIOReadThreadBytesReceived, this);
4704 m_stdio_communication.StartReadThread();
4705
4706 // Now read thread is set up, set up input reader.
4707
4708 if (!m_process_input_reader)
4709 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004710 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004711 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004712}
4713
Kate Stoneb9c1b512016-09-06 20:57:50 +00004714bool Process::ProcessIOHandlerIsActive() {
4715 IOHandlerSP io_handler_sp(m_process_input_reader);
4716 if (io_handler_sp)
4717 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4718 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004719}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004720bool Process::PushProcessIOHandler() {
4721 IOHandlerSP io_handler_sp(m_process_input_reader);
4722 if (io_handler_sp) {
4723 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4724 if (log)
4725 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004726
Kate Stoneb9c1b512016-09-06 20:57:50 +00004727 io_handler_sp->SetIsDone(false);
4728 GetTarget().GetDebugger().PushIOHandler(io_handler_sp);
4729 return true;
4730 }
4731 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004732}
4733
Kate Stoneb9c1b512016-09-06 20:57:50 +00004734bool Process::PopProcessIOHandler() {
4735 IOHandlerSP io_handler_sp(m_process_input_reader);
4736 if (io_handler_sp)
4737 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4738 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004739}
4740
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004741// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004742void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004743
Kate Stoneb9c1b512016-09-06 20:57:50 +00004744void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004745
Kate Stoneb9c1b512016-09-06 20:57:50 +00004746namespace {
4747// RestorePlanState is used to record the "is private", "is master" and "okay to
4748// discard" fields of
4749// the plan we are running, and reset it on Clean or on destruction.
4750// It will only reset the state once, so you can call Clean and then monkey with
4751// the state and it
4752// won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004753
Kate Stoneb9c1b512016-09-06 20:57:50 +00004754class RestorePlanState {
4755public:
4756 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4757 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4758 if (m_thread_plan_sp) {
4759 m_private = m_thread_plan_sp->GetPrivate();
4760 m_is_master = m_thread_plan_sp->IsMasterPlan();
4761 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4762 }
4763 }
4764
4765 ~RestorePlanState() { Clean(); }
4766
4767 void Clean() {
4768 if (!m_already_reset && m_thread_plan_sp) {
4769 m_already_reset = true;
4770 m_thread_plan_sp->SetPrivate(m_private);
4771 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4772 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4773 }
4774 }
4775
4776private:
4777 lldb::ThreadPlanSP m_thread_plan_sp;
4778 bool m_already_reset;
4779 bool m_private;
4780 bool m_is_master;
4781 bool m_okay_to_discard;
4782};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004783} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004784
Pavel Labath2ce22162016-12-01 10:57:30 +00004785static microseconds
4786GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4787 const milliseconds default_one_thread_timeout(250);
4788
4789 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004790 if (!options.GetTimeout()) {
4791 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4792 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004793 }
4794
4795 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004796 if (options.GetOneThreadTimeout())
4797 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004798
4799 // Otherwise use half the total timeout, bounded by the
4800 // default_one_thread_timeout.
4801 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004802 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004803}
4804
4805static Timeout<std::micro>
4806GetExpressionTimeout(const EvaluateExpressionOptions &options,
4807 bool before_first_timeout) {
4808 // If we are going to run all threads the whole time, or if we are only
4809 // going to run one thread, we can just return the overall timeout.
4810 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004811 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004812
4813 if (before_first_timeout)
4814 return GetOneThreadExpressionTimeout(options);
4815
Pavel Labath43d35412016-12-06 11:24:51 +00004816 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004817 return llvm::None;
4818 else
Pavel Labath43d35412016-12-06 11:24:51 +00004819 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004820}
4821
Jim Ingham1624a2d2014-05-05 02:26:40 +00004822ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004823Process::RunThreadPlan(ExecutionContext &exe_ctx,
4824 lldb::ThreadPlanSP &thread_plan_sp,
4825 const EvaluateExpressionOptions &options,
4826 DiagnosticManager &diagnostic_manager) {
4827 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004828
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4830
4831 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004832 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004833 eDiagnosticSeverityError,
4834 "RunThreadPlan called with empty thread plan.");
4835 return eExpressionSetupError;
4836 }
4837
4838 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004839 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004840 eDiagnosticSeverityError,
4841 "RunThreadPlan called with an invalid thread plan.");
4842 return eExpressionSetupError;
4843 }
4844
4845 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004846 diagnostic_manager.PutString(eDiagnosticSeverityError,
4847 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004848 return eExpressionSetupError;
4849 }
4850
4851 Thread *thread = exe_ctx.GetThreadPtr();
4852 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004853 diagnostic_manager.PutString(eDiagnosticSeverityError,
4854 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004855 return eExpressionSetupError;
4856 }
4857
4858 // We need to change some of the thread plan attributes for the thread plan
4859 // runner. This will restore them
4860 // when we are done:
4861
4862 RestorePlanState thread_plan_restorer(thread_plan_sp);
4863
4864 // We rely on the thread plan we are running returning "PlanCompleted" if when
4865 // it successfully completes.
4866 // For that to be true the plan can't be private - since private plans
4867 // suppress themselves in the
4868 // GetCompletedPlan call.
4869
4870 thread_plan_sp->SetPrivate(false);
4871
4872 // The plans run with RunThreadPlan also need to be terminal master plans or
4873 // when they are done we will end
4874 // up asking the plan above us whether we should stop, which may give the
4875 // wrong answer.
4876
4877 thread_plan_sp->SetIsMasterPlan(true);
4878 thread_plan_sp->SetOkayToDiscard(false);
4879
4880 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004881 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004882 eDiagnosticSeverityError,
4883 "RunThreadPlan called while the private state was not stopped.");
4884 return eExpressionSetupError;
4885 }
4886
4887 // Save the thread & frame from the exe_ctx for restoration after we run
4888 const uint32_t thread_idx_id = thread->GetIndexID();
4889 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4890 if (!selected_frame_sp) {
4891 thread->SetSelectedFrame(nullptr);
4892 selected_frame_sp = thread->GetSelectedFrame();
4893 if (!selected_frame_sp) {
4894 diagnostic_manager.Printf(
4895 eDiagnosticSeverityError,
4896 "RunThreadPlan called without a selected frame on thread %d",
4897 thread_idx_id);
4898 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004899 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004900 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004901
Pavel Labath2ce22162016-12-01 10:57:30 +00004902 // Make sure the timeout values make sense. The one thread timeout needs to be
4903 // smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004904 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4905 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004906 diagnostic_manager.PutString(eDiagnosticSeverityError,
4907 "RunThreadPlan called with one thread "
4908 "timeout greater than total timeout");
4909 return eExpressionSetupError;
4910 }
4911
Kate Stoneb9c1b512016-09-06 20:57:50 +00004912 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004913
Kate Stoneb9c1b512016-09-06 20:57:50 +00004914 // N.B. Running the target may unset the currently selected thread and frame.
4915 // We don't want to do that either,
4916 // so we should arrange to reset them as well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004917
Kate Stoneb9c1b512016-09-06 20:57:50 +00004918 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004919
Kate Stoneb9c1b512016-09-06 20:57:50 +00004920 uint32_t selected_tid;
4921 StackID selected_stack_id;
4922 if (selected_thread_sp) {
4923 selected_tid = selected_thread_sp->GetIndexID();
4924 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4925 } else {
4926 selected_tid = LLDB_INVALID_THREAD_ID;
4927 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004928
Kate Stoneb9c1b512016-09-06 20:57:50 +00004929 HostThread backup_private_state_thread;
4930 lldb::StateType old_state = eStateInvalid;
4931 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004932
Kate Stoneb9c1b512016-09-06 20:57:50 +00004933 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4934 LIBLLDB_LOG_PROCESS));
4935 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4936 // Yikes, we are running on the private state thread! So we can't wait for
4937 // public events on this thread, since
4938 // we are the thread that is generating public events.
4939 // The simplest thing to do is to spin up a temporary thread to handle
4940 // private state thread events while
4941 // we are fielding public events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004942 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004943 log->Printf("Running thread plan on private state thread, spinning up "
4944 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004945
Kate Stoneb9c1b512016-09-06 20:57:50 +00004946 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004947
Kate Stoneb9c1b512016-09-06 20:57:50 +00004948 // One other bit of business: we want to run just this thread plan and
4949 // anything it pushes, and then stop,
4950 // returning control here.
4951 // But in the normal course of things, the plan above us on the stack would
4952 // be given a shot at the stop
4953 // event before deciding to stop, and we don't want that. So we insert a
4954 // "stopper" base plan on the stack
4955 // before the plan we want to run. Since base plans always stop and return
4956 // control to the user, that will
4957 // do just what we want.
4958 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4959 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4960 // Have to make sure our public state is stopped, since otherwise the
4961 // reporting logic below doesn't work correctly.
4962 old_state = m_public_state.GetValue();
4963 m_public_state.SetValueNoLock(eStateStopped);
4964
4965 // Now spin up the private state thread:
4966 StartPrivateStateThread(true);
4967 }
4968
4969 thread->QueueThreadPlan(
4970 thread_plan_sp, false); // This used to pass "true" does that make sense?
4971
4972 if (options.GetDebug()) {
4973 // In this case, we aren't actually going to run, we just want to stop right
4974 // away.
4975 // Flush this thread so we will refetch the stacks and show the correct
4976 // backtrace.
4977 // FIXME: To make this prettier we should invent some stop reason for this,
4978 // but that
4979 // is only cosmetic, and this functionality is only of use to lldb
4980 // developers who can
4981 // live with not pretty...
4982 thread->Flush();
4983 return eExpressionStoppedForDebug;
4984 }
4985
4986 ListenerSP listener_sp(
4987 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4988
4989 lldb::EventSP event_to_broadcast_sp;
4990
4991 {
4992 // This process event hijacker Hijacks the Public events and its destructor
4993 // makes sure that the process events get
4994 // restored on exit to the function.
4995 //
4996 // If the event needs to propagate beyond the hijacker (e.g., the process
4997 // exits during execution), then the event
4998 // is put into event_to_broadcast_sp for rebroadcasting.
4999
5000 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5001
5002 if (log) {
5003 StreamString s;
5004 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5005 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5006 " to run thread plan \"%s\".",
5007 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00005008 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005009
5010 bool got_event;
5011 lldb::EventSP event_sp;
5012 lldb::StateType stop_state = lldb::eStateInvalid;
5013
5014 bool before_first_timeout = true; // This is set to false the first time
5015 // that we have to halt the target.
5016 bool do_resume = true;
5017 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005018
5019 // This is just for accounting:
5020 uint32_t num_resumes = 0;
5021
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005023 // going to run one thread, then we don't need the first timeout. So we
5024 // pretend we are after the first timeout already.
5025 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005026 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005027
Kate Stoneb9c1b512016-09-06 20:57:50 +00005028 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005029 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5030 options.GetStopOthers(), options.GetTryAllThreads(),
5031 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005032
5033 // This isn't going to work if there are unfetched events on the queue.
5034 // Are there cases where we might want to run the remaining events here, and
5035 // then try to
5036 // call the function? That's probably being too tricky for our own good.
5037
5038 Event *other_events = listener_sp->PeekAtNextEvent();
5039 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005040 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005041 eDiagnosticSeverityError,
5042 "RunThreadPlan called with pending events on the queue.");
5043 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005044 }
5045
Kate Stoneb9c1b512016-09-06 20:57:50 +00005046 // We also need to make sure that the next event is delivered. We might be
5047 // calling a function as part of
5048 // a thread plan, in which case the last delivered event could be the
5049 // running event, and we don't want
5050 // event coalescing to cause us to lose OUR running event...
5051 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005052
Kate Stoneb9c1b512016-09-06 20:57:50 +00005053// This while loop must exit out the bottom, there's cleanup that we need to do
5054// when we are done.
5055// So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005056
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5058 // It's pretty much impossible to write test cases for things like:
5059 // One thread timeout expires, I go to halt, but the process already stopped
5060 // on the function call stop breakpoint. Turning on this define will make
5061 // us not
5062 // fetch the first event till after the halt. So if you run a quick
5063 // function, it will have
5064 // completed, and the completion event will be waiting, when you interrupt
5065 // for halt.
5066 // The expression evaluation should still succeed.
5067 bool miss_first_event = true;
5068#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005069 while (true) {
5070 // We usually want to resume the process if we get to the top of the loop.
5071 // The only exception is if we get two running events with no intervening
5072 // stop, which can happen, we will just wait for then next stop event.
5073 if (log)
5074 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5075 "before_first_timeout: %i.",
5076 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005077
Kate Stoneb9c1b512016-09-06 20:57:50 +00005078 if (do_resume || handle_running_event) {
5079 // Do the initial resume and wait for the running event before going
5080 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005081
Kate Stoneb9c1b512016-09-06 20:57:50 +00005082 if (do_resume) {
5083 num_resumes++;
5084 Error resume_error = PrivateResume();
5085 if (!resume_error.Success()) {
5086 diagnostic_manager.Printf(
5087 eDiagnosticSeverityError,
5088 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5089 resume_error.AsCString());
5090 return_value = eExpressionSetupError;
5091 break;
5092 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005093 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005094
Pavel Labathd35031e12016-11-30 10:41:42 +00005095 got_event =
5096 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005097 if (!got_event) {
5098 if (log)
5099 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5100 "resume %" PRIu32 ", exiting.",
5101 num_resumes);
5102
5103 diagnostic_manager.Printf(eDiagnosticSeverityError,
5104 "didn't get any event after resume %" PRIu32
5105 ", exiting.",
5106 num_resumes);
5107 return_value = eExpressionSetupError;
5108 break;
5109 }
5110
5111 stop_state =
5112 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5113
5114 if (stop_state != eStateRunning) {
5115 bool restarted = false;
5116
5117 if (stop_state == eStateStopped) {
5118 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5119 event_sp.get());
5120 if (log)
5121 log->Printf(
5122 "Process::RunThreadPlan(): didn't get running event after "
5123 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5124 "handle_running_event: %i).",
5125 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5126 handle_running_event);
5127 }
5128
5129 if (restarted) {
5130 // This is probably an overabundance of caution, I don't think I
5131 // should ever get a stopped & restarted
5132 // event here. But if I do, the best thing is to Halt and then get
5133 // out of here.
5134 const bool clear_thread_plans = false;
5135 const bool use_run_lock = false;
5136 Halt(clear_thread_plans, use_run_lock);
5137 }
5138
5139 diagnostic_manager.Printf(
5140 eDiagnosticSeverityError,
5141 "didn't get running event after initial resume, got %s instead.",
5142 StateAsCString(stop_state));
5143 return_value = eExpressionSetupError;
5144 break;
5145 }
5146
5147 if (log)
5148 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5149 // We need to call the function synchronously, so spin waiting for it to
5150 // return.
5151 // If we get interrupted while executing, we're going to lose our
5152 // context, and
5153 // won't be able to gather the result at this point.
5154 // We set the timeout AFTER the resume, since the resume takes some time
5155 // and we
5156 // don't want to charge that to the timeout.
5157 } else {
5158 if (log)
5159 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5160 }
5161
Kate Stoneb9c1b512016-09-06 20:57:50 +00005162 do_resume = true;
5163 handle_running_event = true;
5164
5165 // Now wait for the process to stop again:
5166 event_sp.reset();
5167
Pavel Labath2ce22162016-12-01 10:57:30 +00005168 Timeout<std::micro> timeout =
5169 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005170 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005171 if (timeout) {
5172 auto now = system_clock::now();
5173 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5174 "endpoint is %s",
5175 llvm::to_string(now).c_str(),
5176 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005177 } else {
5178 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005179 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005180 }
5181
5182#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5183 // See comment above...
5184 if (miss_first_event) {
5185 usleep(1000);
5186 miss_first_event = false;
5187 got_event = false;
5188 } else
5189#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005190 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005191
5192 if (got_event) {
5193 if (event_sp) {
5194 bool keep_going = false;
5195 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5196 const bool clear_thread_plans = false;
5197 const bool use_run_lock = false;
5198 Halt(clear_thread_plans, use_run_lock);
5199 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005200 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5201 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005202 if (log)
5203 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5204 "eBroadcastBitInterrupted, exiting.");
5205 break;
5206 } else {
5207 stop_state =
5208 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5209 if (log)
5210 log->Printf(
5211 "Process::RunThreadPlan(): in while loop, got event: %s.",
5212 StateAsCString(stop_state));
5213
5214 switch (stop_state) {
5215 case lldb::eStateStopped: {
5216 // We stopped, figure out what we are going to do now.
5217 ThreadSP thread_sp =
5218 GetThreadList().FindThreadByIndexID(thread_idx_id);
5219 if (!thread_sp) {
5220 // Ooh, our thread has vanished. Unlikely that this was
5221 // successful execution...
5222 if (log)
5223 log->Printf("Process::RunThreadPlan(): execution completed "
5224 "but our thread (index-id=%u) has vanished.",
5225 thread_idx_id);
5226 return_value = eExpressionInterrupted;
5227 } else {
5228 // If we were restarted, we just need to go back up to fetch
5229 // another event.
5230 if (Process::ProcessEventData::GetRestartedFromEvent(
5231 event_sp.get())) {
5232 if (log) {
5233 log->Printf("Process::RunThreadPlan(): Got a stop and "
5234 "restart, so we'll continue waiting.");
5235 }
5236 keep_going = true;
5237 do_resume = false;
5238 handle_running_event = true;
5239 } else {
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005240 ThreadPlanSP plan = thread->GetCompletedPlan();
5241 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005242
Kate Stoneb9c1b512016-09-06 20:57:50 +00005243 if (log)
5244 log->PutCString("Process::RunThreadPlan(): execution "
5245 "completed successfully.");
5246
5247 // Restore the plan state so it will get reported as
5248 // intended when we are done.
5249 thread_plan_restorer.Clean();
5250
5251 return_value = eExpressionCompleted;
5252 } else {
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005253 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005254 // Something restarted the target, so just wait for it to
5255 // stop for real.
Boris Ulasevich86aaa8a2017-02-15 11:42:47 +00005256 if (stop_info_sp &&
5257 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005258 if (log)
5259 log->Printf("Process::RunThreadPlan() stopped for "
5260 "breakpoint: %s.",
5261 stop_info_sp->GetDescription());
5262 return_value = eExpressionHitBreakpoint;
5263 if (!options.DoesIgnoreBreakpoints()) {
5264 // Restore the plan state and then force Private to
5265 // false. We are
5266 // going to stop because of this plan so we need it to
5267 // become a public
5268 // plan or it won't report correctly when we continue to
5269 // its termination
5270 // later on.
5271 thread_plan_restorer.Clean();
5272 if (thread_plan_sp)
5273 thread_plan_sp->SetPrivate(false);
5274 event_to_broadcast_sp = event_sp;
5275 }
5276 } else {
5277 if (log)
5278 log->PutCString("Process::RunThreadPlan(): thread plan "
5279 "didn't successfully complete.");
5280 if (!options.DoesUnwindOnError())
5281 event_to_broadcast_sp = event_sp;
5282 return_value = eExpressionInterrupted;
5283 }
5284 }
5285 }
5286 }
5287 } break;
5288
5289 case lldb::eStateRunning:
5290 // This shouldn't really happen, but sometimes we do get two
5291 // running events without an
5292 // intervening stop, and in that case we should just go back to
5293 // waiting for the stop.
5294 do_resume = false;
5295 keep_going = true;
5296 handle_running_event = false;
5297 break;
5298
5299 default:
5300 if (log)
5301 log->Printf("Process::RunThreadPlan(): execution stopped with "
5302 "unexpected state: %s.",
5303 StateAsCString(stop_state));
5304
5305 if (stop_state == eStateExited)
5306 event_to_broadcast_sp = event_sp;
5307
Zachary Turnere2411fa2016-11-12 19:12:56 +00005308 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005309 eDiagnosticSeverityError,
5310 "execution stopped with unexpected state.");
5311 return_value = eExpressionInterrupted;
5312 break;
5313 }
5314 }
5315
5316 if (keep_going)
5317 continue;
5318 else
5319 break;
5320 } else {
5321 if (log)
5322 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5323 "the event pointer was null. How odd...");
5324 return_value = eExpressionInterrupted;
5325 break;
5326 }
5327 } else {
5328 // If we didn't get an event that means we've timed out...
5329 // We will interrupt the process here. Depending on what we were asked
5330 // to do we will
5331 // either exit, or try with all threads running for the same timeout.
5332
5333 if (log) {
5334 if (options.GetTryAllThreads()) {
5335 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005336 LLDB_LOG(log,
5337 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005338 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005339 LLDB_LOG(log, "Restarting function with all threads enabled and "
5340 "timeout: {0} timed out, abandoning execution.",
5341 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005342 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005343 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5344 "abandoning execution.",
5345 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005346 }
5347
5348 // It is possible that between the time we issued the Halt, and we get
5349 // around to calling Halt the target
5350 // could have stopped. That's fine, Halt will figure that out and send
5351 // the appropriate Stopped event.
5352 // BUT it is also possible that we stopped & restarted (e.g. hit a
5353 // signal with "stop" set to false.) In
5354 // that case, we'll get the stopped & restarted event, and we should go
5355 // back to waiting for the Halt's
5356 // stopped event. That's what this while loop does.
5357
5358 bool back_to_top = true;
5359 uint32_t try_halt_again = 0;
5360 bool do_halt = true;
5361 const uint32_t num_retries = 5;
5362 while (try_halt_again < num_retries) {
5363 Error halt_error;
5364 if (do_halt) {
5365 if (log)
5366 log->Printf("Process::RunThreadPlan(): Running Halt.");
5367 const bool clear_thread_plans = false;
5368 const bool use_run_lock = false;
5369 Halt(clear_thread_plans, use_run_lock);
5370 }
5371 if (halt_error.Success()) {
5372 if (log)
5373 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5374
Pavel Labathd35031e12016-11-30 10:41:42 +00005375 got_event =
5376 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005377
5378 if (got_event) {
5379 stop_state =
5380 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5381 if (log) {
5382 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5383 StateAsCString(stop_state));
5384 if (stop_state == lldb::eStateStopped &&
5385 Process::ProcessEventData::GetInterruptedFromEvent(
5386 event_sp.get()))
5387 log->PutCString(" Event was the Halt interruption event.");
5388 }
5389
5390 if (stop_state == lldb::eStateStopped) {
5391 // Between the time we initiated the Halt and the time we
5392 // delivered it, the process could have
5393 // already finished its job. Check that here:
5394
5395 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5396 if (log)
5397 log->PutCString("Process::RunThreadPlan(): Even though we "
5398 "timed out, the call plan was done. "
5399 "Exiting wait loop.");
5400 return_value = eExpressionCompleted;
5401 back_to_top = false;
5402 break;
5403 }
5404
5405 if (Process::ProcessEventData::GetRestartedFromEvent(
5406 event_sp.get())) {
5407 if (log)
5408 log->PutCString("Process::RunThreadPlan(): Went to halt "
5409 "but got a restarted event, there must be "
5410 "an un-restarted stopped event so try "
5411 "again... "
5412 "Exiting wait loop.");
5413 try_halt_again++;
5414 do_halt = false;
5415 continue;
5416 }
5417
5418 if (!options.GetTryAllThreads()) {
5419 if (log)
5420 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5421 "was false, we stopped so now we're "
5422 "quitting.");
5423 return_value = eExpressionInterrupted;
5424 back_to_top = false;
5425 break;
5426 }
5427
5428 if (before_first_timeout) {
5429 // Set all the other threads to run, and return to the top of
5430 // the loop, which will continue;
5431 before_first_timeout = false;
5432 thread_plan_sp->SetStopOthers(false);
5433 if (log)
5434 log->PutCString(
5435 "Process::RunThreadPlan(): about to resume.");
5436
5437 back_to_top = true;
5438 break;
5439 } else {
5440 // Running all threads failed, so return Interrupted.
5441 if (log)
5442 log->PutCString("Process::RunThreadPlan(): running all "
5443 "threads timed out.");
5444 return_value = eExpressionInterrupted;
5445 back_to_top = false;
5446 break;
5447 }
5448 }
5449 } else {
5450 if (log)
5451 log->PutCString("Process::RunThreadPlan(): halt said it "
5452 "succeeded, but I got no event. "
5453 "I'm getting out of here passing Interrupted.");
5454 return_value = eExpressionInterrupted;
5455 back_to_top = false;
5456 break;
5457 }
5458 } else {
5459 try_halt_again++;
5460 continue;
5461 }
5462 }
5463
5464 if (!back_to_top || try_halt_again > num_retries)
5465 break;
5466 else
5467 continue;
5468 }
5469 } // END WAIT LOOP
5470
5471 // If we had to start up a temporary private state thread to run this thread
5472 // plan, shut it down now.
5473 if (backup_private_state_thread.IsJoinable()) {
5474 StopPrivateStateThread();
5475 Error error;
5476 m_private_state_thread = backup_private_state_thread;
5477 if (stopper_base_plan_sp) {
5478 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5479 }
5480 if (old_state != eStateInvalid)
5481 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005482 }
5483
Kate Stoneb9c1b512016-09-06 20:57:50 +00005484 if (return_value != eExpressionCompleted && log) {
5485 // Print a backtrace into the log so we can figure out where we are:
5486 StreamString s;
5487 s.PutCString("Thread state after unsuccessful completion: \n");
5488 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005489 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005490 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005491 // Restore the thread state if we are going to discard the plan execution.
5492 // There are three cases where this
5493 // could happen:
5494 // 1) The execution successfully completed
5495 // 2) We hit a breakpoint, and ignore_breakpoints was true
5496 // 3) We got some other error, and discard_on_error was true
5497 bool should_unwind = (return_value == eExpressionInterrupted &&
5498 options.DoesUnwindOnError()) ||
5499 (return_value == eExpressionHitBreakpoint &&
5500 options.DoesIgnoreBreakpoints());
5501
5502 if (return_value == eExpressionCompleted || should_unwind) {
5503 thread_plan_sp->RestoreThreadState();
5504 }
5505
5506 // Now do some processing on the results of the run:
5507 if (return_value == eExpressionInterrupted ||
5508 return_value == eExpressionHitBreakpoint) {
5509 if (log) {
5510 StreamString s;
5511 if (event_sp)
5512 event_sp->Dump(&s);
5513 else {
5514 log->PutCString("Process::RunThreadPlan(): Stop event that "
5515 "interrupted us is NULL.");
5516 }
5517
5518 StreamString ts;
5519
5520 const char *event_explanation = nullptr;
5521
5522 do {
5523 if (!event_sp) {
5524 event_explanation = "<no event>";
5525 break;
5526 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5527 event_explanation = "<user interrupt>";
5528 break;
5529 } else {
5530 const Process::ProcessEventData *event_data =
5531 Process::ProcessEventData::GetEventDataFromEvent(
5532 event_sp.get());
5533
5534 if (!event_data) {
5535 event_explanation = "<no event data>";
5536 break;
5537 }
5538
5539 Process *process = event_data->GetProcessSP().get();
5540
5541 if (!process) {
5542 event_explanation = "<no process>";
5543 break;
5544 }
5545
5546 ThreadList &thread_list = process->GetThreadList();
5547
5548 uint32_t num_threads = thread_list.GetSize();
5549 uint32_t thread_index;
5550
5551 ts.Printf("<%u threads> ", num_threads);
5552
5553 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5554 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5555
5556 if (!thread) {
5557 ts.Printf("<?> ");
5558 continue;
5559 }
5560
5561 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5562 RegisterContext *register_context =
5563 thread->GetRegisterContext().get();
5564
5565 if (register_context)
5566 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5567 else
5568 ts.Printf("[ip unknown] ");
5569
5570 // Show the private stop info here, the public stop info will be
5571 // from the last natural stop.
5572 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5573 if (stop_info_sp) {
5574 const char *stop_desc = stop_info_sp->GetDescription();
5575 if (stop_desc)
5576 ts.PutCString(stop_desc);
5577 }
5578 ts.Printf(">");
5579 }
5580
5581 event_explanation = ts.GetData();
5582 }
5583 } while (0);
5584
5585 if (event_explanation)
5586 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5587 s.GetData(), event_explanation);
5588 else
5589 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5590 s.GetData());
5591 }
5592
5593 if (should_unwind) {
5594 if (log)
5595 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5596 "discarding thread plans up to %p.",
5597 static_cast<void *>(thread_plan_sp.get()));
5598 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5599 } else {
5600 if (log)
5601 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5602 "plan: %p not discarding.",
5603 static_cast<void *>(thread_plan_sp.get()));
5604 }
5605 } else if (return_value == eExpressionSetupError) {
5606 if (log)
5607 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5608
5609 if (options.DoesUnwindOnError()) {
5610 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5611 }
5612 } else {
5613 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5614 if (log)
5615 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5616 return_value = eExpressionCompleted;
5617 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5618 if (log)
5619 log->PutCString(
5620 "Process::RunThreadPlan(): thread plan was discarded");
5621 return_value = eExpressionDiscarded;
5622 } else {
5623 if (log)
5624 log->PutCString(
5625 "Process::RunThreadPlan(): thread plan stopped in mid course");
5626 if (options.DoesUnwindOnError() && thread_plan_sp) {
5627 if (log)
5628 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5629 "'cause unwind_on_error is set.");
5630 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5631 }
5632 }
5633 }
5634
5635 // Thread we ran the function in may have gone away because we ran the
5636 // target
5637 // Check that it's still there, and if it is put it back in the context.
5638 // Also restore the
5639 // frame in the context if it is still present.
5640 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5641 if (thread) {
5642 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5643 }
5644
5645 // Also restore the current process'es selected frame & thread, since this
5646 // function calling may
5647 // be done behind the user's back.
5648
5649 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5650 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5651 selected_stack_id.IsValid()) {
5652 // We were able to restore the selected thread, now restore the frame:
5653 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5654 StackFrameSP old_frame_sp =
5655 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5656 selected_stack_id);
5657 if (old_frame_sp)
5658 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5659 old_frame_sp.get());
5660 }
5661 }
5662 }
5663
5664 // If the process exited during the run of the thread plan, notify everyone.
5665
5666 if (event_to_broadcast_sp) {
5667 if (log)
5668 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5669 BroadcastEvent(event_to_broadcast_sp);
5670 }
5671
5672 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005673}
5674
Kate Stoneb9c1b512016-09-06 20:57:50 +00005675const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5676 const char *result_name;
5677
5678 switch (result) {
5679 case eExpressionCompleted:
5680 result_name = "eExpressionCompleted";
5681 break;
5682 case eExpressionDiscarded:
5683 result_name = "eExpressionDiscarded";
5684 break;
5685 case eExpressionInterrupted:
5686 result_name = "eExpressionInterrupted";
5687 break;
5688 case eExpressionHitBreakpoint:
5689 result_name = "eExpressionHitBreakpoint";
5690 break;
5691 case eExpressionSetupError:
5692 result_name = "eExpressionSetupError";
5693 break;
5694 case eExpressionParseError:
5695 result_name = "eExpressionParseError";
5696 break;
5697 case eExpressionResultUnavailable:
5698 result_name = "eExpressionResultUnavailable";
5699 break;
5700 case eExpressionTimedOut:
5701 result_name = "eExpressionTimedOut";
5702 break;
5703 case eExpressionStoppedForDebug:
5704 result_name = "eExpressionStoppedForDebug";
5705 break;
5706 }
5707 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005708}
5709
Kate Stoneb9c1b512016-09-06 20:57:50 +00005710void Process::GetStatus(Stream &strm) {
5711 const StateType state = GetState();
5712 if (StateIsStoppedState(state, false)) {
5713 if (state == eStateExited) {
5714 int exit_status = GetExitStatus();
5715 const char *exit_description = GetExitDescription();
5716 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5717 GetID(), exit_status, exit_status,
5718 exit_description ? exit_description : "");
5719 } else {
5720 if (state == eStateConnected)
5721 strm.Printf("Connected to remote target.\n");
5722 else
5723 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5724 }
5725 } else {
5726 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5727 }
Pavel Labatha933d512016-04-05 13:07:16 +00005728}
5729
Kate Stoneb9c1b512016-09-06 20:57:50 +00005730size_t Process::GetThreadStatus(Stream &strm,
5731 bool only_threads_with_stop_reason,
5732 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005733 uint32_t num_frames_with_source,
5734 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005735 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005736
Kate Stoneb9c1b512016-09-06 20:57:50 +00005737 // You can't hold the thread list lock while calling Thread::GetStatus. That
5738 // very well might run code (e.g. if we need it
5739 // to get return values or arguments.) For that to work the process has to be
5740 // able to acquire it. So instead copy the thread
5741 // ID's, and look them up one by one:
5742
5743 uint32_t num_threads;
5744 std::vector<lldb::tid_t> thread_id_array;
5745 // Scope for thread list locker;
5746 {
5747 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5748 ThreadList &curr_thread_list = GetThreadList();
5749 num_threads = curr_thread_list.GetSize();
5750 uint32_t idx;
5751 thread_id_array.resize(num_threads);
5752 for (idx = 0; idx < num_threads; ++idx)
5753 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5754 }
5755
5756 for (uint32_t i = 0; i < num_threads; i++) {
5757 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5758 if (thread_sp) {
5759 if (only_threads_with_stop_reason) {
5760 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5761 if (!stop_info_sp || !stop_info_sp->IsValid())
5762 continue;
5763 }
5764 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005765 num_frames_with_source,
5766 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005767 ++num_thread_infos_dumped;
5768 } else {
5769 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5770 if (log)
5771 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5772 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005773 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005774 }
5775 return num_thread_infos_dumped;
5776}
5777
5778void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5779 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5780}
5781
5782bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5783 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5784 region.GetByteSize());
5785}
5786
5787void Process::AddPreResumeAction(PreResumeActionCallback callback,
5788 void *baton) {
5789 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5790}
5791
5792bool Process::RunPreResumeActions() {
5793 bool result = true;
5794 while (!m_pre_resume_actions.empty()) {
5795 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5796 m_pre_resume_actions.pop_back();
5797 bool this_result = action.callback(action.baton);
5798 if (result)
5799 result = this_result;
5800 }
5801 return result;
5802}
5803
5804void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5805
Jim Inghamffd91752016-10-20 22:50:00 +00005806void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5807{
5808 PreResumeCallbackAndBaton element(callback, baton);
5809 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5810 if (found_iter != m_pre_resume_actions.end())
5811 {
5812 m_pre_resume_actions.erase(found_iter);
5813 }
5814}
5815
Kate Stoneb9c1b512016-09-06 20:57:50 +00005816ProcessRunLock &Process::GetRunLock() {
5817 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5818 return m_private_run_lock;
5819 else
5820 return m_public_run_lock;
5821}
5822
5823void Process::Flush() {
5824 m_thread_list.Flush();
5825 m_extended_thread_list.Flush();
5826 m_extended_thread_stop_id = 0;
5827 m_queue_list.Clear();
5828 m_queue_list_stop_id = 0;
5829}
5830
5831void Process::DidExec() {
5832 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5833 if (log)
5834 log->Printf("Process::%s()", __FUNCTION__);
5835
5836 Target &target = GetTarget();
5837 target.CleanupProcess();
5838 target.ClearModules(false);
5839 m_dynamic_checkers_ap.reset();
5840 m_abi_sp.reset();
5841 m_system_runtime_ap.reset();
5842 m_os_ap.reset();
5843 m_dyld_ap.reset();
5844 m_jit_loaders_ap.reset();
5845 m_image_tokens.clear();
5846 m_allocated_memory_cache.Clear();
5847 m_language_runtimes.clear();
5848 m_instrumentation_runtimes.clear();
5849 m_thread_list.DiscardThreadPlans();
5850 m_memory_cache.Clear(true);
5851 m_stop_info_override_callback = nullptr;
5852 DoDidExec();
5853 CompleteAttach();
5854 // Flush the process (threads and all stack frames) after running
5855 // CompleteAttach()
5856 // in case the dynamic loader loaded things in new locations.
5857 Flush();
5858
5859 // After we figure out what was loaded/unloaded in CompleteAttach,
5860 // we need to let the target know so it can do any cleanup it needs to.
5861 target.DidExec();
5862}
5863
5864addr_t Process::ResolveIndirectFunction(const Address *address, Error &error) {
5865 if (address == nullptr) {
5866 error.SetErrorString("Invalid address argument");
5867 return LLDB_INVALID_ADDRESS;
5868 }
5869
5870 addr_t function_addr = LLDB_INVALID_ADDRESS;
5871
5872 addr_t addr = address->GetLoadAddress(&GetTarget());
5873 std::map<addr_t, addr_t>::const_iterator iter =
5874 m_resolved_indirect_addresses.find(addr);
5875 if (iter != m_resolved_indirect_addresses.end()) {
5876 function_addr = (*iter).second;
5877 } else {
5878 if (!InferiorCall(this, address, function_addr)) {
5879 Symbol *symbol = address->CalculateSymbolContextSymbol();
5880 error.SetErrorStringWithFormat(
5881 "Unable to call resolver for indirect function %s",
5882 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5883 function_addr = LLDB_INVALID_ADDRESS;
5884 } else {
5885 m_resolved_indirect_addresses.insert(
5886 std::pair<addr_t, addr_t>(addr, function_addr));
5887 }
5888 }
5889 return function_addr;
5890}
5891
5892void Process::ModulesDidLoad(ModuleList &module_list) {
5893 SystemRuntime *sys_runtime = GetSystemRuntime();
5894 if (sys_runtime) {
5895 sys_runtime->ModulesDidLoad(module_list);
5896 }
5897
5898 GetJITLoaders().ModulesDidLoad(module_list);
5899
5900 // Give runtimes a chance to be created.
5901 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5902 m_instrumentation_runtimes);
5903
5904 // Tell runtimes about new modules.
5905 for (auto pos = m_instrumentation_runtimes.begin();
5906 pos != m_instrumentation_runtimes.end(); ++pos) {
5907 InstrumentationRuntimeSP runtime = pos->second;
5908 runtime->ModulesDidLoad(module_list);
5909 }
5910
5911 // Let any language runtimes we have already created know
5912 // about the modules that loaded.
5913
5914 // Iterate over a copy of this language runtime list in case
5915 // the language runtime ModulesDidLoad somehow causes the language
5916 // riuntime to be unloaded.
5917 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5918 for (const auto &pair : language_runtimes) {
5919 // We must check language_runtime_sp to make sure it is not
5920 // nullptr as we might cache the fact that we didn't have a
5921 // language runtime for a language.
5922 LanguageRuntimeSP language_runtime_sp = pair.second;
5923 if (language_runtime_sp)
5924 language_runtime_sp->ModulesDidLoad(module_list);
5925 }
5926
5927 // If we don't have an operating system plug-in, try to load one since
5928 // loading shared libraries might cause a new one to try and load
5929 if (!m_os_ap)
5930 LoadOperatingSystemPlugin(false);
5931
5932 // Give structured-data plugins a chance to see the modified modules.
5933 for (auto pair : m_structured_data_plugin_map) {
5934 if (pair.second)
5935 pair.second->ModulesDidLoad(*this, module_list);
5936 }
5937}
5938
5939void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5940 const char *fmt, ...) {
5941 bool print_warning = true;
5942
5943 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5944 if (!stream_sp)
5945 return;
5946 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5947 return;
5948 }
5949
5950 if (repeat_key != nullptr) {
5951 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5952 if (it == m_warnings_issued.end()) {
5953 m_warnings_issued[warning_type] = WarningsPointerSet();
5954 m_warnings_issued[warning_type].insert(repeat_key);
5955 } else {
5956 if (it->second.find(repeat_key) != it->second.end()) {
5957 print_warning = false;
5958 } else {
5959 it->second.insert(repeat_key);
5960 }
5961 }
5962 }
5963
5964 if (print_warning) {
5965 va_list args;
5966 va_start(args, fmt);
5967 stream_sp->PrintfVarArg(fmt, args);
5968 va_end(args);
5969 }
5970}
5971
5972void Process::PrintWarningOptimization(const SymbolContext &sc) {
5973 if (GetWarningsOptimization() && sc.module_sp &&
5974 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5975 sc.function->GetIsOptimized()) {
5976 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5977 "%s was compiled with optimization - stepping may behave "
5978 "oddly; variables may not be available.\n",
5979 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5980 }
5981}
5982
5983bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5984 info.Clear();
5985
5986 PlatformSP platform_sp = GetTarget().GetPlatform();
5987 if (!platform_sp)
5988 return false;
5989
5990 return platform_sp->GetProcessInfo(GetID(), info);
5991}
5992
5993ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5994 ThreadCollectionSP threads;
5995
5996 const MemoryHistorySP &memory_history =
5997 MemoryHistory::FindPlugin(shared_from_this());
5998
5999 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006000 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006001 }
6002
6003 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6004
6005 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00006006}
Kuba Brecka63927542014-10-11 01:59:32 +00006007
6008InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00006009Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
6010 InstrumentationRuntimeCollection::iterator pos;
6011 pos = m_instrumentation_runtimes.find(type);
6012 if (pos == m_instrumentation_runtimes.end()) {
6013 return InstrumentationRuntimeSP();
6014 } else
6015 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00006016}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006017
Kate Stoneb9c1b512016-09-06 20:57:50 +00006018bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6019 const ArchSpec &arch, ModuleSpec &module_spec) {
6020 module_spec.Clear();
6021 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006022}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006023
Kate Stoneb9c1b512016-09-06 20:57:50 +00006024size_t Process::AddImageToken(lldb::addr_t image_ptr) {
6025 m_image_tokens.push_back(image_ptr);
6026 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006027}
6028
Kate Stoneb9c1b512016-09-06 20:57:50 +00006029lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
6030 if (token < m_image_tokens.size())
6031 return m_image_tokens[token];
6032 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006033}
6034
Kate Stoneb9c1b512016-09-06 20:57:50 +00006035void Process::ResetImageToken(size_t token) {
6036 if (token < m_image_tokens.size())
6037 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006038}
Jason Molendafd4cea52016-01-08 21:40:11 +00006039
6040Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00006041Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
6042 AddressRange range_bounds) {
6043 Target &target = GetTarget();
6044 DisassemblerSP disassembler_sp;
6045 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006046
Kate Stoneb9c1b512016-09-06 20:57:50 +00006047 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006048
Kate Stoneb9c1b512016-09-06 20:57:50 +00006049 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006050 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006051 if (!default_stop_addr.IsValid())
6052 return retval;
6053
6054 ExecutionContext exe_ctx(this);
6055 const char *plugin_name = nullptr;
6056 const char *flavor = nullptr;
6057 const bool prefer_file_cache = true;
6058 disassembler_sp = Disassembler::DisassembleRange(
6059 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6060 prefer_file_cache);
6061 if (disassembler_sp)
6062 insn_list = &disassembler_sp->GetInstructionList();
6063
6064 if (insn_list == nullptr) {
6065 return retval;
6066 }
6067
6068 size_t insn_offset =
6069 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6070 if (insn_offset == UINT32_MAX) {
6071 return retval;
6072 }
6073
6074 uint32_t branch_index =
6075 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6076 if (branch_index == UINT32_MAX) {
6077 return retval;
6078 }
6079
6080 if (branch_index > insn_offset) {
6081 Address next_branch_insn_address =
6082 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6083 if (next_branch_insn_address.IsValid() &&
6084 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6085 retval = next_branch_insn_address;
6086 }
6087 }
6088
6089 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006090}
Howard Hellyerad007562016-07-07 08:21:28 +00006091
Kate Stoneb9c1b512016-09-06 20:57:50 +00006092Error Process::GetMemoryRegions(
6093 std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006094
Kate Stoneb9c1b512016-09-06 20:57:50 +00006095 Error error;
Howard Hellyerad007562016-07-07 08:21:28 +00006096
Kate Stoneb9c1b512016-09-06 20:57:50 +00006097 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006098
Kate Stoneb9c1b512016-09-06 20:57:50 +00006099 region_list.clear();
6100 do {
6101 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6102 error = GetMemoryRegionInfo(range_end, *region_info);
6103 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6104 if (error.Fail()) {
6105 region_list.clear();
6106 break;
Todd Fiala75930012016-08-19 04:21:48 +00006107 }
6108
Kate Stoneb9c1b512016-09-06 20:57:50 +00006109 range_end = region_info->GetRange().GetRangeEnd();
6110 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6111 region_list.push_back(region_info);
6112 }
6113 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006114
Kate Stoneb9c1b512016-09-06 20:57:50 +00006115 return error;
6116}
6117
6118Error Process::ConfigureStructuredData(
6119 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) {
6120 // If you get this, the Process-derived class needs to implement a method
6121 // to enable an already-reported asynchronous structured data feature.
6122 // See ProcessGDBRemote for an example implementation over gdb-remote.
6123 return Error("unimplemented");
6124}
6125
6126void Process::MapSupportedStructuredDataPlugins(
6127 const StructuredData::Array &supported_type_names) {
6128 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6129
6130 // Bail out early if there are no type names to map.
6131 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006132 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006133 log->Printf("Process::%s(): no structured data types supported",
6134 __FUNCTION__);
6135 return;
6136 }
Todd Fiala75930012016-08-19 04:21:48 +00006137
Kate Stoneb9c1b512016-09-06 20:57:50 +00006138 // Convert StructuredData type names to ConstString instances.
6139 std::set<ConstString> const_type_names;
6140
6141 if (log)
6142 log->Printf("Process::%s(): the process supports the following async "
6143 "structured data types:",
6144 __FUNCTION__);
6145
6146 supported_type_names.ForEach(
6147 [&const_type_names, &log](StructuredData::Object *object) {
6148 if (!object) {
6149 // Invalid - shouldn't be null objects in the array.
6150 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006151 }
6152
6153 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006154 if (!type_name) {
6155 // Invalid format - all type names should be strings.
6156 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006157 }
6158
6159 const_type_names.insert(ConstString(type_name->GetValue()));
6160 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006161 log->Printf("- %s", type_name->GetValue().c_str());
Todd Fiala75930012016-08-19 04:21:48 +00006162 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006163 });
Todd Fiala75930012016-08-19 04:21:48 +00006164
Kate Stoneb9c1b512016-09-06 20:57:50 +00006165 // For each StructuredDataPlugin, if the plugin handles any of the
6166 // types in the supported_type_names, map that type name to that plugin.
6167 uint32_t plugin_index = 0;
6168 for (auto create_instance =
6169 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6170 plugin_index);
6171 create_instance && !const_type_names.empty(); ++plugin_index) {
6172 // Create the plugin.
6173 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6174 if (!plugin_sp) {
6175 // This plugin doesn't think it can work with the process.
6176 // Move on to the next.
6177 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006178 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006179
6180 // For any of the remaining type names, map any that this plugin
6181 // supports.
6182 std::vector<ConstString> names_to_remove;
6183 for (auto &type_name : const_type_names) {
6184 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6185 m_structured_data_plugin_map.insert(
6186 std::make_pair(type_name, plugin_sp));
6187 names_to_remove.push_back(type_name);
6188 if (log)
6189 log->Printf("Process::%s(): using plugin %s for type name "
6190 "%s",
6191 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6192 type_name.GetCString());
6193 }
6194 }
6195
6196 // Remove the type names that were consumed by this plugin.
6197 for (auto &type_name : names_to_remove)
6198 const_type_names.erase(type_name);
6199 }
Todd Fiala75930012016-08-19 04:21:48 +00006200}
6201
Kate Stoneb9c1b512016-09-06 20:57:50 +00006202bool Process::RouteAsyncStructuredData(
6203 const StructuredData::ObjectSP object_sp) {
6204 // Nothing to do if there's no data.
6205 if (!object_sp)
6206 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006207
Kate Stoneb9c1b512016-09-06 20:57:50 +00006208 // The contract is this must be a dictionary, so we can look up the
6209 // routing key via the top-level 'type' string value within the dictionary.
6210 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6211 if (!dictionary)
6212 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006213
Kate Stoneb9c1b512016-09-06 20:57:50 +00006214 // Grab the async structured type name (i.e. the feature/plugin name).
6215 ConstString type_name;
6216 if (!dictionary->GetValueForKeyAsString("type", type_name))
6217 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006218
Kate Stoneb9c1b512016-09-06 20:57:50 +00006219 // Check if there's a plugin registered for this type name.
6220 auto find_it = m_structured_data_plugin_map.find(type_name);
6221 if (find_it == m_structured_data_plugin_map.end()) {
6222 // We don't have a mapping for this structured data type.
6223 return false;
6224 }
Todd Fiala75930012016-08-19 04:21:48 +00006225
Kate Stoneb9c1b512016-09-06 20:57:50 +00006226 // Route the structured data to the plugin.
6227 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6228 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006229}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006230
6231Error Process::UpdateAutomaticSignalFiltering() {
6232 // Default implementation does nothign.
6233 // No automatic signal filtering to speak of.
6234 return Error();
6235}