blob: a18eab0f26501bb52e194e1500dcd307dbcb2be9 [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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000022#include "lldb/Core/Module.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000023#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000026#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000027#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Host/Host.h"
Greg Clayton44d93782014-01-27 23:43:24 +000030#include "lldb/Host/Terminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000032#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000033#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000034#include "lldb/Target/LanguageRuntime.h"
35#include "lldb/Target/CPPLanguageRuntime.h"
36#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000037#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000039#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000040#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/Target.h"
42#include "lldb/Target/TargetList.h"
43#include "lldb/Target/Thread.h"
44#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000045#include "lldb/Target/ThreadPlanBase.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000046#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047
Charles Davis510938e2013-08-27 05:04:57 +000048#ifndef LLDB_DISABLE_POSIX
49#include <spawn.h>
50#endif
51
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052using namespace lldb;
53using namespace lldb_private;
54
Greg Clayton67cc0632012-08-22 17:17:09 +000055
56// Comment out line below to disable memory caching, overriding the process setting
57// target.process.disable-memory-cache
58#define ENABLE_MEMORY_CACHING
59
60#ifdef ENABLE_MEMORY_CACHING
61#define DISABLE_MEM_CACHE_DEFAULT false
62#else
63#define DISABLE_MEM_CACHE_DEFAULT true
64#endif
65
66class ProcessOptionValueProperties : public OptionValueProperties
67{
68public:
69 ProcessOptionValueProperties (const ConstString &name) :
70 OptionValueProperties (name)
71 {
72 }
73
74 // This constructor is used when creating ProcessOptionValueProperties when it
75 // is part of a new lldb_private::Process instance. It will copy all current
76 // global property values as needed
77 ProcessOptionValueProperties (ProcessProperties *global_properties) :
78 OptionValueProperties(*global_properties->GetValueProperties())
79 {
80 }
81
82 virtual const Property *
83 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
84 {
85 // When gettings the value for a key from the process options, we will always
86 // try and grab the setting from the current process if there is one. Else we just
87 // use the one from this instance.
88 if (exe_ctx)
89 {
90 Process *process = exe_ctx->GetProcessPtr();
91 if (process)
92 {
93 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
94 if (this != instance_properties)
95 return instance_properties->ProtectedGetPropertyAtIndex (idx);
96 }
97 }
98 return ProtectedGetPropertyAtIndex (idx);
99 }
100};
101
102static PropertyDefinition
103g_properties[] =
104{
105 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Ingham8c3f2762012-11-29 00:41:12 +0000106 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
107 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000108 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
109 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Claytone1e835c2012-11-29 18:48:47 +0000110 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham29950772013-01-26 02:19:28 +0000111 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Jim Inghamacff8952013-05-02 00:27:30 +0000112 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000113 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
114};
115
116enum {
117 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000118 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000119 ePropertyIgnoreBreakpointsInExpressions,
120 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000121 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000122 ePropertyStopOnSharedLibraryEvents,
123 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000124};
125
126ProcessProperties::ProcessProperties (bool is_global) :
127 Properties ()
128{
129 if (is_global)
130 {
131 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
132 m_collection_sp->Initialize(g_properties);
133 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000134 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000135 true,
136 Thread::GetGlobalProperties()->GetValueProperties());
137 }
138 else
139 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
140}
141
142ProcessProperties::~ProcessProperties()
143{
144}
145
146bool
147ProcessProperties::GetDisableMemoryCache() const
148{
149 const uint32_t idx = ePropertyDisableMemCache;
150 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
151}
152
153Args
154ProcessProperties::GetExtraStartupCommands () const
155{
156 Args args;
157 const uint32_t idx = ePropertyExtraStartCommand;
158 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
159 return args;
160}
161
162void
163ProcessProperties::SetExtraStartupCommands (const Args &args)
164{
165 const uint32_t idx = ePropertyExtraStartCommand;
166 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
167}
168
Greg Claytonc9d645d2012-10-18 22:40:37 +0000169FileSpec
170ProcessProperties::GetPythonOSPluginPath () const
171{
172 const uint32_t idx = ePropertyPythonOSPluginPath;
173 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
174}
175
176void
177ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
178{
179 const uint32_t idx = ePropertyPythonOSPluginPath;
180 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
181}
182
Jim Ingham184e9812013-01-15 02:47:48 +0000183
184bool
185ProcessProperties::GetIgnoreBreakpointsInExpressions () const
186{
187 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
188 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
189}
190
191void
192ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
193{
194 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
195 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
196}
197
198bool
199ProcessProperties::GetUnwindOnErrorInExpressions () const
200{
201 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
202 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
203}
204
205void
206ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
207{
208 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
209 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
210}
211
Jim Ingham29950772013-01-26 02:19:28 +0000212bool
213ProcessProperties::GetStopOnSharedLibraryEvents () const
214{
215 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
217}
218
219void
220ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
221{
222 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
223 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
224}
225
Jim Inghamacff8952013-05-02 00:27:30 +0000226bool
227ProcessProperties::GetDetachKeepsStopped () const
228{
229 const uint32_t idx = ePropertyDetachKeepsStopped;
230 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
231}
232
233void
234ProcessProperties::SetDetachKeepsStopped (bool stop)
235{
236 const uint32_t idx = ePropertyDetachKeepsStopped;
237 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
238}
239
Greg Clayton32e0a752011-03-30 18:16:51 +0000240void
Greg Clayton8b82f082011-04-12 05:54:46 +0000241ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000242{
243 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000244 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000245 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000246
247 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000248 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000249
250 if (m_executable)
251 {
252 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
253 s.PutCString (" file = ");
254 m_executable.Dump(&s);
255 s.EOL();
256 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000257 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000258 if (argc > 0)
259 {
260 for (uint32_t i=0; i<argc; i++)
261 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000262 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000263 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000264 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000265 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000266 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000267 }
268 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000269
270 const uint32_t envc = m_environment.GetArgumentCount();
271 if (envc > 0)
272 {
273 for (uint32_t i=0; i<envc; i++)
274 {
275 const char *env = m_environment.GetArgumentAtIndex(i);
276 if (i < 10)
277 s.Printf (" env[%u] = %s\n", i, env);
278 else
279 s.Printf ("env[%u] = %s\n", i, env);
280 }
281 }
282
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000283 if (m_arch.IsValid())
284 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
285
Greg Clayton8b82f082011-04-12 05:54:46 +0000286 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000287 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 cstr = platform->GetUserName (m_uid);
289 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000290 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000291 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000292 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 cstr = platform->GetGroupName (m_gid);
294 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000295 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000296 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000297 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 cstr = platform->GetUserName (m_euid);
299 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000300 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000301 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000302 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000303 cstr = platform->GetGroupName (m_egid);
304 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000305 }
306}
307
308void
Greg Clayton8b82f082011-04-12 05:54:46 +0000309ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000310{
Greg Clayton8b82f082011-04-12 05:54:46 +0000311 const char *label;
312 if (show_args || verbose)
313 label = "ARGUMENTS";
314 else
315 label = "NAME";
316
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000317 if (verbose)
318 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000319 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000320 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
321 }
322 else
323 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000324 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000325 s.PutCString ("====== ====== ========== ======= ============================\n");
326 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000327}
328
329void
Greg Clayton8b82f082011-04-12 05:54:46 +0000330ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000331{
332 if (m_pid != LLDB_INVALID_PROCESS_ID)
333 {
334 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000335 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000336
Greg Clayton32e0a752011-03-30 18:16:51 +0000337
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000338 if (verbose)
339 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000340 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000341 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
342 s.Printf ("%-10s ", cstr);
343 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000344 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000345
Greg Clayton8b82f082011-04-12 05:54:46 +0000346 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000347 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
348 s.Printf ("%-10s ", cstr);
349 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000350 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000351
Greg Clayton8b82f082011-04-12 05:54:46 +0000352 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000353 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
354 s.Printf ("%-10s ", cstr);
355 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000356 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000357
Greg Clayton8b82f082011-04-12 05:54:46 +0000358 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000359 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
360 s.Printf ("%-10s ", cstr);
361 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000362 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000363 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
364 }
365 else
366 {
Jason Molendafd54b362011-09-20 21:44:10 +0000367 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000368 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000369 (int)m_arch.GetTriple().getArchName().size(),
370 m_arch.GetTriple().getArchName().data());
371 }
372
Greg Clayton8b82f082011-04-12 05:54:46 +0000373 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000374 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000375 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000376 if (argc > 0)
377 {
378 for (uint32_t i=0; i<argc; i++)
379 {
380 if (i > 0)
381 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000382 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383 }
384 }
385 }
386 else
387 {
388 s.PutCString (GetName());
389 }
390
391 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000392 }
393}
394
Greg Clayton8b82f082011-04-12 05:54:46 +0000395
396void
Greg Clayton45392552012-10-17 22:57:12 +0000397ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000398{
399 m_arguments.SetArguments (argv);
400
401 // Is the first argument the executable?
402 if (first_arg_is_executable)
403 {
404 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
405 if (first_arg)
406 {
407 // Yes the first argument is an executable, set it as the executable
408 // in the launch options. Don't resolve the file path as the path
409 // could be a remote platform path
410 const bool resolve = false;
411 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000412 }
413 }
414}
415void
Greg Clayton45392552012-10-17 22:57:12 +0000416ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000417{
418 // Copy all arguments
419 m_arguments = args;
420
421 // Is the first argument the executable?
422 if (first_arg_is_executable)
423 {
Greg Clayton982c9762011-11-03 21:22:33 +0000424 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000425 if (first_arg)
426 {
427 // Yes the first argument is an executable, set it as the executable
428 // in the launch options. Don't resolve the file path as the path
429 // could be a remote platform path
430 const bool resolve = false;
431 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000432 }
433 }
434}
435
Greg Clayton1d885962011-11-08 02:43:13 +0000436void
Greg Claytonee95ed52011-11-17 22:14:31 +0000437ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000438{
439 // If notthing was specified, then check the process for any default
440 // settings that were set with "settings set"
441 if (m_file_actions.empty())
442 {
Greg Clayton1d885962011-11-08 02:43:13 +0000443 if (m_flags.Test(eLaunchFlagDisableSTDIO))
444 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000445 AppendSuppressFileAction (STDIN_FILENO , true, false);
446 AppendSuppressFileAction (STDOUT_FILENO, false, true);
447 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000448 }
449 else
450 {
451 // Check for any values that might have gotten set with any of:
452 // (lldb) settings set target.input-path
453 // (lldb) settings set target.output-path
454 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000455 FileSpec in_path;
456 FileSpec out_path;
457 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000458 if (target)
459 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000460 in_path = target->GetStandardInputPath();
461 out_path = target->GetStandardOutputPath();
462 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000463 }
464
Greg Clayton67cc0632012-08-22 17:17:09 +0000465 if (in_path || out_path || err_path)
466 {
467 char path[PATH_MAX];
468 if (in_path && in_path.GetPath(path, sizeof(path)))
469 AppendOpenFileAction(STDIN_FILENO, path, true, false);
470
471 if (out_path && out_path.GetPath(path, sizeof(path)))
472 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
473
474 if (err_path && err_path.GetPath(path, sizeof(path)))
475 AppendOpenFileAction(STDERR_FILENO, path, false, true);
476 }
477 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000478 {
479 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000480 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000481 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
482 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
483 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
484 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000485 }
486 }
Greg Clayton1d885962011-11-08 02:43:13 +0000487 }
488 }
489}
490
Greg Clayton144f3a92011-11-15 03:53:30 +0000491
492bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000493ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
494 bool localhost,
495 bool will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000496 bool first_arg_is_full_shell_command,
497 int32_t num_resumes)
Greg Clayton144f3a92011-11-15 03:53:30 +0000498{
499 error.Clear();
500
501 if (GetFlags().Test (eLaunchFlagLaunchInShell))
502 {
503 const char *shell_executable = GetShell();
504 if (shell_executable)
505 {
506 char shell_resolved_path[PATH_MAX];
507
508 if (localhost)
509 {
510 FileSpec shell_filespec (shell_executable, true);
511
512 if (!shell_filespec.Exists())
513 {
514 // Resolve the path in case we just got "bash", "sh" or "tcsh"
515 if (!shell_filespec.ResolveExecutableLocation ())
516 {
517 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
518 return false;
519 }
520 }
521 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
522 shell_executable = shell_resolved_path;
523 }
524
Greg Clayton45392552012-10-17 22:57:12 +0000525 const char **argv = GetArguments().GetConstArgumentVector ();
526 if (argv == NULL || argv[0] == NULL)
527 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000528 Args shell_arguments;
529 std::string safe_arg;
530 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000531 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000532 StreamString shell_command;
533 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000534 {
Greg Clayton45392552012-10-17 22:57:12 +0000535 // Add a modified PATH environment variable in case argv[0]
536 // is a relative path
537 const char *argv0 = argv[0];
538 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
539 {
540 // We have a relative path to our executable which may not work if
541 // we just try to run "a.out" (without it being converted to "./a.out")
542 const char *working_dir = GetWorkingDirectory();
Greg Clayton8938f8d2013-02-14 03:54:39 +0000543 // Be sure to put quotes around PATH's value in case any paths have spaces...
544 std::string new_path("PATH=\"");
Greg Clayton45392552012-10-17 22:57:12 +0000545 const size_t empty_path_len = new_path.size();
546
547 if (working_dir && working_dir[0])
548 {
549 new_path += working_dir;
550 }
551 else
552 {
553 char current_working_dir[PATH_MAX];
554 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
555 if (cwd && cwd[0])
556 new_path += cwd;
557 }
558 const char *curr_path = getenv("PATH");
559 if (curr_path)
560 {
561 if (new_path.size() > empty_path_len)
562 new_path += ':';
563 new_path += curr_path;
564 }
Greg Clayton8938f8d2013-02-14 03:54:39 +0000565 new_path += "\" ";
Greg Clayton45392552012-10-17 22:57:12 +0000566 shell_command.PutCString(new_path.c_str());
567 }
568
Greg Claytond1cf11a2012-04-14 01:42:46 +0000569 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000570
Greg Clayton45392552012-10-17 22:57:12 +0000571 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000572 if (GetArchitecture().IsValid())
573 {
574 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000575 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000576 // 1 - stop in shell
577 // 2 - stop in /usr/bin/arch
578 // 3 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000579 SetResumeCount(num_resumes + 1);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000580 }
581 else
582 {
Greg Clayton45392552012-10-17 22:57:12 +0000583 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000584 // 1 - stop in shell
585 // 2 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000586 SetResumeCount(num_resumes);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000587 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000588 }
Greg Clayton45392552012-10-17 22:57:12 +0000589
590 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000591 {
Greg Clayton45392552012-10-17 22:57:12 +0000592 // There should only be one argument that is the shell command itself to be used as is
593 if (argv[0] && !argv[1])
594 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000595 else
Greg Clayton45392552012-10-17 22:57:12 +0000596 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000597 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000598 else
599 {
Greg Clayton45392552012-10-17 22:57:12 +0000600 for (size_t i=0; argv[i] != NULL; ++i)
601 {
602 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
603 shell_command.Printf(" %s", arg);
604 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000605 }
Greg Clayton45392552012-10-17 22:57:12 +0000606 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000607 m_executable.SetFile(shell_executable, false);
608 m_arguments = shell_arguments;
609 return true;
610 }
611 else
612 {
613 error.SetErrorString ("invalid shell path");
614 }
615 }
616 else
617 {
618 error.SetErrorString ("not launching in shell");
619 }
620 return false;
621}
622
623
Greg Clayton32e0a752011-03-30 18:16:51 +0000624bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000625ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
626{
627 if ((read || write) && fd >= 0 && path && path[0])
628 {
629 m_action = eFileActionOpen;
630 m_fd = fd;
631 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000632 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000633 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000634 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000635 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000636 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000637 m_path.assign (path);
638 return true;
639 }
640 else
641 {
642 Clear();
643 }
644 return false;
645}
646
647bool
648ProcessLaunchInfo::FileAction::Close (int fd)
649{
650 Clear();
651 if (fd >= 0)
652 {
653 m_action = eFileActionClose;
654 m_fd = fd;
655 }
656 return m_fd >= 0;
657}
658
659
660bool
661ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
662{
663 Clear();
664 if (fd >= 0 && dup_fd >= 0)
665 {
666 m_action = eFileActionDuplicate;
667 m_fd = fd;
668 m_arg = dup_fd;
669 }
670 return m_fd >= 0;
671}
672
673
674
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000675#ifndef LLDB_DISABLE_POSIX
Greg Clayton8b82f082011-04-12 05:54:46 +0000676bool
Charles Davis510938e2013-08-27 05:04:57 +0000677ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions,
Greg Clayton8b82f082011-04-12 05:54:46 +0000678 const FileAction *info,
679 Log *log,
680 Error& error)
681{
682 if (info == NULL)
683 return false;
684
Charles Davis510938e2013-08-27 05:04:57 +0000685 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
686
Greg Clayton8b82f082011-04-12 05:54:46 +0000687 switch (info->m_action)
688 {
689 case eFileActionNone:
690 error.Clear();
691 break;
692
693 case eFileActionClose:
694 if (info->m_fd == -1)
695 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
696 else
697 {
698 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
699 eErrorTypePOSIX);
700 if (log && (error.Fail() || log))
701 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
702 file_actions, info->m_fd);
703 }
704 break;
705
706 case eFileActionDuplicate:
707 if (info->m_fd == -1)
708 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
709 else if (info->m_arg == -1)
710 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
711 else
712 {
713 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
714 eErrorTypePOSIX);
715 if (log && (error.Fail() || log))
716 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
717 file_actions, info->m_fd, info->m_arg);
718 }
719 break;
720
721 case eFileActionOpen:
722 if (info->m_fd == -1)
723 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
724 else
725 {
726 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000727
Greg Clayton8b82f082011-04-12 05:54:46 +0000728 mode_t mode = 0;
729
Greg Clayton144f3a92011-11-15 03:53:30 +0000730 if (oflag & O_CREAT)
731 mode = 0640;
732
Greg Clayton8b82f082011-04-12 05:54:46 +0000733 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
734 info->m_fd,
735 info->m_path.c_str(),
736 oflag,
737 mode),
738 eErrorTypePOSIX);
739 if (error.Fail() || log)
740 error.PutToLog(log,
741 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
742 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
743 }
744 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000745 }
746 return error.Success();
747}
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000748#endif
Greg Clayton8b82f082011-04-12 05:54:46 +0000749
750Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000751ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000752{
753 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000754 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000755
756 switch (short_option)
757 {
758 case 's': // Stop at program entry point
759 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
760 break;
761
Greg Clayton8b82f082011-04-12 05:54:46 +0000762 case 'i': // STDIN for read only
763 {
764 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000765 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000766 launch_info.AppendFileAction (action);
767 }
768 break;
769
770 case 'o': // Open STDOUT for write only
771 {
772 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000773 if (action.Open (STDOUT_FILENO, option_arg, false, true))
774 launch_info.AppendFileAction (action);
775 }
776 break;
777
778 case 'e': // STDERR for write only
779 {
780 ProcessLaunchInfo::FileAction action;
781 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000782 launch_info.AppendFileAction (action);
783 }
784 break;
785
Greg Clayton9845a8d2012-03-06 04:01:04 +0000786
Greg Clayton8b82f082011-04-12 05:54:46 +0000787 case 'p': // Process plug-in name
788 launch_info.SetProcessPluginName (option_arg);
789 break;
790
791 case 'n': // Disable STDIO
792 {
793 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000794 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000795 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000796 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000797 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000798 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000799 launch_info.AppendFileAction (action);
800 }
801 break;
802
803 case 'w':
804 launch_info.SetWorkingDirectory (option_arg);
805 break;
806
807 case 't': // Open process in new terminal window
808 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
809 break;
810
811 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000812 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
813 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000814 break;
815
816 case 'A':
817 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
818 break;
819
Greg Clayton982c9762011-11-03 21:22:33 +0000820 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000821 if (option_arg && option_arg[0])
822 launch_info.SetShell (option_arg);
823 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000824 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000825 break;
826
Greg Clayton8b82f082011-04-12 05:54:46 +0000827 case 'v':
828 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
829 break;
830
831 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000832 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000833 break;
834
835 }
836 return error;
837}
838
839OptionDefinition
840ProcessLaunchCommandOptions::g_option_table[] =
841{
Virgile Belloe2607b52013-09-05 16:42:23 +0000842{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
843{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
844{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
845{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
846{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
847{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
848{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000849
Virgile Belloe2607b52013-09-05 16:42:23 +0000850{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
851{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
852{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000853
Virgile Belloe2607b52013-09-05 16:42:23 +0000854{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000855
Virgile Belloe2607b52013-09-05 16:42:23 +0000856{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000857
858{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
859};
860
861
862
863bool
864ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000865{
866 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
867 return true;
868 const char *match_name = m_match_info.GetName();
869 if (!match_name)
870 return true;
871
872 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
873}
874
875bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000876ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000877{
878 if (!NameMatches (proc_info.GetName()))
879 return false;
880
881 if (m_match_info.ProcessIDIsValid() &&
882 m_match_info.GetProcessID() != proc_info.GetProcessID())
883 return false;
884
885 if (m_match_info.ParentProcessIDIsValid() &&
886 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
887 return false;
888
Greg Clayton8b82f082011-04-12 05:54:46 +0000889 if (m_match_info.UserIDIsValid () &&
890 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000891 return false;
892
Greg Clayton8b82f082011-04-12 05:54:46 +0000893 if (m_match_info.GroupIDIsValid () &&
894 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000895 return false;
896
897 if (m_match_info.EffectiveUserIDIsValid () &&
898 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
899 return false;
900
901 if (m_match_info.EffectiveGroupIDIsValid () &&
902 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
903 return false;
904
905 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000906 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000907 return false;
908 return true;
909}
910
911bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000912ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000913{
914 if (m_name_match_type != eNameMatchIgnore)
915 return false;
916
917 if (m_match_info.ProcessIDIsValid())
918 return false;
919
920 if (m_match_info.ParentProcessIDIsValid())
921 return false;
922
Greg Clayton8b82f082011-04-12 05:54:46 +0000923 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000924 return false;
925
Greg Clayton8b82f082011-04-12 05:54:46 +0000926 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000927 return false;
928
929 if (m_match_info.EffectiveUserIDIsValid ())
930 return false;
931
932 if (m_match_info.EffectiveGroupIDIsValid ())
933 return false;
934
935 if (m_match_info.GetArchitecture().IsValid())
936 return false;
937
938 if (m_match_all_users)
939 return false;
940
941 return true;
942
943}
944
945void
Greg Clayton8b82f082011-04-12 05:54:46 +0000946ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000947{
948 m_match_info.Clear();
949 m_name_match_type = eNameMatchIgnore;
950 m_match_all_users = false;
951}
Greg Clayton58be07b2011-01-07 06:08:19 +0000952
Greg Claytonc3776bf2012-02-09 06:16:32 +0000953ProcessSP
954Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955{
Greg Clayton949e8222013-01-16 17:29:04 +0000956 static uint32_t g_process_unique_id = 0;
957
Greg Claytonc3776bf2012-02-09 06:16:32 +0000958 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959 ProcessCreateInstance create_callback = NULL;
960 if (plugin_name)
961 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000962 ConstString const_plugin_name(plugin_name);
963 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964 if (create_callback)
965 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000966 process_sp = create_callback(target, listener, crash_file_path);
967 if (process_sp)
968 {
Greg Clayton949e8222013-01-16 17:29:04 +0000969 if (process_sp->CanDebug(target, true))
970 {
971 process_sp->m_process_unique_id = ++g_process_unique_id;
972 }
973 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000974 process_sp.reset();
975 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000976 }
977 }
978 else
979 {
Greg Claytonc982c762010-07-09 20:39:50 +0000980 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000981 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000982 process_sp = create_callback(target, listener, crash_file_path);
983 if (process_sp)
984 {
Greg Clayton949e8222013-01-16 17:29:04 +0000985 if (process_sp->CanDebug(target, false))
986 {
987 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000988 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000989 }
990 else
991 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000992 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993 }
994 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000995 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996}
997
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000998ConstString &
999Process::GetStaticBroadcasterClass ()
1000{
1001 static ConstString class_name ("lldb.process");
1002 return class_name;
1003}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004
1005//----------------------------------------------------------------------
1006// Process constructor
1007//----------------------------------------------------------------------
1008Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +00001009 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001011 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013 m_public_state (eStateUnloaded),
1014 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001015 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1016 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017 m_private_state_listener ("lldb.process.internal_state_listener"),
1018 m_private_state_control_wait(),
1019 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001020 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001021 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022 m_thread_index_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001023 m_queue_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001024 m_thread_id_to_index_id_map (),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001025 m_queue_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001026 m_exit_status (-1),
1027 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001028 m_thread_mutex (Mutex::eMutexTypeRecursive),
1029 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001030 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +00001031 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +00001032 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001033 m_queue_list (this),
1034 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001036 m_image_tokens (),
1037 m_listener (listener),
1038 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001039 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001040 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001041 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001042 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001043 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001044 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001045 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001046 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001047 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1048 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001049 m_memory_cache (*this),
1050 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001051 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001052 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001053 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001054 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001055 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001056 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001057 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +00001058 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +00001059 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001060 m_destroy_in_process (false),
1061 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001063 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001064
Greg Clayton5160ce52013-03-27 23:08:40 +00001065 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001066 if (log)
1067 log->Printf ("%p Process::Process()", this);
1068
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001069 SetEventName (eBroadcastBitStateChanged, "state-changed");
1070 SetEventName (eBroadcastBitInterrupt, "interrupt");
1071 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1072 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001073 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001074
Greg Clayton35a4cc52012-10-29 20:52:08 +00001075 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1076 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1077 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1078
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079 listener.StartListeningForEvents (this,
1080 eBroadcastBitStateChanged |
1081 eBroadcastBitInterrupt |
1082 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001083 eBroadcastBitSTDERR |
1084 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085
1086 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001087 eBroadcastBitStateChanged |
1088 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089
1090 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1091 eBroadcastInternalStateControlStop |
1092 eBroadcastInternalStateControlPause |
1093 eBroadcastInternalStateControlResume);
1094}
1095
1096//----------------------------------------------------------------------
1097// Destructor
1098//----------------------------------------------------------------------
1099Process::~Process()
1100{
Greg Clayton5160ce52013-03-27 23:08:40 +00001101 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 if (log)
1103 log->Printf ("%p Process::~Process()", this);
1104 StopPrivateStateThread();
1105}
1106
Greg Clayton67cc0632012-08-22 17:17:09 +00001107const ProcessPropertiesSP &
1108Process::GetGlobalProperties()
1109{
1110 static ProcessPropertiesSP g_settings_sp;
1111 if (!g_settings_sp)
1112 g_settings_sp.reset (new ProcessProperties (true));
1113 return g_settings_sp;
1114}
1115
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116void
1117Process::Finalize()
1118{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001119 switch (GetPrivateState())
1120 {
1121 case eStateConnected:
1122 case eStateAttaching:
1123 case eStateLaunching:
1124 case eStateStopped:
1125 case eStateRunning:
1126 case eStateStepping:
1127 case eStateCrashed:
1128 case eStateSuspended:
1129 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001130 {
1131 // FIXME: This will have to be a process setting:
1132 bool keep_stopped = false;
1133 Detach(keep_stopped);
1134 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001135 else
1136 Destroy();
1137 break;
1138
1139 case eStateInvalid:
1140 case eStateUnloaded:
1141 case eStateDetached:
1142 case eStateExited:
1143 break;
1144 }
1145
Greg Clayton1ed54f52011-10-01 00:45:15 +00001146 // Clear our broadcaster before we proceed with destroying
1147 Broadcaster::Clear();
1148
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149 // Do any cleanup needed prior to being destructed... Subclasses
1150 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001151
1152 // We need to destroy the loader before the derived Process class gets destroyed
1153 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001154 m_dynamic_checkers_ap.reset();
1155 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001156 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00001157 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001158 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001159 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001160 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +00001161 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001162 m_queue_list.Clear();
1163 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +00001164 std::vector<Notifications> empty_notifications;
1165 m_notifications.swap(empty_notifications);
1166 m_image_tokens.clear();
1167 m_memory_cache.Clear();
1168 m_allocated_memory_cache.Clear();
1169 m_language_runtimes.clear();
1170 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001171//#ifdef LLDB_CONFIGURATION_DEBUG
1172// StreamFile s(stdout, false);
1173// EventSP event_sp;
1174// while (m_private_state_listener.GetNextEvent(event_sp))
1175// {
1176// event_sp->Dump (&s);
1177// s.EOL();
1178// }
1179//#endif
1180 // We have to be very careful here as the m_private_state_listener might
1181 // contain events that have ProcessSP values in them which can keep this
1182 // process around forever. These events need to be cleared out.
1183 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001184 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1185 m_public_run_lock.SetStopped();
1186 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1187 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001188 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189}
1190
1191void
1192Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1193{
1194 m_notifications.push_back(callbacks);
1195 if (callbacks.initialize != NULL)
1196 callbacks.initialize (callbacks.baton, this);
1197}
1198
1199bool
1200Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1201{
1202 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1203 for (pos = m_notifications.begin(); pos != end; ++pos)
1204 {
1205 if (pos->baton == callbacks.baton &&
1206 pos->initialize == callbacks.initialize &&
1207 pos->process_state_changed == callbacks.process_state_changed)
1208 {
1209 m_notifications.erase(pos);
1210 return true;
1211 }
1212 }
1213 return false;
1214}
1215
1216void
1217Process::SynchronouslyNotifyStateChanged (StateType state)
1218{
1219 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1220 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1221 {
1222 if (notification_pos->process_state_changed)
1223 notification_pos->process_state_changed (notification_pos->baton, this, state);
1224 }
1225}
1226
1227// FIXME: We need to do some work on events before the general Listener sees them.
1228// For instance if we are continuing from a breakpoint, we need to ensure that we do
1229// the little "insert real insn, step & stop" trick. But we can't do that when the
1230// event is delivered by the broadcaster - since that is done on the thread that is
1231// waiting for new events, so if we needed more than one event for our handling, we would
1232// stall. So instead we do it when we fetch the event off of the queue.
1233//
1234
1235StateType
1236Process::GetNextEvent (EventSP &event_sp)
1237{
1238 StateType state = eStateInvalid;
1239
1240 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1241 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1242
1243 return state;
1244}
1245
1246
1247StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001248Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001249{
Jim Ingham4b536182011-08-09 02:12:22 +00001250 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1251 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1252 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001253 if (event_sp_ptr)
1254 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001255 StateType state = GetState();
1256 // If we are exited or detached, we won't ever get back to any
1257 // other valid state...
1258 if (state == eStateDetached || state == eStateExited)
1259 return state;
1260
Daniel Malea9e9919f2013-10-09 16:56:28 +00001261 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1262 if (log)
1263 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1264
1265 if (!wait_always &&
1266 StateIsStoppedState(state, true) &&
1267 StateIsStoppedState(GetPrivateState(), true)) {
1268 if (log)
1269 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1270 __FUNCTION__);
1271 return state;
1272 }
1273
Jim Ingham4b536182011-08-09 02:12:22 +00001274 while (state != eStateInvalid)
1275 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001276 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001277 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001278 if (event_sp_ptr && event_sp)
1279 *event_sp_ptr = event_sp;
1280
Jim Ingham4b536182011-08-09 02:12:22 +00001281 switch (state)
1282 {
1283 case eStateCrashed:
1284 case eStateDetached:
1285 case eStateExited:
1286 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001287 // We need to toggle the run lock as this won't get done in
1288 // SetPublicState() if the process is hijacked.
1289 if (hijack_listener)
1290 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001291 return state;
1292 case eStateStopped:
1293 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1294 continue;
1295 else
Greg Clayton44d93782014-01-27 23:43:24 +00001296 {
1297 // We need to toggle the run lock as this won't get done in
1298 // SetPublicState() if the process is hijacked.
1299 if (hijack_listener)
1300 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001301 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001302 }
Jim Ingham4b536182011-08-09 02:12:22 +00001303 default:
1304 continue;
1305 }
1306 }
1307 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308}
1309
1310
1311StateType
1312Process::WaitForState
1313(
1314 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001315 const StateType *match_states,
1316 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001317)
1318{
1319 EventSP event_sp;
1320 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001321 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322 while (state != eStateInvalid)
1323 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001324 // If we are exited or detached, we won't ever get back to any
1325 // other valid state...
1326 if (state == eStateDetached || state == eStateExited)
1327 return state;
1328
Greg Clayton44d93782014-01-27 23:43:24 +00001329 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330
1331 for (i=0; i<num_match_states; ++i)
1332 {
1333 if (match_states[i] == state)
1334 return state;
1335 }
1336 }
1337 return state;
1338}
1339
Jim Ingham30f9b212010-10-11 23:53:14 +00001340bool
1341Process::HijackProcessEvents (Listener *listener)
1342{
1343 if (listener != NULL)
1344 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001345 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001346 }
1347 else
1348 return false;
1349}
1350
1351void
1352Process::RestoreProcessEvents ()
1353{
1354 RestoreBroadcaster();
1355}
1356
Jim Ingham0f16e732011-02-08 05:20:59 +00001357bool
1358Process::HijackPrivateProcessEvents (Listener *listener)
1359{
1360 if (listener != NULL)
1361 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001362 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001363 }
1364 else
1365 return false;
1366}
1367
1368void
1369Process::RestorePrivateProcessEvents ()
1370{
1371 m_private_state_broadcaster.RestoreBroadcaster();
1372}
1373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001375Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376{
Greg Clayton5160ce52013-03-27 23:08:40 +00001377 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378
1379 if (log)
1380 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1381
Greg Clayton44d93782014-01-27 23:43:24 +00001382 Listener *listener = hijack_listener;
1383 if (listener == NULL)
1384 listener = &m_listener;
1385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001386 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001387 if (listener->WaitForEventForBroadcasterWithType (timeout,
1388 this,
1389 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1390 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001391 {
1392 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1393 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1394 else if (log)
1395 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1396 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001397
1398 if (log)
1399 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1400 __FUNCTION__,
1401 timeout,
1402 StateAsCString(state));
1403 return state;
1404}
1405
1406Event *
1407Process::PeekAtStateChangedEvents ()
1408{
Greg Clayton5160ce52013-03-27 23:08:40 +00001409 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410
1411 if (log)
1412 log->Printf ("Process::%s...", __FUNCTION__);
1413
1414 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001415 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1416 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001417 if (log)
1418 {
1419 if (event_ptr)
1420 {
1421 log->Printf ("Process::%s (event_ptr) => %s",
1422 __FUNCTION__,
1423 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1424 }
1425 else
1426 {
1427 log->Printf ("Process::%s no events found",
1428 __FUNCTION__);
1429 }
1430 }
1431 return event_ptr;
1432}
1433
1434StateType
1435Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1436{
Greg Clayton5160ce52013-03-27 23:08:40 +00001437 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001438
1439 if (log)
1440 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1441
1442 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001443 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1444 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001445 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001446 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001447 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1448 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001449
1450 // This is a bit of a hack, but when we wait here we could very well return
1451 // to the command-line, and that could disable the log, which would render the
1452 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001453 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001454 {
1455 if (state == eStateInvalid)
1456 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1457 else
1458 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1459 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001460 return state;
1461}
1462
1463bool
1464Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1465{
Greg Clayton5160ce52013-03-27 23:08:40 +00001466 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467
1468 if (log)
1469 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1470
1471 if (control_only)
1472 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1473 else
1474 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1475}
1476
1477bool
1478Process::IsRunning () const
1479{
1480 return StateIsRunningState (m_public_state.GetValue());
1481}
1482
1483int
1484Process::GetExitStatus ()
1485{
1486 if (m_public_state.GetValue() == eStateExited)
1487 return m_exit_status;
1488 return -1;
1489}
1490
Greg Clayton85851dd2010-12-04 00:10:17 +00001491
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492const char *
1493Process::GetExitDescription ()
1494{
1495 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1496 return m_exit_string.c_str();
1497 return NULL;
1498}
1499
Greg Clayton6779606a2011-01-22 23:43:18 +00001500bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001501Process::SetExitStatus (int status, const char *cstr)
1502{
Greg Clayton5160ce52013-03-27 23:08:40 +00001503 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001504 if (log)
1505 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1506 status, status,
1507 cstr ? "\"" : "",
1508 cstr ? cstr : "NULL",
1509 cstr ? "\"" : "");
1510
Greg Clayton6779606a2011-01-22 23:43:18 +00001511 // We were already in the exited state
1512 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001513 {
Greg Clayton385d6032011-01-26 23:47:29 +00001514 if (log)
1515 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001516 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001517 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001518
1519 m_exit_status = status;
1520 if (cstr)
1521 m_exit_string = cstr;
1522 else
1523 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001524
Greg Clayton6779606a2011-01-22 23:43:18 +00001525 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001526
Greg Clayton6779606a2011-01-22 23:43:18 +00001527 SetPrivateState (eStateExited);
Greg Clayton44d93782014-01-27 23:43:24 +00001528 CancelWatchForSTDIN (true);
Greg Clayton6779606a2011-01-22 23:43:18 +00001529 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530}
1531
1532// This static callback can be used to watch for local child processes on
1533// the current host. The the child process exits, the process will be
1534// found in the global target list (we want to be completely sure that the
1535// lldb_private::Process doesn't go away before we can deliver the signal.
1536bool
Greg Claytone4e45922011-11-16 05:37:56 +00001537Process::SetProcessExitStatus (void *callback_baton,
1538 lldb::pid_t pid,
1539 bool exited,
1540 int signo, // Zero for no signal
1541 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542)
1543{
Greg Clayton5160ce52013-03-27 23:08:40 +00001544 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001545 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001546 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001547 callback_baton,
1548 pid,
1549 exited,
1550 signo,
1551 exit_status);
1552
1553 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001554 {
Greg Clayton66111032010-06-23 01:19:29 +00001555 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001556 if (target_sp)
1557 {
1558 ProcessSP process_sp (target_sp->GetProcessSP());
1559 if (process_sp)
1560 {
1561 const char *signal_cstr = NULL;
1562 if (signo)
1563 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1564
1565 process_sp->SetExitStatus (exit_status, signal_cstr);
1566 }
1567 }
1568 return true;
1569 }
1570 return false;
1571}
1572
1573
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001574void
1575Process::UpdateThreadListIfNeeded ()
1576{
1577 const uint32_t stop_id = GetStopID();
1578 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1579 {
Greg Clayton2637f822011-11-17 01:23:07 +00001580 const StateType state = GetPrivateState();
1581 if (StateIsStoppedState (state, true))
1582 {
1583 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001584 // m_thread_list does have its own mutex, but we need to
1585 // hold onto the mutex between the call to UpdateThreadList(...)
1586 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001587 ThreadList &old_thread_list = m_thread_list;
1588 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001589 ThreadList new_thread_list(this);
1590 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001591 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001592 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001593 {
Jim Ingham09437922013-03-01 20:04:25 +00001594 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1595 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1596 // shutting us down, causing a deadlock.
1597 if (!m_destroy_in_process)
1598 {
1599 OperatingSystem *os = GetOperatingSystem ();
1600 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001601 {
1602 // Clear any old backing threads where memory threads might have been
1603 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001604 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001605 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001606 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001607
1608 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001609 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1610 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1611 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Claytonb3ae8762013-04-12 20:07:46 +00001612 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001613 else
1614 {
1615 // No OS plug-in, the new thread list is the same as the real thread list
1616 new_thread_list = real_thread_list;
1617 }
Jim Ingham09437922013-03-01 20:04:25 +00001618 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001619
1620 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001621 m_thread_list.Update (new_thread_list);
1622 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001623
Jason Molenda4ff13262013-11-20 00:31:38 +00001624 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1625 {
1626 // Clear any extended threads that we may have accumulated previously
1627 m_extended_thread_list.Clear();
1628 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001629
1630 m_queue_list.Clear();
1631 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001632 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001633 }
Greg Clayton2637f822011-11-17 01:23:07 +00001634 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001635 }
1636}
1637
Jason Molenda5e8dce42013-12-13 00:29:16 +00001638void
1639Process::UpdateQueueListIfNeeded ()
1640{
1641 if (m_system_runtime_ap.get())
1642 {
1643 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1644 {
1645 const StateType state = GetPrivateState();
1646 if (StateIsStoppedState (state, true))
1647 {
1648 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1649 m_queue_list_stop_id = GetLastNaturalStopID();
1650 }
1651 }
1652 }
1653}
1654
Greg Claytona4d87472013-01-18 23:41:08 +00001655ThreadSP
1656Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1657{
1658 OperatingSystem *os = GetOperatingSystem ();
1659 if (os)
1660 return os->CreateThread(tid, context);
1661 return ThreadSP();
1662}
1663
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001664uint32_t
1665Process::GetNextThreadIndexID (uint64_t thread_id)
1666{
1667 return AssignIndexIDToThread(thread_id);
1668}
1669
1670bool
1671Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1672{
1673 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1674 if (iterator == m_thread_id_to_index_id_map.end())
1675 {
1676 return false;
1677 }
1678 else
1679 {
1680 return true;
1681 }
1682}
1683
1684uint32_t
1685Process::AssignIndexIDToThread(uint64_t thread_id)
1686{
1687 uint32_t result = 0;
1688 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1689 if (iterator == m_thread_id_to_index_id_map.end())
1690 {
1691 result = ++m_thread_index_id;
1692 m_thread_id_to_index_id_map[thread_id] = result;
1693 }
1694 else
1695 {
1696 result = iterator->second;
1697 }
1698
1699 return result;
1700}
1701
Jason Molenda5e8dce42013-12-13 00:29:16 +00001702bool
1703Process::HasAssignedIndexIDToQueue(queue_id_t queue_id)
1704{
1705 std::map<uint64_t, uint32_t>::iterator iterator = m_queue_id_to_index_id_map.find(queue_id);
1706 if (iterator == m_queue_id_to_index_id_map.end())
1707 {
1708 return false;
1709 }
1710 else
1711 {
1712 return true;
1713 }
1714}
1715
1716uint32_t
1717Process::AssignIndexIDToQueue(queue_id_t queue_id)
1718{
1719 uint32_t result = 0;
1720 std::map<uint64_t, uint32_t>::iterator iterator = m_queue_id_to_index_id_map.find(queue_id);
1721 if (iterator == m_queue_id_to_index_id_map.end())
1722 {
1723 result = ++m_queue_index_id;
1724 m_queue_id_to_index_id_map[queue_id] = result;
1725 }
1726 else
1727 {
1728 result = iterator->second;
1729 }
1730
1731 return result;
1732}
1733
1734
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001735StateType
1736Process::GetState()
1737{
1738 // If any other threads access this we will need a mutex for it
1739 return m_public_state.GetValue ();
1740}
1741
1742void
Jim Ingham221d51c2013-05-08 00:35:16 +00001743Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001744{
Greg Clayton5160ce52013-03-27 23:08:40 +00001745 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001746 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001747 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001748 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001749 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001750
1751 // On the transition from Run to Stopped, we unlock the writer end of the
1752 // run lock. The lock gets locked in Resume, which is the public API
1753 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001754 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1755 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001756 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001757 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001758 if (log)
1759 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001760 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001761 }
1762 else
1763 {
1764 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1765 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001766 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001767 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001768 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001769 {
1770 if (log)
1771 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001772 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001773 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001774 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001775 }
1776 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001777}
1778
Jim Ingham3b8285d2012-04-19 01:40:33 +00001779Error
1780Process::Resume ()
1781{
Greg Clayton5160ce52013-03-27 23:08:40 +00001782 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001783 if (log)
1784 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001785 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001786 {
1787 Error error("Resume request failed - process still running.");
1788 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001789 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001790 return error;
1791 }
1792 return PrivateResume();
1793}
1794
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795StateType
1796Process::GetPrivateState ()
1797{
1798 return m_private_state.GetValue();
1799}
1800
1801void
1802Process::SetPrivateState (StateType new_state)
1803{
Greg Clayton5160ce52013-03-27 23:08:40 +00001804 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805 bool state_changed = false;
1806
1807 if (log)
1808 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1809
Andrew Kaylor29d65742013-05-10 17:19:04 +00001810 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811 Mutex::Locker locker(m_private_state.GetMutex());
1812
1813 const StateType old_state = m_private_state.GetValueNoLock ();
1814 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001815
Greg Claytonaa49c832013-05-03 22:25:56 +00001816 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1817 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1818 if (old_state_is_stopped != new_state_is_stopped)
1819 {
1820 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001821 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001822 else
Ed Maste64fad602013-07-29 20:58:06 +00001823 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001824 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001825
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 if (state_changed)
1827 {
1828 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001829 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001831 // Note, this currently assumes that all threads in the list
1832 // stop when the process stops. In the future we will want to
1833 // support a debugging model where some threads continue to run
1834 // while others are stopped. When that happens we will either need
1835 // a way for the thread list to identify which threads are stopping
1836 // or create a special thread list containing only threads which
1837 // actually stopped.
1838 //
1839 // The process plugin is responsible for managing the actual
1840 // behavior of the threads and should have stopped any threads
1841 // that are going to stop before we get here.
1842 m_thread_list.DidStop();
1843
Jim Ingham4b536182011-08-09 02:12:22 +00001844 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001845 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001846 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001847 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848 }
1849 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001850 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1851 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1852 else
1853 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001854 }
1855 else
1856 {
1857 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001858 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001859 }
1860}
1861
Jim Ingham0faa43f2011-11-08 03:00:11 +00001862void
1863Process::SetRunningUserExpression (bool on)
1864{
1865 m_mod_id.SetRunningUserExpression (on);
1866}
1867
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001868addr_t
1869Process::GetImageInfoAddress()
1870{
1871 return LLDB_INVALID_ADDRESS;
1872}
1873
Greg Clayton8f343b02010-11-04 01:54:29 +00001874//----------------------------------------------------------------------
1875// LoadImage
1876//
1877// This function provides a default implementation that works for most
1878// unix variants. Any Process subclasses that need to do shared library
1879// loading differently should override LoadImage and UnloadImage and
1880// do what is needed.
1881//----------------------------------------------------------------------
1882uint32_t
1883Process::LoadImage (const FileSpec &image_spec, Error &error)
1884{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001885 char path[PATH_MAX];
1886 image_spec.GetPath(path, sizeof(path));
1887
Greg Clayton8f343b02010-11-04 01:54:29 +00001888 DynamicLoader *loader = GetDynamicLoader();
1889 if (loader)
1890 {
1891 error = loader->CanLoadImage();
1892 if (error.Fail())
1893 return LLDB_INVALID_IMAGE_TOKEN;
1894 }
1895
1896 if (error.Success())
1897 {
1898 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001899
1900 if (thread_sp)
1901 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001902 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001903
1904 if (frame_sp)
1905 {
1906 ExecutionContext exe_ctx;
1907 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001908 EvaluateExpressionOptions expr_options;
1909 expr_options.SetUnwindOnError(true);
1910 expr_options.SetIgnoreBreakpoints(true);
1911 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001912 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001913 expr.Printf("dlopen (\"%s\", 2)", path);
1914 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001915 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001916 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001917 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001918 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001919 expr.GetData(),
1920 prefix,
1921 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001922 expr_error);
1923 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001924 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001925 error = result_valobj_sp->GetError();
1926 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001927 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001928 Scalar scalar;
1929 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001930 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001931 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1932 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1933 {
1934 uint32_t image_token = m_image_tokens.size();
1935 m_image_tokens.push_back (image_ptr);
1936 return image_token;
1937 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001938 }
1939 }
1940 }
1941 }
1942 }
1943 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001944 if (!error.AsCString())
1945 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001946 return LLDB_INVALID_IMAGE_TOKEN;
1947}
1948
1949//----------------------------------------------------------------------
1950// UnloadImage
1951//
1952// This function provides a default implementation that works for most
1953// unix variants. Any Process subclasses that need to do shared library
1954// loading differently should override LoadImage and UnloadImage and
1955// do what is needed.
1956//----------------------------------------------------------------------
1957Error
1958Process::UnloadImage (uint32_t image_token)
1959{
1960 Error error;
1961 if (image_token < m_image_tokens.size())
1962 {
1963 const addr_t image_addr = m_image_tokens[image_token];
1964 if (image_addr == LLDB_INVALID_ADDRESS)
1965 {
1966 error.SetErrorString("image already unloaded");
1967 }
1968 else
1969 {
1970 DynamicLoader *loader = GetDynamicLoader();
1971 if (loader)
1972 error = loader->CanLoadImage();
1973
1974 if (error.Success())
1975 {
1976 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001977
1978 if (thread_sp)
1979 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001980 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001981
1982 if (frame_sp)
1983 {
1984 ExecutionContext exe_ctx;
1985 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001986 EvaluateExpressionOptions expr_options;
1987 expr_options.SetUnwindOnError(true);
1988 expr_options.SetIgnoreBreakpoints(true);
1989 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001990 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001991 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001992 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001993 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001994 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001995 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001996 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001997 expr.GetData(),
1998 prefix,
1999 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002000 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002001 if (result_valobj_sp->GetError().Success())
2002 {
2003 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002004 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002005 {
2006 if (scalar.UInt(1))
2007 {
2008 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2009 }
2010 else
2011 {
2012 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2013 }
2014 }
2015 }
2016 else
2017 {
2018 error = result_valobj_sp->GetError();
2019 }
2020 }
2021 }
2022 }
2023 }
2024 }
2025 else
2026 {
2027 error.SetErrorString("invalid image token");
2028 }
2029 return error;
2030}
2031
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002032const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002033Process::GetABI()
2034{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002035 if (!m_abi_sp)
2036 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2037 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038}
2039
Jim Ingham22777012010-09-23 02:01:19 +00002040LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002041Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002042{
2043 LanguageRuntimeCollection::iterator pos;
2044 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002045 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002046 {
Jim Inghamab175242012-03-10 00:22:19 +00002047 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002048
Jim Inghamab175242012-03-10 00:22:19 +00002049 m_language_runtimes[language] = runtime_sp;
2050 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002051 }
2052 else
2053 return (*pos).second.get();
2054}
2055
2056CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002057Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002058{
Jim Inghamab175242012-03-10 00:22:19 +00002059 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002060 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2061 return static_cast<CPPLanguageRuntime *> (runtime);
2062 return NULL;
2063}
2064
2065ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002066Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002067{
Jim Inghamab175242012-03-10 00:22:19 +00002068 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002069 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2070 return static_cast<ObjCLanguageRuntime *> (runtime);
2071 return NULL;
2072}
2073
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002074bool
2075Process::IsPossibleDynamicValue (ValueObject& in_value)
2076{
2077 if (in_value.IsDynamic())
2078 return false;
2079 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2080
2081 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2082 {
2083 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2084 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2085 }
2086
2087 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2088 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2089 return true;
2090
2091 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2092 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2093}
2094
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095BreakpointSiteList &
2096Process::GetBreakpointSiteList()
2097{
2098 return m_breakpoint_site_list;
2099}
2100
2101const BreakpointSiteList &
2102Process::GetBreakpointSiteList() const
2103{
2104 return m_breakpoint_site_list;
2105}
2106
2107
2108void
2109Process::DisableAllBreakpointSites ()
2110{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002111 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2112// bp_site->SetEnabled(true);
2113 DisableBreakpointSite(bp_site);
2114 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002115}
2116
2117Error
2118Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2119{
2120 Error error (DisableBreakpointSiteByID (break_id));
2121
2122 if (error.Success())
2123 m_breakpoint_site_list.Remove(break_id);
2124
2125 return error;
2126}
2127
2128Error
2129Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2130{
2131 Error error;
2132 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2133 if (bp_site_sp)
2134 {
2135 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002136 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002137 }
2138 else
2139 {
Daniel Malead01b2952012-11-29 21:49:15 +00002140 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002141 }
2142
2143 return error;
2144}
2145
2146Error
2147Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2148{
2149 Error error;
2150 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2151 if (bp_site_sp)
2152 {
2153 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002154 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155 }
2156 else
2157 {
Daniel Malead01b2952012-11-29 21:49:15 +00002158 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002159 }
2160 return error;
2161}
2162
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002163lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002164Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002166 addr_t load_addr = LLDB_INVALID_ADDRESS;
2167
2168 bool show_error = true;
2169 switch (GetState())
2170 {
2171 case eStateInvalid:
2172 case eStateUnloaded:
2173 case eStateConnected:
2174 case eStateAttaching:
2175 case eStateLaunching:
2176 case eStateDetached:
2177 case eStateExited:
2178 show_error = false;
2179 break;
2180
2181 case eStateStopped:
2182 case eStateRunning:
2183 case eStateStepping:
2184 case eStateCrashed:
2185 case eStateSuspended:
2186 show_error = IsAlive();
2187 break;
2188 }
2189
2190 // Reset the IsIndirect flag here, in case the location changes from
2191 // pointing to a indirect symbol to a regular symbol.
2192 owner->SetIsIndirect (false);
2193
2194 if (owner->ShouldResolveIndirectFunctions())
2195 {
2196 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2197 if (symbol && symbol->IsIndirect())
2198 {
2199 Error error;
2200 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2201 if (!error.Success() && show_error)
2202 {
Greg Clayton44d93782014-01-27 23:43:24 +00002203 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2204 symbol->GetAddress().GetLoadAddress(&m_target),
2205 owner->GetBreakpoint().GetID(),
2206 owner->GetID(),
2207 error.AsCString() ? error.AsCString() : "unkown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002208 return LLDB_INVALID_BREAK_ID;
2209 }
2210 Address resolved_address(load_addr);
2211 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2212 owner->SetIsIndirect(true);
2213 }
2214 else
2215 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2216 }
2217 else
2218 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2219
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002220 if (load_addr != LLDB_INVALID_ADDRESS)
2221 {
2222 BreakpointSiteSP bp_site_sp;
2223
2224 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2225 // create a new breakpoint site and add it.
2226
2227 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2228
2229 if (bp_site_sp)
2230 {
2231 bp_site_sp->AddOwner (owner);
2232 owner->SetBreakpointSite (bp_site_sp);
2233 return bp_site_sp->GetID();
2234 }
2235 else
2236 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002237 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238 if (bp_site_sp)
2239 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002240 Error error = EnableBreakpointSite (bp_site_sp.get());
2241 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242 {
2243 owner->SetBreakpointSite (bp_site_sp);
2244 return m_breakpoint_site_list.Add (bp_site_sp);
2245 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002246 else
2247 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002248 if (show_error)
2249 {
2250 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002251 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2252 load_addr,
2253 owner->GetBreakpoint().GetID(),
2254 owner->GetID(),
2255 error.AsCString() ? error.AsCString() : "unkown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002256 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002257 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258 }
2259 }
2260 }
2261 // We failed to enable the breakpoint
2262 return LLDB_INVALID_BREAK_ID;
2263
2264}
2265
2266void
2267Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2268{
2269 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2270 if (num_owners == 0)
2271 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002272 // Don't try to disable the site if we don't have a live process anymore.
2273 if (IsAlive())
2274 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002275 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2276 }
2277}
2278
2279
2280size_t
2281Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2282{
2283 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002284 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285
Jim Ingham20c77192011-06-29 19:42:28 +00002286 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002287 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002288 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2289 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002291 addr_t intersect_addr;
2292 size_t intersect_size;
2293 size_t opcode_offset;
2294 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002295 {
2296 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2297 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002298 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002299 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002300 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002301 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002302 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002303 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 }
2305 return bytes_removed;
2306}
2307
2308
Greg Claytonded470d2011-03-19 01:12:21 +00002309
2310size_t
2311Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2312{
2313 PlatformSP platform_sp (m_target.GetPlatform());
2314 if (platform_sp)
2315 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2316 return 0;
2317}
2318
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002319Error
2320Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2321{
2322 Error error;
2323 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002324 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 const addr_t bp_addr = bp_site->GetLoadAddress();
2326 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002327 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002328 if (bp_site->IsEnabled())
2329 {
2330 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002331 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332 return error;
2333 }
2334
2335 if (bp_addr == LLDB_INVALID_ADDRESS)
2336 {
2337 error.SetErrorString("BreakpointSite contains an invalid load address.");
2338 return error;
2339 }
2340 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2341 // trap for the breakpoint site
2342 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2343
2344 if (bp_opcode_size == 0)
2345 {
Daniel Malead01b2952012-11-29 21:49:15 +00002346 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 }
2348 else
2349 {
2350 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2351
2352 if (bp_opcode_bytes == NULL)
2353 {
2354 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2355 return error;
2356 }
2357
2358 // Save the original opcode by reading it
2359 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2360 {
2361 // Write a software breakpoint in place of the original opcode
2362 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2363 {
2364 uint8_t verify_bp_opcode_bytes[64];
2365 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2366 {
2367 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2368 {
2369 bp_site->SetEnabled(true);
2370 bp_site->SetType (BreakpointSite::eSoftware);
2371 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002372 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373 bp_site->GetID(),
2374 (uint64_t)bp_addr);
2375 }
2376 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002377 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378 }
2379 else
2380 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2381 }
2382 else
2383 error.SetErrorString("Unable to write breakpoint trap to memory.");
2384 }
2385 else
2386 error.SetErrorString("Unable to read memory at breakpoint address.");
2387 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002388 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002389 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002390 bp_site->GetID(),
2391 (uint64_t)bp_addr,
2392 error.AsCString());
2393 return error;
2394}
2395
2396Error
2397Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2398{
2399 Error error;
2400 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002401 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 addr_t bp_addr = bp_site->GetLoadAddress();
2403 lldb::user_id_t breakID = bp_site->GetID();
2404 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002405 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406
2407 if (bp_site->IsHardware())
2408 {
2409 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2410 }
2411 else if (bp_site->IsEnabled())
2412 {
2413 const size_t break_op_size = bp_site->GetByteSize();
2414 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2415 if (break_op_size > 0)
2416 {
2417 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002418 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002419 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420 bool break_op_found = false;
2421
2422 // Read the breakpoint opcode
2423 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2424 {
2425 bool verify = false;
2426 // Make sure we have the a breakpoint opcode exists at this address
2427 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2428 {
2429 break_op_found = true;
2430 // We found a valid breakpoint opcode at this address, now restore
2431 // the saved opcode.
2432 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2433 {
2434 verify = true;
2435 }
2436 else
2437 error.SetErrorString("Memory write failed when restoring original opcode.");
2438 }
2439 else
2440 {
2441 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2442 // Set verify to true and so we can check if the original opcode has already been restored
2443 verify = true;
2444 }
2445
2446 if (verify)
2447 {
Greg Claytonc982c762010-07-09 20:39:50 +00002448 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002449 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450 // Verify that our original opcode made it back to the inferior
2451 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2452 {
2453 // compare the memory we just read with the original opcode
2454 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2455 {
2456 // SUCCESS
2457 bp_site->SetEnabled(false);
2458 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002459 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002460 return error;
2461 }
2462 else
2463 {
2464 if (break_op_found)
2465 error.SetErrorString("Failed to restore original opcode.");
2466 }
2467 }
2468 else
2469 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2470 }
2471 }
2472 else
2473 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2474 }
2475 }
2476 else
2477 {
2478 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002479 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480 return error;
2481 }
2482
2483 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002484 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485 bp_site->GetID(),
2486 (uint64_t)bp_addr,
2487 error.AsCString());
2488 return error;
2489
2490}
2491
Greg Clayton58be07b2011-01-07 06:08:19 +00002492// Uncomment to verify memory caching works after making changes to caching code
2493//#define VERIFY_MEMORY_READS
2494
Sean Callanan64c0cf22012-06-07 22:26:42 +00002495size_t
2496Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2497{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002498 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002499 if (!GetDisableMemoryCache())
2500 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002501#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002502 // Memory caching is enabled, with debug verification
2503
2504 if (buf && size)
2505 {
2506 // Uncomment the line below to make sure memory caching is working.
2507 // I ran this through the test suite and got no assertions, so I am
2508 // pretty confident this is working well. If any changes are made to
2509 // memory caching, uncomment the line below and test your changes!
2510
2511 // Verify all memory reads by using the cache first, then redundantly
2512 // reading the same memory from the inferior and comparing to make sure
2513 // everything is exactly the same.
2514 std::string verify_buf (size, '\0');
2515 assert (verify_buf.size() == size);
2516 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2517 Error verify_error;
2518 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2519 assert (cache_bytes_read == verify_bytes_read);
2520 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2521 assert (verify_error.Success() == error.Success());
2522 return cache_bytes_read;
2523 }
2524 return 0;
2525#else // !defined(VERIFY_MEMORY_READS)
2526 // Memory caching is enabled, without debug verification
2527
2528 return m_memory_cache.Read (addr, buf, size, error);
2529#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002530 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002531 else
2532 {
2533 // Memory caching is disabled
2534
2535 return ReadMemoryFromInferior (addr, buf, size, error);
2536 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002537}
Greg Clayton58be07b2011-01-07 06:08:19 +00002538
Greg Clayton4c82d422012-05-18 23:20:01 +00002539size_t
2540Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2541{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002542 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002543 out_str.clear();
2544 addr_t curr_addr = addr;
2545 while (1)
2546 {
2547 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2548 if (length == 0)
2549 break;
2550 out_str.append(buf, length);
2551 // If we got "length - 1" bytes, we didn't get the whole C string, we
2552 // need to read some more characters
2553 if (length == sizeof(buf) - 1)
2554 curr_addr += length;
2555 else
2556 break;
2557 }
2558 return out_str.size();
2559}
2560
Greg Clayton58be07b2011-01-07 06:08:19 +00002561
2562size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002563Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2564 size_t type_width)
2565{
2566 size_t total_bytes_read = 0;
2567 if (dst && max_bytes && type_width && max_bytes >= type_width)
2568 {
2569 // Ensure a null terminator independent of the number of bytes that is read.
2570 memset (dst, 0, max_bytes);
2571 size_t bytes_left = max_bytes - type_width;
2572
2573 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2574 assert(sizeof(terminator) >= type_width &&
2575 "Attempting to validate a string with more than 4 bytes per character!");
2576
2577 addr_t curr_addr = addr;
2578 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2579 char *curr_dst = dst;
2580
2581 error.Clear();
2582 while (bytes_left > 0 && error.Success())
2583 {
2584 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2585 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2586 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2587
2588 if (bytes_read == 0)
2589 break;
2590
2591 // Search for a null terminator of correct size and alignment in bytes_read
2592 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2593 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2594 if (::strncmp(&dst[i], terminator, type_width) == 0)
2595 {
2596 error.Clear();
2597 return i;
2598 }
2599
2600 total_bytes_read += bytes_read;
2601 curr_dst += bytes_read;
2602 curr_addr += bytes_read;
2603 bytes_left -= bytes_read;
2604 }
2605 }
2606 else
2607 {
2608 if (max_bytes)
2609 error.SetErrorString("invalid arguments");
2610 }
2611 return total_bytes_read;
2612}
2613
2614// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2615// null terminators.
2616size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002617Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002618{
2619 size_t total_cstr_len = 0;
2620 if (dst && dst_max_len)
2621 {
Greg Claytone91b7952011-12-15 03:14:23 +00002622 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002623 // NULL out everything just to be safe
2624 memset (dst, 0, dst_max_len);
2625 Error error;
2626 addr_t curr_addr = addr;
2627 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2628 size_t bytes_left = dst_max_len - 1;
2629 char *curr_dst = dst;
2630
2631 while (bytes_left > 0)
2632 {
2633 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2634 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2635 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2636
2637 if (bytes_read == 0)
2638 {
Greg Claytone91b7952011-12-15 03:14:23 +00002639 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002640 dst[total_cstr_len] = '\0';
2641 break;
2642 }
2643 const size_t len = strlen(curr_dst);
2644
2645 total_cstr_len += len;
2646
2647 if (len < bytes_to_read)
2648 break;
2649
2650 curr_dst += bytes_read;
2651 curr_addr += bytes_read;
2652 bytes_left -= bytes_read;
2653 }
2654 }
Greg Claytone91b7952011-12-15 03:14:23 +00002655 else
2656 {
2657 if (dst == NULL)
2658 result_error.SetErrorString("invalid arguments");
2659 else
2660 result_error.Clear();
2661 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002662 return total_cstr_len;
2663}
2664
2665size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002666Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2667{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002668 if (buf == NULL || size == 0)
2669 return 0;
2670
2671 size_t bytes_read = 0;
2672 uint8_t *bytes = (uint8_t *)buf;
2673
2674 while (bytes_read < size)
2675 {
2676 const size_t curr_size = size - bytes_read;
2677 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2678 bytes + bytes_read,
2679 curr_size,
2680 error);
2681 bytes_read += curr_bytes_read;
2682 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2683 break;
2684 }
2685
2686 // Replace any software breakpoint opcodes that fall into this range back
2687 // into "buf" before we return
2688 if (bytes_read > 0)
2689 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2690 return bytes_read;
2691}
2692
Greg Clayton58a4c462010-12-16 20:01:20 +00002693uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002694Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002695{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002696 Scalar scalar;
2697 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2698 return scalar.ULongLong(fail_value);
2699 return fail_value;
2700}
2701
2702addr_t
2703Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2704{
2705 Scalar scalar;
2706 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2707 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2708 return LLDB_INVALID_ADDRESS;
2709}
2710
2711
2712bool
2713Process::WritePointerToMemory (lldb::addr_t vm_addr,
2714 lldb::addr_t ptr_value,
2715 Error &error)
2716{
2717 Scalar scalar;
2718 const uint32_t addr_byte_size = GetAddressByteSize();
2719 if (addr_byte_size <= 4)
2720 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002721 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002722 scalar = ptr_value;
2723 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002724}
2725
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726size_t
2727Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2728{
2729 size_t bytes_written = 0;
2730 const uint8_t *bytes = (const uint8_t *)buf;
2731
2732 while (bytes_written < size)
2733 {
2734 const size_t curr_size = size - bytes_written;
2735 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2736 bytes + bytes_written,
2737 curr_size,
2738 error);
2739 bytes_written += curr_bytes_written;
2740 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2741 break;
2742 }
2743 return bytes_written;
2744}
2745
2746size_t
2747Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2748{
Greg Clayton58be07b2011-01-07 06:08:19 +00002749#if defined (ENABLE_MEMORY_CACHING)
2750 m_memory_cache.Flush (addr, size);
2751#endif
2752
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 if (buf == NULL || size == 0)
2754 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002755
Jim Ingham4b536182011-08-09 02:12:22 +00002756 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002757
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002758 // We need to write any data that would go where any current software traps
2759 // (enabled software breakpoints) any software traps (breakpoints) that we
2760 // may have placed in our tasks memory.
2761
Greg Claytond8cf1a12013-06-12 00:46:38 +00002762 BreakpointSiteList bp_sites_in_range;
2763
2764 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002766 // No breakpoint sites overlap
2767 if (bp_sites_in_range.IsEmpty())
2768 return WriteMemoryPrivate (addr, buf, size, error);
2769 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002770 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002771 const uint8_t *ubuf = (const uint8_t *)buf;
2772 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773
Greg Claytond8cf1a12013-06-12 00:46:38 +00002774 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2775
2776 if (error.Success())
2777 {
2778 addr_t intersect_addr;
2779 size_t intersect_size;
2780 size_t opcode_offset;
2781 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2782 assert(intersects);
2783 assert(addr <= intersect_addr && intersect_addr < addr + size);
2784 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2785 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2786
2787 // Check for bytes before this breakpoint
2788 const addr_t curr_addr = addr + bytes_written;
2789 if (intersect_addr > curr_addr)
2790 {
2791 // There are some bytes before this breakpoint that we need to
2792 // just write to memory
2793 size_t curr_size = intersect_addr - curr_addr;
2794 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2795 ubuf + bytes_written,
2796 curr_size,
2797 error);
2798 bytes_written += curr_bytes_written;
2799 if (curr_bytes_written != curr_size)
2800 {
2801 // We weren't able to write all of the requested bytes, we
2802 // are done looping and will return the number of bytes that
2803 // we have written so far.
2804 if (error.Success())
2805 error.SetErrorToGenericError();
2806 }
2807 }
2808 // Now write any bytes that would cover up any software breakpoints
2809 // directly into the breakpoint opcode buffer
2810 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2811 bytes_written += intersect_size;
2812 }
2813 });
2814
2815 if (bytes_written < size)
2816 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2817 ubuf + bytes_written,
2818 size - bytes_written,
2819 error);
2820 }
2821 }
2822 else
2823 {
2824 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002825 }
2826
2827 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002828 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002829}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002830
2831size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002832Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002833{
2834 if (byte_size == UINT32_MAX)
2835 byte_size = scalar.GetByteSize();
2836 if (byte_size > 0)
2837 {
2838 uint8_t buf[32];
2839 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2840 if (mem_size > 0)
2841 return WriteMemory(addr, buf, mem_size, error);
2842 else
2843 error.SetErrorString ("failed to get scalar as memory data");
2844 }
2845 else
2846 {
2847 error.SetErrorString ("invalid scalar value");
2848 }
2849 return 0;
2850}
2851
2852size_t
2853Process::ReadScalarIntegerFromMemory (addr_t addr,
2854 uint32_t byte_size,
2855 bool is_signed,
2856 Scalar &scalar,
2857 Error &error)
2858{
Greg Clayton7060f892013-05-01 23:41:30 +00002859 uint64_t uval = 0;
2860 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002861 {
Greg Clayton7060f892013-05-01 23:41:30 +00002862 error.SetErrorString ("byte size is zero");
2863 }
2864 else if (byte_size & (byte_size - 1))
2865 {
2866 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2867 }
2868 else if (byte_size <= sizeof(uval))
2869 {
2870 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002871 if (bytes_read == byte_size)
2872 {
2873 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002874 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002875 if (byte_size <= 4)
2876 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002877 else
Greg Clayton7060f892013-05-01 23:41:30 +00002878 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002879 if (is_signed)
2880 scalar.SignExtend(byte_size * 8);
2881 return bytes_read;
2882 }
2883 }
2884 else
2885 {
2886 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2887 }
2888 return 0;
2889}
2890
Greg Claytond495c532011-05-17 03:37:42 +00002891#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892addr_t
2893Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2894{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002895 if (GetPrivateState() != eStateStopped)
2896 return LLDB_INVALID_ADDRESS;
2897
Greg Claytond495c532011-05-17 03:37:42 +00002898#if defined (USE_ALLOCATE_MEMORY_CACHE)
2899 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2900#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002901 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002902 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002903 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002904 log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Deepak Panickald66b50c2013-10-22 12:27:43 +00002905 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002906 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002907 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002908 m_mod_id.GetStopID(),
2909 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002910 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002911#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912}
2913
Sean Callanan90539452011-09-20 23:01:51 +00002914bool
2915Process::CanJIT ()
2916{
Sean Callanana7b443a2012-02-14 22:50:38 +00002917 if (m_can_jit == eCanJITDontKnow)
2918 {
2919 Error err;
2920
2921 uint64_t allocated_memory = AllocateMemory(8,
2922 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2923 err);
2924
2925 if (err.Success())
2926 m_can_jit = eCanJITYes;
2927 else
2928 m_can_jit = eCanJITNo;
2929
2930 DeallocateMemory (allocated_memory);
2931 }
2932
Sean Callanan90539452011-09-20 23:01:51 +00002933 return m_can_jit == eCanJITYes;
2934}
2935
2936void
2937Process::SetCanJIT (bool can_jit)
2938{
2939 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2940}
2941
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942Error
2943Process::DeallocateMemory (addr_t ptr)
2944{
Greg Claytond495c532011-05-17 03:37:42 +00002945 Error error;
2946#if defined (USE_ALLOCATE_MEMORY_CACHE)
2947 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2948 {
Daniel Malead01b2952012-11-29 21:49:15 +00002949 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002950 }
2951#else
2952 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002953
Greg Clayton5160ce52013-03-27 23:08:40 +00002954 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002955 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002956 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002957 ptr,
2958 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002959 m_mod_id.GetStopID(),
2960 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002961#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002962 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963}
2964
Han Ming Ongc811d382012-11-17 00:33:14 +00002965
Greg Claytonc9660542012-02-05 02:38:54 +00002966ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002967Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002968 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002969{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002970 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002971 if (module_sp)
2972 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002973 Error error;
2974 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2975 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002976 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002977 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002978 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002979}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002980
2981Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002982Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983{
2984 Error error;
2985 error.SetErrorString("watchpoints are not supported");
2986 return error;
2987}
2988
2989Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002990Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991{
2992 Error error;
2993 error.SetErrorString("watchpoints are not supported");
2994 return error;
2995}
2996
2997StateType
2998Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2999{
3000 StateType state;
3001 // Now wait for the process to launch and return control to us, and then
3002 // call DidLaunch:
3003 while (1)
3004 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003005 event_sp.reset();
3006 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3007
Greg Clayton2637f822011-11-17 01:23:07 +00003008 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003009 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003010
3011 // If state is invalid, then we timed out
3012 if (state == eStateInvalid)
3013 break;
3014
3015 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 HandlePrivateEvent (event_sp);
3017 }
3018 return state;
3019}
3020
3021Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003022Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003023{
3024 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003025 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003026 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003027 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003028 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003029 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003030
Greg Claytonaa149cb2011-08-11 02:48:45 +00003031 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032 if (exe_module)
3033 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003034 char local_exec_file_path[PATH_MAX];
3035 char platform_exec_file_path[PATH_MAX];
3036 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3037 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003038 if (exe_module->GetFileSpec().Exists())
3039 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003040 // Install anything that might need to be installed prior to launching.
3041 // For host systems, this will do nothing, but if we are connected to a
3042 // remote platform it will install any needed binaries
3043 error = GetTarget().Install(&launch_info);
3044 if (error.Fail())
3045 return error;
3046
Greg Clayton71337622011-02-24 22:24:29 +00003047 if (PrivateStateThreadIsValid ())
3048 PausePrivateStateThread ();
3049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 error = WillLaunch (exe_module);
3051 if (error.Success())
3052 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003053 const bool restarted = false;
3054 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003055 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056
Ed Maste64fad602013-07-29 20:58:06 +00003057 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003058 {
3059 // Now launch using these arguments.
3060 error = DoLaunch (exe_module, launch_info);
3061 }
3062 else
3063 {
3064 // This shouldn't happen
3065 error.SetErrorString("failed to acquire process run lock");
3066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067
3068 if (error.Fail())
3069 {
3070 if (GetID() != LLDB_INVALID_PROCESS_ID)
3071 {
3072 SetID (LLDB_INVALID_PROCESS_ID);
3073 const char *error_string = error.AsCString();
3074 if (error_string == NULL)
3075 error_string = "launch failed";
3076 SetExitStatus (-1, error_string);
3077 }
3078 }
3079 else
3080 {
3081 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003082 TimeValue timeout_time;
3083 timeout_time = TimeValue::Now();
3084 timeout_time.OffsetWithSeconds(10);
3085 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086
Greg Clayton1a38ea72011-06-22 01:42:17 +00003087 if (state == eStateInvalid || event_sp.get() == NULL)
3088 {
3089 // We were able to launch the process, but we failed to
3090 // catch the initial stop.
3091 SetExitStatus (0, "failed to catch stop after launch");
3092 Destroy();
3093 }
3094 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003095 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003096
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097 DidLaunch ();
3098
Greg Claytonc859e2d2012-02-13 23:10:39 +00003099 DynamicLoader *dyld = GetDynamicLoader ();
3100 if (dyld)
3101 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003102
Jason Molendaeef51062013-11-05 03:57:19 +00003103 SystemRuntime *system_runtime = GetSystemRuntime ();
3104 if (system_runtime)
3105 system_runtime->DidLaunch();
3106
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003107 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108 // This delays passing the stopped event to listeners till DidLaunch gets
3109 // a chance to complete...
3110 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00003111
3112 if (PrivateStateThreadIsValid ())
3113 ResumePrivateStateThread ();
3114 else
3115 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003116 }
3117 else if (state == eStateExited)
3118 {
3119 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3120 // not likely to work, and return an invalid pid.
3121 HandlePrivateEvent (event_sp);
3122 }
3123 }
3124 }
3125 }
3126 else
3127 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003128 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129 }
3130 }
3131 return error;
3132}
3133
Greg Claytonc3776bf2012-02-09 06:16:32 +00003134
3135Error
3136Process::LoadCore ()
3137{
3138 Error error = DoLoadCore();
3139 if (error.Success())
3140 {
3141 if (PrivateStateThreadIsValid ())
3142 ResumePrivateStateThread ();
3143 else
3144 StartPrivateStateThread ();
3145
Greg Claytonc859e2d2012-02-13 23:10:39 +00003146 DynamicLoader *dyld = GetDynamicLoader ();
3147 if (dyld)
3148 dyld->DidAttach();
3149
Jason Molendaeef51062013-11-05 03:57:19 +00003150 SystemRuntime *system_runtime = GetSystemRuntime ();
3151 if (system_runtime)
3152 system_runtime->DidAttach();
3153
Greg Claytonc859e2d2012-02-13 23:10:39 +00003154 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003155 // We successfully loaded a core file, now pretend we stopped so we can
3156 // show all of the threads in the core file and explore the crashed
3157 // state.
3158 SetPrivateState (eStateStopped);
3159
3160 }
3161 return error;
3162}
3163
Greg Claytonc859e2d2012-02-13 23:10:39 +00003164DynamicLoader *
3165Process::GetDynamicLoader ()
3166{
3167 if (m_dyld_ap.get() == NULL)
3168 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3169 return m_dyld_ap.get();
3170}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003171
Jason Molendaeef51062013-11-05 03:57:19 +00003172SystemRuntime *
3173Process::GetSystemRuntime ()
3174{
3175 if (m_system_runtime_ap.get() == NULL)
3176 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3177 return m_system_runtime_ap.get();
3178}
3179
Greg Claytonc3776bf2012-02-09 06:16:32 +00003180
Jim Inghambb3a2832011-01-29 01:49:25 +00003181Process::NextEventAction::EventActionResult
3182Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183{
Jim Inghambb3a2832011-01-29 01:49:25 +00003184 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3185 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003186 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003187 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003188 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003189 return eEventActionRetry;
3190
3191 case eStateStopped:
3192 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003193 {
3194 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003195 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003196 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003197 // We don't want these events to be reported, so go set the ShouldReportStop here:
3198 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3199
Greg Claytonc9ed4782011-11-12 02:10:56 +00003200 if (m_exec_count > 0)
3201 {
3202 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003203 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003204 return eEventActionRetry;
3205 }
3206 else
3207 {
3208 m_process->CompleteAttach ();
3209 return eEventActionSuccess;
3210 }
3211 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003212 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003213
Greg Clayton513c26c2011-01-29 07:10:55 +00003214 default:
3215 case eStateExited:
3216 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003217 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003218 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003219
3220 m_exit_string.assign ("No valid Process");
3221 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003222}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003223
Jim Inghambb3a2832011-01-29 01:49:25 +00003224Process::NextEventAction::EventActionResult
3225Process::AttachCompletionHandler::HandleBeingInterrupted()
3226{
3227 return eEventActionSuccess;
3228}
3229
3230const char *
3231Process::AttachCompletionHandler::GetExitString ()
3232{
3233 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234}
3235
3236Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003237Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003238{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003240 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003241 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003242 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003243 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003244
Greg Clayton144f3a92011-11-15 03:53:30 +00003245 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003246 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003247 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003248 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003249 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003250
Greg Clayton144f3a92011-11-15 03:53:30 +00003251 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003252 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003253 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3254
3255 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003257 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3258 if (error.Success())
3259 {
Ed Maste64fad602013-07-29 20:58:06 +00003260 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003261 {
3262 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003263 const bool restarted = false;
3264 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003265 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003266 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003267 }
3268 else
3269 {
3270 // This shouldn't happen
3271 error.SetErrorString("failed to acquire process run lock");
3272 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003273
Greg Clayton144f3a92011-11-15 03:53:30 +00003274 if (error.Fail())
3275 {
3276 if (GetID() != LLDB_INVALID_PROCESS_ID)
3277 {
3278 SetID (LLDB_INVALID_PROCESS_ID);
3279 if (error.AsCString() == NULL)
3280 error.SetErrorString("attach failed");
3281
3282 SetExitStatus(-1, error.AsCString());
3283 }
3284 }
3285 else
3286 {
3287 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3288 StartPrivateStateThread();
3289 }
3290 return error;
3291 }
Greg Claytone996fd32011-03-08 22:40:15 +00003292 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003293 else
Greg Claytone996fd32011-03-08 22:40:15 +00003294 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003295 ProcessInstanceInfoList process_infos;
3296 PlatformSP platform_sp (m_target.GetPlatform ());
3297
3298 if (platform_sp)
3299 {
3300 ProcessInstanceInfoMatch match_info;
3301 match_info.GetProcessInfo() = attach_info;
3302 match_info.SetNameMatchType (eNameMatchEquals);
3303 platform_sp->FindProcesses (match_info, process_infos);
3304 const uint32_t num_matches = process_infos.GetSize();
3305 if (num_matches == 1)
3306 {
3307 attach_pid = process_infos.GetProcessIDAtIndex(0);
3308 // Fall through and attach using the above process ID
3309 }
3310 else
3311 {
3312 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3313 if (num_matches > 1)
3314 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3315 else
3316 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3317 }
3318 }
3319 else
3320 {
3321 error.SetErrorString ("invalid platform, can't find processes by name");
3322 return error;
3323 }
Greg Claytone996fd32011-03-08 22:40:15 +00003324 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325 }
3326 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003327 {
3328 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003329 }
3330 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003331
3332 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003333 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003334 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003335 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003337
Ed Maste64fad602013-07-29 20:58:06 +00003338 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003339 {
3340 // Now attach using these arguments.
3341 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003342 const bool restarted = false;
3343 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003344 error = DoAttachToProcessWithID (attach_pid, attach_info);
3345 }
3346 else
3347 {
3348 // This shouldn't happen
3349 error.SetErrorString("failed to acquire process run lock");
3350 }
3351
Greg Clayton144f3a92011-11-15 03:53:30 +00003352 if (error.Success())
3353 {
3354
3355 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3356 StartPrivateStateThread();
3357 }
3358 else
Greg Claytone996fd32011-03-08 22:40:15 +00003359 {
3360 if (GetID() != LLDB_INVALID_PROCESS_ID)
3361 {
3362 SetID (LLDB_INVALID_PROCESS_ID);
3363 const char *error_string = error.AsCString();
3364 if (error_string == NULL)
3365 error_string = "attach failed";
3366
3367 SetExitStatus(-1, error_string);
3368 }
3369 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 }
3371 }
3372 return error;
3373}
3374
Greg Clayton93d3c8332011-02-16 04:46:07 +00003375void
3376Process::CompleteAttach ()
3377{
3378 // Let the process subclass figure out at much as it can about the process
3379 // before we go looking for a dynamic loader plug-in.
3380 DidAttach();
3381
Jim Ingham4299fdb2011-09-15 01:10:17 +00003382 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3383 // the same as the one we've already set, switch architectures.
3384 PlatformSP platform_sp (m_target.GetPlatform ());
3385 assert (platform_sp.get());
3386 if (platform_sp)
3387 {
Greg Clayton70512312012-05-08 01:45:38 +00003388 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003389 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003390 {
3391 ArchSpec platform_arch;
3392 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3393 if (platform_sp)
3394 {
3395 m_target.SetPlatform (platform_sp);
3396 m_target.SetArchitecture(platform_arch);
3397 }
3398 }
3399 else
3400 {
3401 ProcessInstanceInfo process_info;
3402 platform_sp->GetProcessInfo (GetID(), process_info);
3403 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003404 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003405 m_target.SetArchitecture (process_arch);
3406 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003407 }
3408
3409 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003410 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003411 DynamicLoader *dyld = GetDynamicLoader ();
3412 if (dyld)
3413 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003414
Jason Molendaeef51062013-11-05 03:57:19 +00003415 SystemRuntime *system_runtime = GetSystemRuntime ();
3416 if (system_runtime)
3417 system_runtime->DidAttach();
3418
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003419 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003420 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003421 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003422 Mutex::Locker modules_locker(target_modules.GetMutex());
3423 size_t num_modules = target_modules.GetSize();
3424 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003425
Andy Gibbsa297a972013-06-19 19:04:53 +00003426 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003427 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003428 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003429 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003430 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003431 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003432 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003433 break;
3434 }
3435 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003436 if (new_executable_module_sp)
3437 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003438}
3439
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003440Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003441Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003442{
Greg Claytonb766a732011-02-04 01:58:07 +00003443 m_abi_sp.reset();
3444 m_process_input_reader.reset();
3445
3446 // Find the process and its architecture. Make sure it matches the architecture
3447 // of the current Target, and if not adjust it.
3448
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003449 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003450 if (error.Success())
3451 {
Greg Clayton71337622011-02-24 22:24:29 +00003452 if (GetID() != LLDB_INVALID_PROCESS_ID)
3453 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003454 EventSP event_sp;
3455 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3456
3457 if (state == eStateStopped || state == eStateCrashed)
3458 {
3459 // If we attached and actually have a process on the other end, then
3460 // this ended up being the equivalent of an attach.
3461 CompleteAttach ();
3462
3463 // This delays passing the stopped event to listeners till
3464 // CompleteAttach gets a chance to complete...
3465 HandlePrivateEvent (event_sp);
3466
3467 }
Greg Clayton71337622011-02-24 22:24:29 +00003468 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003469
3470 if (PrivateStateThreadIsValid ())
3471 ResumePrivateStateThread ();
3472 else
3473 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003474 }
3475 return error;
3476}
3477
3478
3479Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003480Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003481{
Greg Clayton5160ce52013-03-27 23:08:40 +00003482 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003483 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003484 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003485 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003486 StateAsCString(m_public_state.GetValue()),
3487 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488
3489 Error error (WillResume());
3490 // Tell the process it is about to resume before the thread list
3491 if (error.Success())
3492 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003493 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003494 // can let all of our threads know that they are about to be
3495 // resumed. Threads will each be called with
3496 // Thread::WillResume(StateType) where StateType contains the state
3497 // that they are supposed to have when the process is resumed
3498 // (suspended/running/stepping). Threads should also check
3499 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003500 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003501 if (m_thread_list.WillResume())
3502 {
Jim Ingham372787f2012-04-07 00:00:41 +00003503 // Last thing, do the PreResumeActions.
3504 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003505 {
Jim Ingham0161b492013-02-09 01:29:05 +00003506 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003507 }
3508 else
3509 {
3510 m_mod_id.BumpResumeID();
3511 error = DoResume();
3512 if (error.Success())
3513 {
3514 DidResume();
3515 m_thread_list.DidResume();
3516 if (log)
3517 log->Printf ("Process thinks the process has resumed.");
3518 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003519 }
3520 }
3521 else
3522 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003523 // Somebody wanted to run without running. So generate a continue & a stopped event,
3524 // and let the world handle them.
3525 if (log)
3526 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3527
3528 SetPrivateState(eStateRunning);
3529 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003530 }
3531 }
Jim Ingham444586b2011-01-24 06:34:17 +00003532 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003533 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003534 return error;
3535}
3536
3537Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003538Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003539{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003540 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3541 // in case it was already set and some thread plan logic calls halt on its
3542 // own.
3543 m_clear_thread_plans_on_stop |= clear_thread_plans;
3544
Jim Inghamaacc3182012-06-06 00:29:30 +00003545 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3546 // we could just straightaway get another event. It just narrows the window...
3547 m_currently_handling_event.WaitForValueEqualTo(false);
3548
3549
Jim Inghambb3a2832011-01-29 01:49:25 +00003550 // Pause our private state thread so we can ensure no one else eats
3551 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003552 Listener halt_listener ("lldb.process.halt_listener");
3553 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003554
Jim Inghambb3a2832011-01-29 01:49:25 +00003555 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003556 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003557
Greg Clayton513c26c2011-01-29 07:10:55 +00003558 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003559 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003560
Greg Clayton513c26c2011-01-29 07:10:55 +00003561 bool caused_stop = false;
3562
3563 // Ask the process subclass to actually halt our process
3564 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003566 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003567 if (m_public_state.GetValue() == eStateAttaching)
3568 {
3569 SetExitStatus(SIGKILL, "Cancelled async attach.");
3570 Destroy ();
3571 }
3572 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003573 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003574 // If "caused_stop" is true, then DoHalt stopped the process. If
3575 // "caused_stop" is false, the process was already stopped.
3576 // If the DoHalt caused the process to stop, then we want to catch
3577 // this event and set the interrupted bool to true before we pass
3578 // this along so clients know that the process was interrupted by
3579 // a halt command.
3580 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003581 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003582 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003583 TimeValue timeout_time;
3584 timeout_time = TimeValue::Now();
3585 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003586 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3587 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003588
Jim Ingham0f16e732011-02-08 05:20:59 +00003589 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003590 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003591 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003592 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003593 }
3594 else
3595 {
Greg Clayton2637f822011-11-17 01:23:07 +00003596 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003597 {
3598 // We caused the process to interrupt itself, so mark this
3599 // as such in the stop event so clients can tell an interrupted
3600 // process from a natural stop
3601 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3602 }
3603 else
3604 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003605 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003606 if (log)
3607 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3608 error.SetErrorString ("Did not get stopped event after halt.");
3609 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003610 }
3611 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003612 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003613 }
3614 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003615 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003616 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003617 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003618
3619 // Post any event we might have consumed. If all goes well, we will have
3620 // stopped the process, intercepted the event and set the interrupted
3621 // bool in the event. Post it to the private event queue and that will end up
3622 // correctly setting the state.
3623 if (event_sp)
3624 m_private_state_broadcaster.BroadcastEvent(event_sp);
3625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626 return error;
3627}
3628
3629Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003630Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3631{
3632 Error error;
3633 if (m_public_state.GetValue() == eStateRunning)
3634 {
3635 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3636 if (log)
3637 log->Printf("Process::Destroy() About to halt.");
3638 error = Halt();
3639 if (error.Success())
3640 {
3641 // Consume the halt event.
3642 TimeValue timeout (TimeValue::Now());
3643 timeout.OffsetWithSeconds(1);
3644 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3645
3646 // If the process exited while we were waiting for it to stop, put the exited event into
3647 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3648 // they don't have a process anymore...
3649
3650 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3651 {
3652 if (log)
3653 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3654 return error;
3655 }
3656 else
3657 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3658
3659 if (state != eStateStopped)
3660 {
3661 if (log)
3662 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3663 // If we really couldn't stop the process then we should just error out here, but if the
3664 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3665 StateType private_state = m_private_state.GetValue();
3666 if (private_state != eStateStopped)
3667 {
3668 return error;
3669 }
3670 }
3671 }
3672 else
3673 {
3674 if (log)
3675 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3676 }
3677 }
3678 return error;
3679}
3680
3681Error
Jim Inghamacff8952013-05-02 00:27:30 +00003682Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003684 EventSP exit_event_sp;
3685 Error error;
3686 m_destroy_in_process = true;
3687
3688 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003689
3690 if (error.Success())
3691 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003692 if (DetachRequiresHalt())
3693 {
3694 error = HaltForDestroyOrDetach (exit_event_sp);
3695 if (!error.Success())
3696 {
3697 m_destroy_in_process = false;
3698 return error;
3699 }
3700 else if (exit_event_sp)
3701 {
3702 // We shouldn't need to do anything else here. There's no process left to detach from...
3703 StopPrivateStateThread();
3704 m_destroy_in_process = false;
3705 return error;
3706 }
3707 }
3708
Jim Inghamacff8952013-05-02 00:27:30 +00003709 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003710 if (error.Success())
3711 {
3712 DidDetach();
3713 StopPrivateStateThread();
3714 }
Jim Inghamacff8952013-05-02 00:27:30 +00003715 else
3716 {
3717 return error;
3718 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003720 m_destroy_in_process = false;
3721
3722 // If we exited when we were waiting for a process to stop, then
3723 // forward the event here so we don't lose the event
3724 if (exit_event_sp)
3725 {
3726 // Directly broadcast our exited event because we shut down our
3727 // private state thread above
3728 BroadcastEvent(exit_event_sp);
3729 }
3730
3731 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3732 // the last events through the event system, in which case we might strand the write lock. Unlock
3733 // it here so when we do to tear down the process we don't get an error destroying the lock.
3734
Ed Maste64fad602013-07-29 20:58:06 +00003735 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736 return error;
3737}
3738
3739Error
3740Process::Destroy ()
3741{
Jim Ingham09437922013-03-01 20:04:25 +00003742
3743 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3744 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3745 // failed and the process stays around for some reason it won't be in a confused state.
3746
3747 m_destroy_in_process = true;
3748
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003749 Error error (WillDestroy());
3750 if (error.Success())
3751 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003752 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003753 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003754 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003755 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003756 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003757
Jim Inghamaacc3182012-06-06 00:29:30 +00003758 if (m_public_state.GetValue() != eStateRunning)
3759 {
3760 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3761 // kill it, we don't want it hitting a breakpoint...
3762 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3763 // we're not going to have much luck doing this now.
3764 m_thread_list.DiscardThreadPlans();
3765 DisableAllBreakpointSites();
3766 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003767
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003768 error = DoDestroy();
3769 if (error.Success())
3770 {
3771 DidDestroy();
3772 StopPrivateStateThread();
3773 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003774 m_stdio_communication.StopReadThread();
3775 m_stdio_communication.Disconnect();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003776 if (m_process_input_reader)
3777 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003778
3779 // If we exited when we were waiting for a process to stop, then
3780 // forward the event here so we don't lose the event
3781 if (exit_event_sp)
3782 {
3783 // Directly broadcast our exited event because we shut down our
3784 // private state thread above
3785 BroadcastEvent(exit_event_sp);
3786 }
3787
Jim Inghamb1e2e842012-04-12 18:49:31 +00003788 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3789 // the last events through the event system, in which case we might strand the write lock. Unlock
3790 // it here so when we do to tear down the process we don't get an error destroying the lock.
Ed Maste64fad602013-07-29 20:58:06 +00003791 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003792 }
Jim Ingham09437922013-03-01 20:04:25 +00003793
3794 m_destroy_in_process = false;
3795
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003796 return error;
3797}
3798
3799Error
3800Process::Signal (int signal)
3801{
3802 Error error (WillSignal());
3803 if (error.Success())
3804 {
3805 error = DoSignal(signal);
3806 if (error.Success())
3807 DidSignal();
3808 }
3809 return error;
3810}
3811
Greg Clayton514487e2011-02-15 21:59:32 +00003812lldb::ByteOrder
3813Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814{
Greg Clayton514487e2011-02-15 21:59:32 +00003815 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003816}
3817
3818uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003819Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003820{
Greg Clayton514487e2011-02-15 21:59:32 +00003821 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003822}
3823
Greg Clayton514487e2011-02-15 21:59:32 +00003824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825bool
3826Process::ShouldBroadcastEvent (Event *event_ptr)
3827{
3828 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3829 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003830 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003831
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 switch (state)
3833 {
Greg Claytonb766a732011-02-04 01:58:07 +00003834 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003835 case eStateAttaching:
3836 case eStateLaunching:
3837 case eStateDetached:
3838 case eStateExited:
3839 case eStateUnloaded:
3840 // These events indicate changes in the state of the debugging session, always report them.
3841 return_value = true;
3842 break;
3843 case eStateInvalid:
3844 // We stopped for no apparent reason, don't report it.
3845 return_value = false;
3846 break;
3847 case eStateRunning:
3848 case eStateStepping:
3849 // If we've started the target running, we handle the cases where we
3850 // are already running and where there is a transition from stopped to
3851 // running differently.
3852 // running -> running: Automatically suppress extra running events
3853 // stopped -> running: Report except when there is one or more no votes
3854 // and no yes votes.
3855 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003856 if (m_force_next_event_delivery)
3857 return_value = true;
3858 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003859 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003860 switch (m_last_broadcast_state)
3861 {
3862 case eStateRunning:
3863 case eStateStepping:
3864 // We always suppress multiple runnings with no PUBLIC stop in between.
3865 return_value = false;
3866 break;
3867 default:
3868 // TODO: make this work correctly. For now always report
3869 // run if we aren't running so we don't miss any runnning
3870 // events. If I run the lldb/test/thread/a.out file and
3871 // break at main.cpp:58, run and hit the breakpoints on
3872 // multiple threads, then somehow during the stepping over
3873 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003874
Jim Ingham1460e4b2014-01-10 23:46:59 +00003875 // This is a transition from stop to run.
3876 switch (m_thread_list.ShouldReportRun (event_ptr))
3877 {
3878 case eVoteYes:
3879 case eVoteNoOpinion:
3880 return_value = true;
3881 break;
3882 case eVoteNo:
3883 return_value = false;
3884 break;
3885 }
3886 break;
3887 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003888 }
3889 break;
3890 case eStateStopped:
3891 case eStateCrashed:
3892 case eStateSuspended:
3893 {
3894 // We've stopped. First see if we're going to restart the target.
3895 // If we are going to stop, then we always broadcast the event.
3896 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003897 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003898
Jim Inghamcb4ca112012-05-16 01:32:14 +00003899 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003900 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003901 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003902 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003903 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3904 event_ptr,
3905 StateAsCString(state));
3906 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003907 }
3908 else
3909 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003910 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3911 bool should_resume = false;
3912
Jim Ingham0161b492013-02-09 01:29:05 +00003913 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3914 // Asking the thread list is also not likely to go well, since we are running again.
3915 // So in that case just report the event.
3916
Jim Ingham0161b492013-02-09 01:29:05 +00003917 if (!was_restarted)
3918 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003919
3920 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921 {
Jim Ingham0161b492013-02-09 01:29:05 +00003922 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3923 if (log)
3924 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3925 should_resume,
3926 StateAsCString(state),
3927 was_restarted,
3928 stop_vote);
3929
3930 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003931 {
3932 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003933 return_value = true;
3934 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003935 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003936 case eVoteNo:
3937 return_value = false;
3938 break;
3939 }
Jim Ingham0161b492013-02-09 01:29:05 +00003940
Jim Inghamcb95f342012-09-05 21:13:56 +00003941 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003942 {
3943 if (log)
3944 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3945 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003946 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003947 }
3948
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003949 }
3950 else
3951 {
3952 return_value = true;
3953 SynchronouslyNotifyStateChanged (state);
3954 }
3955 }
3956 }
Jim Ingham0161b492013-02-09 01:29:05 +00003957 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003958 }
Jim Ingham0161b492013-02-09 01:29:05 +00003959
Jim Ingham1460e4b2014-01-10 23:46:59 +00003960 // Forcing the next event delivery is a one shot deal. So reset it here.
3961 m_force_next_event_delivery = false;
3962
Jim Ingham0161b492013-02-09 01:29:05 +00003963 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3964 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3965 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3966 // because the PublicState reflects the last event pulled off the queue, and there may be several
3967 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3968 // yet. m_last_broadcast_state gets updated here.
3969
3970 if (return_value)
3971 m_last_broadcast_state = state;
3972
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003973 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003974 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3975 event_ptr,
3976 StateAsCString(state),
3977 StateAsCString(m_last_broadcast_state),
3978 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003979 return return_value;
3980}
3981
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982
3983bool
Jim Ingham372787f2012-04-07 00:00:41 +00003984Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003985{
Greg Clayton5160ce52013-03-27 23:08:40 +00003986 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003987
Greg Clayton8b82f082011-04-12 05:54:46 +00003988 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003990 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3991
Jim Ingham372787f2012-04-07 00:00:41 +00003992 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003993 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003994
3995 // Create a thread that watches our internal state and controls which
3996 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003997 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003998 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003999 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00004000 else
Daniel Malead01b2952012-11-29 21:49:15 +00004001 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00004002
4003 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00004004 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00004005 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
4006 if (success)
4007 {
4008 ResumePrivateStateThread();
4009 return true;
4010 }
4011 else
4012 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004013}
4014
4015void
4016Process::PausePrivateStateThread ()
4017{
4018 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4019}
4020
4021void
4022Process::ResumePrivateStateThread ()
4023{
4024 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4025}
4026
4027void
4028Process::StopPrivateStateThread ()
4029{
Greg Clayton8b82f082011-04-12 05:54:46 +00004030 if (PrivateStateThreadIsValid ())
4031 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004032 else
4033 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004034 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004035 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004036 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004037 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038}
4039
4040void
4041Process::ControlPrivateStateThread (uint32_t signal)
4042{
Greg Clayton5160ce52013-03-27 23:08:40 +00004043 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004044
4045 assert (signal == eBroadcastInternalStateControlStop ||
4046 signal == eBroadcastInternalStateControlPause ||
4047 signal == eBroadcastInternalStateControlResume);
4048
4049 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004050 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004052 // Signal the private state thread. First we should copy this is case the
4053 // thread starts exiting since the private state thread will NULL this out
4054 // when it exits
4055 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00004056 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004057 {
4058 TimeValue timeout_time;
4059 bool timed_out;
4060
4061 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4062
4063 timeout_time = TimeValue::Now();
4064 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004065 if (log)
4066 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004067 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4068 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4069
4070 if (signal == eBroadcastInternalStateControlStop)
4071 {
4072 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004073 {
4074 Error error;
4075 Host::ThreadCancel (private_state_thread, &error);
4076 if (log)
4077 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4078 }
4079 else
4080 {
4081 if (log)
4082 log->Printf ("The control event killed the private state thread without having to cancel.");
4083 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004084
4085 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004086 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00004087 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004088 }
4089 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004090 else
4091 {
4092 if (log)
4093 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4094 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004095}
4096
4097void
Jim Inghamcfc09352012-07-27 23:57:19 +00004098Process::SendAsyncInterrupt ()
4099{
4100 if (PrivateStateThreadIsValid())
4101 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4102 else
4103 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4104}
4105
4106void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004107Process::HandlePrivateEvent (EventSP &event_sp)
4108{
Greg Clayton5160ce52013-03-27 23:08:40 +00004109 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004110 m_resume_requested = false;
4111
Jim Inghamaacc3182012-06-06 00:29:30 +00004112 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004113
Greg Clayton414f5d32011-01-25 02:58:48 +00004114 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004115
4116 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004117 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004118 {
Jim Ingham754ab982011-01-29 04:05:41 +00004119 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004120 if (log)
4121 log->Printf ("Ran next event action, result was %d.", action_result);
4122
Jim Inghambb3a2832011-01-29 01:49:25 +00004123 switch (action_result)
4124 {
4125 case NextEventAction::eEventActionSuccess:
4126 SetNextEventAction(NULL);
4127 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004128
Jim Inghambb3a2832011-01-29 01:49:25 +00004129 case NextEventAction::eEventActionRetry:
4130 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004131
Jim Inghambb3a2832011-01-29 01:49:25 +00004132 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004133 // Handle Exiting Here. If we already got an exited event,
4134 // we should just propagate it. Otherwise, swallow this event,
4135 // and set our state to exit so the next event will kill us.
4136 if (new_state != eStateExited)
4137 {
4138 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004139 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004140 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004141 SetNextEventAction(NULL);
4142 return;
4143 }
4144 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004145 break;
4146 }
4147 }
4148
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149 // See if we should broadcast this state to external clients?
4150 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004151
4152 if (should_broadcast)
4153 {
4154 if (log)
4155 {
Daniel Malead01b2952012-11-29 21:49:15 +00004156 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004157 __FUNCTION__,
4158 GetID(),
4159 StateAsCString(new_state),
4160 StateAsCString (GetState ()),
4161 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004162 }
Jim Ingham9575d842011-03-11 03:53:59 +00004163 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004164 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004165 {
4166 // Only push the input handler if we aren't fowarding events,
4167 // as this means the curses GUI is in use...
4168 if (!GetTarget().GetDebugger().IsForwardingEvents())
4169 PushProcessIOHandler ();
4170 }
Jim Inghamb78d73f2013-05-15 01:21:48 +00004171 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Greg Clayton44d93782014-01-27 23:43:24 +00004172 PopProcessIOHandler ();
Jim Ingham9575d842011-03-11 03:53:59 +00004173
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004174 BroadcastEvent (event_sp);
4175 }
4176 else
4177 {
4178 if (log)
4179 {
Daniel Malead01b2952012-11-29 21:49:15 +00004180 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004181 __FUNCTION__,
4182 GetID(),
4183 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004184 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185 }
4186 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004187 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004188}
4189
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004190thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004191Process::PrivateStateThread (void *arg)
4192{
4193 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004194 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004195 return result;
4196}
4197
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004198thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004199Process::RunPrivateStateThread ()
4200{
Jim Ingham076b3042012-04-10 01:21:57 +00004201 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004202 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004203
Greg Clayton5160ce52013-03-27 23:08:40 +00004204 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004205 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004206 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004207
4208 bool exit_now = false;
4209 while (!exit_now)
4210 {
4211 EventSP event_sp;
4212 WaitForEventsPrivate (NULL, event_sp, control_only);
4213 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4214 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004215 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004216 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004217
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004218 switch (event_sp->GetType())
4219 {
4220 case eBroadcastInternalStateControlStop:
4221 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004222 break; // doing any internal state managment below
4223
4224 case eBroadcastInternalStateControlPause:
4225 control_only = true;
4226 break;
4227
4228 case eBroadcastInternalStateControlResume:
4229 control_only = false;
4230 break;
4231 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004232
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004233 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004234 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004235 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004236 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4237 {
4238 if (m_public_state.GetValue() == eStateAttaching)
4239 {
4240 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004241 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004242 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4243 }
4244 else
4245 {
4246 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004247 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004248 Halt();
4249 }
4250 continue;
4251 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004252
4253 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4254
4255 if (internal_state != eStateInvalid)
4256 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004257 if (m_clear_thread_plans_on_stop &&
4258 StateIsStoppedState(internal_state, true))
4259 {
4260 m_clear_thread_plans_on_stop = false;
4261 m_thread_list.DiscardThreadPlans();
4262 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004263 HandlePrivateEvent (event_sp);
4264 }
4265
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004266 if (internal_state == eStateInvalid ||
4267 internal_state == eStateExited ||
4268 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004269 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004270 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004271 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004272
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004273 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004274 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004275 }
4276
Caroline Tice20ad3c42010-10-29 21:48:37 +00004277 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004279 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004280
Ed Maste64fad602013-07-29 20:58:06 +00004281 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004282 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4283 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004284 return NULL;
4285}
4286
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004287//------------------------------------------------------------------
4288// Process Event Data
4289//------------------------------------------------------------------
4290
4291Process::ProcessEventData::ProcessEventData () :
4292 EventData (),
4293 m_process_sp (),
4294 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004295 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004296 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004297 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004298{
4299}
4300
4301Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4302 EventData (),
4303 m_process_sp (process_sp),
4304 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004305 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004306 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004307 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004308{
4309}
4310
4311Process::ProcessEventData::~ProcessEventData()
4312{
4313}
4314
4315const ConstString &
4316Process::ProcessEventData::GetFlavorString ()
4317{
4318 static ConstString g_flavor ("Process::ProcessEventData");
4319 return g_flavor;
4320}
4321
4322const ConstString &
4323Process::ProcessEventData::GetFlavor () const
4324{
4325 return ProcessEventData::GetFlavorString ();
4326}
4327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004328void
4329Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4330{
4331 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004332 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4333 // the public event queue, then other times when we're pretending that this is where we stopped at the
4334 // end of expression evaluation. m_update_state is used to distinguish these
4335 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004336 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004337 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004338 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004339
Jim Ingham221d51c2013-05-08 00:35:16 +00004340 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004341
4342 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4343 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004344 {
4345 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004346 uint32_t num_threads = curr_thread_list.GetSize();
4347 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004348
Jim Ingham4b536182011-08-09 02:12:22 +00004349 // The actions might change one of the thread's stop_info's opinions about whether we should
4350 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004351
4352 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4353 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4354 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4355 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back
4356 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004357 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004358 for (idx = 0; idx < num_threads; ++idx)
4359 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4360
Jim Inghamc7078c22012-12-13 22:24:15 +00004361 // Use this to track whether we should continue from here. We will only continue the target running if
4362 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4363 // then it doesn't matter what the other threads say...
4364
4365 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004366
Jim Ingham0ad7e052013-04-25 02:04:59 +00004367 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4368 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4369 // thing to do is, and it's better to let the user decide than continue behind their backs.
4370
4371 bool does_anybody_have_an_opinion = false;
4372
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004373 for (idx = 0; idx < num_threads; ++idx)
4374 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004375 curr_thread_list = m_process_sp->GetThreadList();
4376 if (curr_thread_list.GetSize() != num_threads)
4377 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004378 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004379 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004380 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004381 break;
4382 }
4383
4384 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4385
4386 if (thread_sp->GetIndexID() != thread_index_array[idx])
4387 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004388 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004389 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004390 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004391 idx,
4392 thread_index_array[idx],
4393 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004394 break;
4395 }
4396
Jim Inghamb15bfc72010-10-20 00:39:53 +00004397 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004398 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004399 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004400 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004401 bool this_thread_wants_to_stop;
4402 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004403 {
Jim Ingham0161b492013-02-09 01:29:05 +00004404 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4405 }
4406 else
4407 {
4408 stop_info_sp->PerformAction(event_ptr);
4409 // The stop action might restart the target. If it does, then we want to mark that in the
4410 // event so that whoever is receiving it will know to wait for the running event and reflect
4411 // that state appropriately.
4412 // We also need to stop processing actions, since they aren't expecting the target to be running.
4413
4414 // FIXME: we might have run.
4415 if (stop_info_sp->HasTargetRunSinceMe())
4416 {
4417 SetRestarted (true);
4418 break;
4419 }
4420
4421 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004422 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004423
Jim Inghamc7078c22012-12-13 22:24:15 +00004424 if (still_should_stop == false)
4425 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004426 }
4427 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004428
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004429
Jim Inghama8ca6e22013-05-03 23:04:37 +00004430 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004431 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004432 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004433 {
4434 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004435 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004436 // Use the public resume method here, since this is just
4437 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004438 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004439 }
4440 else
4441 {
4442 // If we didn't restart, run the Stop Hooks here:
4443 // They might also restart the target, so watch for that.
4444 m_process_sp->GetTarget().RunStopHooks();
4445 if (m_process_sp->GetPrivateState() == eStateRunning)
4446 SetRestarted(true);
4447 }
Jim Ingham9575d842011-03-11 03:53:59 +00004448 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004449 }
4450}
4451
4452void
4453Process::ProcessEventData::Dump (Stream *s) const
4454{
4455 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004456 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004457
Greg Clayton8b82f082011-04-12 05:54:46 +00004458 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004459}
4460
4461const Process::ProcessEventData *
4462Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4463{
4464 if (event_ptr)
4465 {
4466 const EventData *event_data = event_ptr->GetData();
4467 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4468 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4469 }
4470 return NULL;
4471}
4472
4473ProcessSP
4474Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4475{
4476 ProcessSP process_sp;
4477 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4478 if (data)
4479 process_sp = data->GetProcessSP();
4480 return process_sp;
4481}
4482
4483StateType
4484Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4485{
4486 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4487 if (data == NULL)
4488 return eStateInvalid;
4489 else
4490 return data->GetState();
4491}
4492
4493bool
4494Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4495{
4496 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4497 if (data == NULL)
4498 return false;
4499 else
4500 return data->GetRestarted();
4501}
4502
4503void
4504Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4505{
4506 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4507 if (data != NULL)
4508 data->SetRestarted(new_value);
4509}
4510
Jim Ingham0161b492013-02-09 01:29:05 +00004511size_t
4512Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4513{
4514 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4515 if (data != NULL)
4516 return data->GetNumRestartedReasons();
4517 else
4518 return 0;
4519}
4520
4521const char *
4522Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4523{
4524 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4525 if (data != NULL)
4526 return data->GetRestartedReasonAtIndex(idx);
4527 else
4528 return NULL;
4529}
4530
4531void
4532Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4533{
4534 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4535 if (data != NULL)
4536 data->AddRestartedReason(reason);
4537}
4538
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004539bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004540Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4541{
4542 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4543 if (data == NULL)
4544 return false;
4545 else
4546 return data->GetInterrupted ();
4547}
4548
4549void
4550Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4551{
4552 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4553 if (data != NULL)
4554 data->SetInterrupted(new_value);
4555}
4556
4557bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004558Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4559{
4560 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4561 if (data)
4562 {
4563 data->SetUpdateStateOnRemoval();
4564 return true;
4565 }
4566 return false;
4567}
4568
Greg Claytond9e416c2012-02-18 05:35:26 +00004569lldb::TargetSP
4570Process::CalculateTarget ()
4571{
4572 return m_target.shared_from_this();
4573}
4574
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004575void
Greg Clayton0603aa92010-10-04 01:05:56 +00004576Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004577{
Greg Claytonc14ee322011-09-22 04:58:26 +00004578 exe_ctx.SetTargetPtr (&m_target);
4579 exe_ctx.SetProcessPtr (this);
4580 exe_ctx.SetThreadPtr(NULL);
4581 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004582}
4583
Greg Claytone996fd32011-03-08 22:40:15 +00004584//uint32_t
4585//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4586//{
4587// return 0;
4588//}
4589//
4590//ArchSpec
4591//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4592//{
4593// return Host::GetArchSpecForExistingProcess (pid);
4594//}
4595//
4596//ArchSpec
4597//Process::GetArchSpecForExistingProcess (const char *process_name)
4598//{
4599// return Host::GetArchSpecForExistingProcess (process_name);
4600//}
4601//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004602void
4603Process::AppendSTDOUT (const char * s, size_t len)
4604{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004605 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004606 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004607 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004608}
4609
4610void
Greg Clayton93e86192011-11-13 04:45:22 +00004611Process::AppendSTDERR (const char * s, size_t len)
4612{
4613 Mutex::Locker locker (m_stdio_communication_mutex);
4614 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004615 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004616}
4617
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004618void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004619Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004620{
4621 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004622 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004623 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4624}
4625
4626size_t
4627Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4628{
4629 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004630 if (m_profile_data.empty())
4631 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004632
4633 std::string &one_profile_data = m_profile_data.front();
4634 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004635 if (bytes_available > 0)
4636 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004637 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004638 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004639 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004640 if (bytes_available > buf_size)
4641 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004642 memcpy(buf, one_profile_data.c_str(), buf_size);
4643 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004644 bytes_available = buf_size;
4645 }
4646 else
4647 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004648 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004649 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004650 }
4651 }
4652 return bytes_available;
4653}
4654
4655
Greg Clayton93e86192011-11-13 04:45:22 +00004656//------------------------------------------------------------------
4657// Process STDIO
4658//------------------------------------------------------------------
4659
4660size_t
4661Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4662{
4663 Mutex::Locker locker(m_stdio_communication_mutex);
4664 size_t bytes_available = m_stdout_data.size();
4665 if (bytes_available > 0)
4666 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004667 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004668 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004669 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004670 if (bytes_available > buf_size)
4671 {
4672 memcpy(buf, m_stdout_data.c_str(), buf_size);
4673 m_stdout_data.erase(0, buf_size);
4674 bytes_available = buf_size;
4675 }
4676 else
4677 {
4678 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4679 m_stdout_data.clear();
4680 }
4681 }
4682 return bytes_available;
4683}
4684
4685
4686size_t
4687Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4688{
4689 Mutex::Locker locker(m_stdio_communication_mutex);
4690 size_t bytes_available = m_stderr_data.size();
4691 if (bytes_available > 0)
4692 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004693 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004694 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004695 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004696 if (bytes_available > buf_size)
4697 {
4698 memcpy(buf, m_stderr_data.c_str(), buf_size);
4699 m_stderr_data.erase(0, buf_size);
4700 bytes_available = buf_size;
4701 }
4702 else
4703 {
4704 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4705 m_stderr_data.clear();
4706 }
4707 }
4708 return bytes_available;
4709}
4710
4711void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004712Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4713{
4714 Process *process = (Process *) baton;
4715 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4716}
4717
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004718void
Greg Clayton44d93782014-01-27 23:43:24 +00004719Process::ResetProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004720{
4721 m_process_input_reader.reset();
4722}
4723
Greg Clayton44d93782014-01-27 23:43:24 +00004724
4725class IOHandlerProcessSTDIO :
4726 public IOHandler
4727{
4728public:
4729 IOHandlerProcessSTDIO (Process *process,
4730 int write_fd) :
4731 IOHandler(process->GetTarget().GetDebugger()),
4732 m_process (process),
4733 m_read_file (),
4734 m_write_file (write_fd, false),
4735 m_pipe_read(),
4736 m_pipe_write()
4737 {
4738 m_read_file.SetDescriptor(GetInputFD(), false);
4739 }
4740
4741 virtual
4742 ~IOHandlerProcessSTDIO ()
4743 {
4744
4745 }
4746
4747 bool
4748 OpenPipes ()
4749 {
4750 if (m_pipe_read.IsValid() && m_pipe_write.IsValid())
4751 return true;
4752
4753 int fds[2];
Deepak Panickal914b8d92014-01-31 18:48:46 +00004754#ifdef _MSC_VER
4755 // pipe is not supported on windows so default to a fail condition
4756 int err = 1;
4757#else
Greg Clayton44d93782014-01-27 23:43:24 +00004758 int err = pipe(fds);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004759#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004760 if (err == 0)
4761 {
4762 m_pipe_read.SetDescriptor(fds[0], true);
4763 m_pipe_write.SetDescriptor(fds[1], true);
4764 return true;
4765 }
4766 return false;
4767 }
4768
4769 void
4770 ClosePipes()
4771 {
4772 m_pipe_read.Close();
4773 m_pipe_write.Close();
4774 }
4775
4776 // Each IOHandler gets to run until it is done. It should read data
4777 // from the "in" and place output into "out" and "err and return
4778 // when done.
4779 virtual void
4780 Run ()
4781 {
4782 if (m_read_file.IsValid() && m_write_file.IsValid())
4783 {
4784 SetIsDone(false);
4785 if (OpenPipes())
4786 {
4787 const int read_fd = m_read_file.GetDescriptor();
4788 const int pipe_read_fd = m_pipe_read.GetDescriptor();
4789 TerminalState terminal_state;
4790 terminal_state.Save (read_fd, false);
4791 Terminal terminal(read_fd);
4792 terminal.SetCanonical(false);
4793 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004794// FD_ZERO, FD_SET are not supported on windows
4795#ifndef _MSC_VER
Greg Clayton44d93782014-01-27 23:43:24 +00004796 while (!GetIsDone())
4797 {
4798 fd_set read_fdset;
4799 FD_ZERO (&read_fdset);
4800 FD_SET (read_fd, &read_fdset);
4801 FD_SET (pipe_read_fd, &read_fdset);
4802 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4803 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4804 if (num_set_fds < 0)
4805 {
4806 const int select_errno = errno;
4807
4808 if (select_errno != EINTR)
4809 SetIsDone(true);
4810 }
4811 else if (num_set_fds > 0)
4812 {
4813 char ch = 0;
4814 size_t n;
4815 if (FD_ISSET (read_fd, &read_fdset))
4816 {
4817 n = 1;
4818 if (m_read_file.Read(&ch, n).Success() && n == 1)
4819 {
4820 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4821 SetIsDone(true);
4822 }
4823 else
4824 SetIsDone(true);
4825 }
4826 if (FD_ISSET (pipe_read_fd, &read_fdset))
4827 {
4828 // Consume the interrupt byte
4829 n = 1;
4830 m_pipe_read.Read (&ch, n);
4831 SetIsDone(true);
4832 }
4833 }
4834 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004835#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004836 terminal_state.Restore();
4837
4838 }
4839 else
4840 SetIsDone(true);
4841 }
4842 else
4843 SetIsDone(true);
4844 }
4845
4846 // Hide any characters that have been displayed so far so async
4847 // output can be displayed. Refresh() will be called after the
4848 // output has been displayed.
4849 virtual void
4850 Hide ()
4851 {
4852
4853 }
4854 // Called when the async output has been received in order to update
4855 // the input reader (refresh the prompt and redisplay any current
4856 // line(s) that are being edited
4857 virtual void
4858 Refresh ()
4859 {
4860
4861 }
4862 virtual void
4863 Interrupt ()
4864 {
4865 size_t n = 1;
4866 char ch = 'q';
4867 m_pipe_write.Write (&ch, n);
4868 }
4869
4870 virtual void
4871 GotEOF()
4872 {
4873
4874 }
4875
4876protected:
4877 Process *m_process;
4878 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4879 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
4880 File m_pipe_read;
4881 File m_pipe_write;
4882
4883};
4884
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004885void
Greg Clayton44d93782014-01-27 23:43:24 +00004886Process::WatchForSTDIN (IOHandler &io_handler)
4887{
4888}
4889
4890void
4891Process::CancelWatchForSTDIN (bool exited)
4892{
4893 if (m_process_input_reader)
4894 {
4895 if (exited)
4896 m_process_input_reader->SetIsDone(true);
4897 m_process_input_reader->Interrupt();
4898 }
4899}
4900
4901void
4902Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004903{
4904 // First set up the Read Thread for reading/handling process I/O
4905
Greg Clayton44d93782014-01-27 23:43:24 +00004906 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004907
4908 if (conn_ap.get())
4909 {
4910 m_stdio_communication.SetConnection (conn_ap.release());
4911 if (m_stdio_communication.IsConnected())
4912 {
4913 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4914 m_stdio_communication.StartReadThread();
4915
4916 // Now read thread is set up, set up input reader.
4917
4918 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004919 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004920 }
4921 }
4922}
4923
4924void
Greg Clayton44d93782014-01-27 23:43:24 +00004925Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004926{
Greg Clayton44d93782014-01-27 23:43:24 +00004927 IOHandlerSP io_handler_sp (m_process_input_reader);
4928 if (io_handler_sp)
4929 {
4930 io_handler_sp->SetIsDone(false);
4931 m_target.GetDebugger().PushIOHandler (io_handler_sp);
4932 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004933}
4934
4935void
Greg Clayton44d93782014-01-27 23:43:24 +00004936Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004937{
Greg Clayton44d93782014-01-27 23:43:24 +00004938 IOHandlerSP io_handler_sp (m_process_input_reader);
4939 if (io_handler_sp)
4940 {
4941 io_handler_sp->Interrupt();
4942 m_target.GetDebugger().PopIOHandler (io_handler_sp);
4943 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004944}
4945
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004946// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004947void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004948Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004949{
Greg Clayton6920b522012-08-22 18:39:03 +00004950 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004951}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004952
Greg Clayton99d0faf2010-11-18 23:32:35 +00004953void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004954Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004955{
Greg Clayton6920b522012-08-22 18:39:03 +00004956 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004957}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004958
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004959ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004960Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004961 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004962 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004963 Stream &errors)
4964{
4965 ExecutionResults return_value = eExecutionSetupError;
4966
Jim Ingham77787032011-01-20 02:03:18 +00004967 if (thread_plan_sp.get() == NULL)
4968 {
4969 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004970 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004971 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004972
4973 if (!thread_plan_sp->ValidatePlan(NULL))
4974 {
4975 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4976 return eExecutionSetupError;
4977 }
4978
Greg Claytonc14ee322011-09-22 04:58:26 +00004979 if (exe_ctx.GetProcessPtr() != this)
4980 {
4981 errors.Printf("RunThreadPlan called on wrong process.");
4982 return eExecutionSetupError;
4983 }
4984
4985 Thread *thread = exe_ctx.GetThreadPtr();
4986 if (thread == NULL)
4987 {
4988 errors.Printf("RunThreadPlan called with invalid thread.");
4989 return eExecutionSetupError;
4990 }
Jim Ingham77787032011-01-20 02:03:18 +00004991
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004992 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4993 // For that to be true the plan can't be private - since private plans suppress themselves in the
4994 // GetCompletedPlan call.
4995
4996 bool orig_plan_private = thread_plan_sp->GetPrivate();
4997 thread_plan_sp->SetPrivate(false);
4998
Jim Ingham444586b2011-01-24 06:34:17 +00004999 if (m_private_state.GetValue() != eStateStopped)
5000 {
5001 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00005002 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005003 }
5004
Jim Ingham66243842011-08-13 00:56:10 +00005005 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005006 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005007 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005008 if (!selected_frame_sp)
5009 {
5010 thread->SetSelectedFrame(0);
5011 selected_frame_sp = thread->GetSelectedFrame();
5012 if (!selected_frame_sp)
5013 {
5014 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
5015 return eExecutionSetupError;
5016 }
5017 }
5018
5019 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005020
5021 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5022 // so we should arrange to reset them as well.
5023
Greg Claytonc14ee322011-09-22 04:58:26 +00005024 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00005025
Jim Ingham66243842011-08-13 00:56:10 +00005026 uint32_t selected_tid;
5027 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005028 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005029 {
5030 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005031 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005032 }
5033 else
5034 {
5035 selected_tid = LLDB_INVALID_THREAD_ID;
5036 }
5037
Jim Ingham372787f2012-04-07 00:00:41 +00005038 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00005039 lldb::StateType old_state;
5040 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005041
Greg Clayton5160ce52013-03-27 23:08:40 +00005042 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00005043 if (Host::GetCurrentThread() == m_private_state_thread)
5044 {
Jim Ingham076b3042012-04-10 01:21:57 +00005045 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5046 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005047 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Ingham076b3042012-04-10 01:21:57 +00005048 // we are fielding public events here.
5049 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005050 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Ingham076b3042012-04-10 01:21:57 +00005051
5052
Jim Ingham372787f2012-04-07 00:00:41 +00005053 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005054
5055 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5056 // returning control here.
5057 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5058 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5059 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5060 // do just what we want.
5061 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5062 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5063 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5064 old_state = m_public_state.GetValue();
5065 m_public_state.SetValueNoLock(eStateStopped);
5066
5067 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005068 StartPrivateStateThread(true);
5069 }
5070
5071 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00005072
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005073 if (options.GetDebug())
5074 {
5075 // In this case, we aren't actually going to run, we just want to stop right away.
5076 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5077 // FIXME: To make this prettier we should invent some stop reason for this, but that
5078 // is only cosmetic, and this functionality is only of use to lldb developers who can
5079 // live with not pretty...
5080 thread->Flush();
5081 return eExecutionStoppedForDebug;
5082 }
5083
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005084 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00005085
Sean Callanana46ec452012-07-11 21:31:24 +00005086 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00005087
Jim Ingham77787032011-01-20 02:03:18 +00005088 {
Sean Callanana46ec452012-07-11 21:31:24 +00005089 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5090 // restored on exit to the function.
5091 //
5092 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5093 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00005094
Sean Callanana46ec452012-07-11 21:31:24 +00005095 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00005096
Jim Inghamf48169b2010-11-30 02:22:11 +00005097 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005098 {
5099 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005100 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005101 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005102 thread->GetIndexID(),
5103 thread->GetID(),
5104 s.GetData());
5105 }
5106
5107 bool got_event;
5108 lldb::EventSP event_sp;
5109 lldb::StateType stop_state = lldb::eStateInvalid;
5110
5111 TimeValue* timeout_ptr = NULL;
5112 TimeValue real_timeout;
5113
Jim Ingham0161b492013-02-09 01:29:05 +00005114 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
Sean Callanana46ec452012-07-11 21:31:24 +00005115 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005116 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005117 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00005118
Jim Ingham0161b492013-02-09 01:29:05 +00005119 // This is just for accounting:
5120 uint32_t num_resumes = 0;
5121
5122 TimeValue one_thread_timeout = TimeValue::Now();
5123 TimeValue final_timeout = one_thread_timeout;
5124
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005125 uint32_t timeout_usec = options.GetTimeoutUsec();
5126 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005127 {
5128 // If we are running all threads then we take half the time to run all threads, bounded by
5129 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005130 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00005131 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
5132 else
5133 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00005134 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00005135 if (computed_timeout > default_one_thread_timeout_usec)
5136 computed_timeout = default_one_thread_timeout_usec;
5137 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
5138 }
5139 final_timeout.OffsetWithMicroSeconds (timeout_usec);
5140 }
5141 else
5142 {
5143 if (timeout_usec != 0)
5144 final_timeout.OffsetWithMicroSeconds(timeout_usec);
5145 }
5146
Jim Ingham1460e4b2014-01-10 23:46:59 +00005147 // This isn't going to work if there are unfetched events on the queue.
5148 // Are there cases where we might want to run the remaining events here, and then try to
5149 // call the function? That's probably being too tricky for our own good.
5150
5151 Event *other_events = listener.PeekAtNextEvent();
5152 if (other_events != NULL)
5153 {
5154 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
5155 return eExecutionSetupError;
5156 }
5157
5158 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5159 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5160 // event coalescing to cause us to lose OUR running event...
5161 ForceNextEventDelivery();
5162
Jim Ingham8559a352012-11-26 23:52:18 +00005163 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5164 // So don't call return anywhere within it.
5165
Sean Callanana46ec452012-07-11 21:31:24 +00005166 while (1)
5167 {
5168 // We usually want to resume the process if we get to the top of the loop.
5169 // The only exception is if we get two running events with no intervening
5170 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005171 if (log)
5172 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5173 do_resume,
5174 handle_running_event,
5175 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00005176
Jim Ingham184e9812013-01-15 02:47:48 +00005177 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005178 {
5179 // Do the initial resume and wait for the running event before going further.
5180
Jim Ingham184e9812013-01-15 02:47:48 +00005181 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005182 {
Jim Ingham0161b492013-02-09 01:29:05 +00005183 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005184 Error resume_error = PrivateResume ();
5185 if (!resume_error.Success())
5186 {
Jim Ingham0161b492013-02-09 01:29:05 +00005187 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5188 num_resumes,
5189 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00005190 return_value = eExecutionSetupError;
5191 break;
5192 }
Sean Callanana46ec452012-07-11 21:31:24 +00005193 }
Sean Callanana46ec452012-07-11 21:31:24 +00005194
Jim Ingham0161b492013-02-09 01:29:05 +00005195 TimeValue resume_timeout = TimeValue::Now();
5196 resume_timeout.OffsetWithMicroSeconds(500000);
5197
5198 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005199 if (!got_event)
5200 {
5201 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005202 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5203 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005204
Jim Ingham0161b492013-02-09 01:29:05 +00005205 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005206 return_value = eExecutionSetupError;
5207 break;
5208 }
5209
5210 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005211
Sean Callanana46ec452012-07-11 21:31:24 +00005212 if (stop_state != eStateRunning)
5213 {
Jim Ingham0161b492013-02-09 01:29:05 +00005214 bool restarted = false;
5215
5216 if (stop_state == eStateStopped)
5217 {
5218 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5219 if (log)
5220 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5221 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5222 num_resumes,
5223 StateAsCString(stop_state),
5224 restarted,
5225 do_resume,
5226 handle_running_event);
5227 }
5228
5229 if (restarted)
5230 {
5231 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5232 // event here. But if I do, the best thing is to Halt and then get out of here.
5233 Halt();
5234 }
5235
Jim Ingham35e1bda2012-10-16 21:41:58 +00005236 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5237 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00005238 return_value = eExecutionSetupError;
5239 break;
5240 }
5241
5242 if (log)
5243 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5244 // We need to call the function synchronously, so spin waiting for it to return.
5245 // If we get interrupted while executing, we're going to lose our context, and
5246 // won't be able to gather the result at this point.
5247 // We set the timeout AFTER the resume, since the resume takes some time and we
5248 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005249 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005250 else
5251 {
Sean Callanana46ec452012-07-11 21:31:24 +00005252 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005253 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005254 }
Jim Ingham0161b492013-02-09 01:29:05 +00005255
5256 if (before_first_timeout)
5257 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005258 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005259 timeout_ptr = &one_thread_timeout;
5260 else
5261 {
5262 if (timeout_usec == 0)
5263 timeout_ptr = NULL;
5264 else
5265 timeout_ptr = &final_timeout;
5266 }
5267 }
5268 else
5269 {
5270 if (timeout_usec == 0)
5271 timeout_ptr = NULL;
5272 else
5273 timeout_ptr = &final_timeout;
5274 }
5275
5276 do_resume = true;
5277 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005278
Sean Callanana46ec452012-07-11 21:31:24 +00005279 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005280 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005281
Jim Ingham0f16e732011-02-08 05:20:59 +00005282 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005283 {
Sean Callanana46ec452012-07-11 21:31:24 +00005284 if (timeout_ptr)
5285 {
Matt Kopec676a4872013-02-21 23:55:31 +00005286 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005287 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5288 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005289 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005290 else
Sean Callanana46ec452012-07-11 21:31:24 +00005291 {
5292 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5293 }
5294 }
5295
5296 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5297
5298 if (got_event)
5299 {
5300 if (event_sp.get())
5301 {
5302 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005303 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005304 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005305 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005306 return_value = eExecutionInterrupted;
5307 errors.Printf ("Execution halted by user interrupt.");
5308 if (log)
5309 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005310 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005311 }
5312 else
5313 {
5314 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5315 if (log)
5316 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5317
5318 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005319 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005320 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005321 {
Jim Ingham0161b492013-02-09 01:29:05 +00005322 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005323 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5324 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005325 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005326 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005327 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005328 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5329 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005330 }
5331 else
5332 {
Jim Ingham0161b492013-02-09 01:29:05 +00005333 // If we were restarted, we just need to go back up to fetch another event.
5334 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005335 {
5336 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005337 {
5338 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5339 }
5340 keep_going = true;
5341 do_resume = false;
5342 handle_running_event = true;
5343
Jim Inghamcfc09352012-07-27 23:57:19 +00005344 }
5345 else
5346 {
Jim Ingham0161b492013-02-09 01:29:05 +00005347
5348 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5349 StopReason stop_reason = eStopReasonInvalid;
5350 if (stop_info_sp)
5351 stop_reason = stop_info_sp->GetStopReason();
5352
5353
5354 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5355 // it is OUR plan that is complete?
5356 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005357 {
5358 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005359 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5360 // Now mark this plan as private so it doesn't get reported as the stop reason
5361 // after this point.
5362 if (thread_plan_sp)
5363 thread_plan_sp->SetPrivate (orig_plan_private);
5364 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005365 }
5366 else
5367 {
Jim Ingham0161b492013-02-09 01:29:05 +00005368 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005369 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005370 {
5371 if (log)
5372 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005373 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005374 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005375 {
5376 event_to_broadcast_sp = event_sp;
5377 }
Jim Ingham0161b492013-02-09 01:29:05 +00005378 }
Jim Ingham184e9812013-01-15 02:47:48 +00005379 else
Jim Ingham0161b492013-02-09 01:29:05 +00005380 {
5381 if (log)
5382 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005383 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005384 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005385 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005386 }
Jim Ingham184e9812013-01-15 02:47:48 +00005387 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005388 }
Sean Callanana46ec452012-07-11 21:31:24 +00005389 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005390 }
5391 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005392
Jim Inghamcfc09352012-07-27 23:57:19 +00005393 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005394 // This shouldn't really happen, but sometimes we do get two running events without an
5395 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005396 do_resume = false;
5397 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005398 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005399 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005400
Jim Inghamcfc09352012-07-27 23:57:19 +00005401 default:
5402 if (log)
5403 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5404
5405 if (stop_state == eStateExited)
5406 event_to_broadcast_sp = event_sp;
5407
Sean Callananbf154da2012-08-08 17:35:10 +00005408 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005409 return_value = eExecutionInterrupted;
5410 break;
5411 }
Sean Callanana46ec452012-07-11 21:31:24 +00005412 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005413
Sean Callanana46ec452012-07-11 21:31:24 +00005414 if (keep_going)
5415 continue;
5416 else
5417 break;
5418 }
5419 else
5420 {
5421 if (log)
5422 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5423 return_value = eExecutionInterrupted;
5424 break;
5425 }
5426 }
5427 else
5428 {
5429 // If we didn't get an event that means we've timed out...
5430 // We will interrupt the process here. Depending on what we were asked to do we will
5431 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005432
5433 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005434 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005435 {
Jim Ingham0161b492013-02-09 01:29:05 +00005436 uint64_t remaining_time = final_timeout - TimeValue::Now();
5437 if (before_first_timeout)
5438 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005439 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005440 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005441 else
5442 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005443 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005444 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005445 }
5446 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005447 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005448 "abandoning execution.",
5449 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005450 }
5451
Jim Ingham0161b492013-02-09 01:29:05 +00005452 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5453 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5454 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5455 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5456 // stopped event. That's what this while loop does.
5457
5458 bool back_to_top = true;
5459 uint32_t try_halt_again = 0;
5460 bool do_halt = true;
5461 const uint32_t num_retries = 5;
5462 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005463 {
Jim Ingham0161b492013-02-09 01:29:05 +00005464 Error halt_error;
5465 if (do_halt)
5466 {
5467 if (log)
5468 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5469 halt_error = Halt();
5470 }
5471 if (halt_error.Success())
5472 {
5473 if (log)
5474 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5475
5476 real_timeout = TimeValue::Now();
5477 real_timeout.OffsetWithMicroSeconds(500000);
5478
5479 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005480
Jim Ingham0161b492013-02-09 01:29:05 +00005481 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005482 {
Jim Ingham0161b492013-02-09 01:29:05 +00005483 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5484 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005485 {
Jim Ingham0161b492013-02-09 01:29:05 +00005486 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5487 if (stop_state == lldb::eStateStopped
5488 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5489 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005490 }
5491
Jim Ingham0161b492013-02-09 01:29:05 +00005492 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005493 {
Jim Ingham0161b492013-02-09 01:29:05 +00005494 // Between the time we initiated the Halt and the time we delivered it, the process could have
5495 // already finished its job. Check that here:
5496
5497 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5498 {
5499 if (log)
5500 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5501 "Exiting wait loop.");
5502 return_value = eExecutionCompleted;
5503 back_to_top = false;
5504 break;
5505 }
5506
5507 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5508 {
5509 if (log)
5510 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5511 "Exiting wait loop.");
5512 try_halt_again++;
5513 do_halt = false;
5514 continue;
5515 }
Sean Callanana46ec452012-07-11 21:31:24 +00005516
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005517 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005518 {
5519 if (log)
5520 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5521 return_value = eExecutionInterrupted;
5522 back_to_top = false;
5523 break;
5524 }
5525
5526 if (before_first_timeout)
5527 {
5528 // Set all the other threads to run, and return to the top of the loop, which will continue;
5529 before_first_timeout = false;
5530 thread_plan_sp->SetStopOthers (false);
5531 if (log)
5532 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005533
Jim Ingham0161b492013-02-09 01:29:05 +00005534 back_to_top = true;
5535 break;
5536 }
5537 else
5538 {
5539 // Running all threads failed, so return Interrupted.
5540 if (log)
5541 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5542 return_value = eExecutionInterrupted;
5543 back_to_top = false;
5544 break;
5545 }
Sean Callanana46ec452012-07-11 21:31:24 +00005546 }
5547 }
5548 else
Jim Ingham0161b492013-02-09 01:29:05 +00005549 { if (log)
5550 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5551 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005552 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005553 back_to_top = false;
5554 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005555 }
5556 }
Jim Ingham0161b492013-02-09 01:29:05 +00005557 else
5558 {
5559 try_halt_again++;
5560 continue;
5561 }
Sean Callanana46ec452012-07-11 21:31:24 +00005562 }
Jim Ingham0161b492013-02-09 01:29:05 +00005563
5564 if (!back_to_top || try_halt_again > num_retries)
5565 break;
5566 else
5567 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005568 }
Sean Callanana46ec452012-07-11 21:31:24 +00005569 } // END WAIT LOOP
5570
5571 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5572 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5573 {
5574 StopPrivateStateThread();
5575 Error error;
5576 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005577 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005578 {
5579 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5580 }
5581 m_public_state.SetValueNoLock(old_state);
5582
5583 }
5584
Jim Ingham184e9812013-01-15 02:47:48 +00005585 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5586 // could happen:
5587 // 1) The execution successfully completed
5588 // 2) We hit a breakpoint, and ignore_breakpoints was true
5589 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005590 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5591 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005592
Jim Ingham184e9812013-01-15 02:47:48 +00005593 if (return_value == eExecutionCompleted
5594 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005595 {
5596 thread_plan_sp->RestoreThreadState();
5597 }
Sean Callanana46ec452012-07-11 21:31:24 +00005598
5599 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005600 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005601 {
5602 if (log)
5603 {
5604 StreamString s;
5605 if (event_sp)
5606 event_sp->Dump (&s);
5607 else
5608 {
5609 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5610 }
5611
5612 StreamString ts;
5613
5614 const char *event_explanation = NULL;
5615
5616 do
5617 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005618 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005619 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005620 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005621 break;
5622 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005623 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005624 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005625 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005626 break;
5627 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005628 else
Sean Callanana46ec452012-07-11 21:31:24 +00005629 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005630 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5631
5632 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005633 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005634 event_explanation = "<no event data>";
5635 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005636 }
5637
Jim Inghamcfc09352012-07-27 23:57:19 +00005638 Process *process = event_data->GetProcessSP().get();
5639
5640 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005641 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005642 event_explanation = "<no process>";
5643 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005644 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005645
5646 ThreadList &thread_list = process->GetThreadList();
5647
5648 uint32_t num_threads = thread_list.GetSize();
5649 uint32_t thread_index;
5650
5651 ts.Printf("<%u threads> ", num_threads);
5652
5653 for (thread_index = 0;
5654 thread_index < num_threads;
5655 ++thread_index)
5656 {
5657 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5658
5659 if (!thread)
5660 {
5661 ts.Printf("<?> ");
5662 continue;
5663 }
5664
Daniel Malead01b2952012-11-29 21:49:15 +00005665 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005666 RegisterContext *register_context = thread->GetRegisterContext().get();
5667
5668 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005669 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005670 else
5671 ts.Printf("[ip unknown] ");
5672
5673 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5674 if (stop_info_sp)
5675 {
5676 const char *stop_desc = stop_info_sp->GetDescription();
5677 if (stop_desc)
5678 ts.PutCString (stop_desc);
5679 }
5680 ts.Printf(">");
5681 }
5682
5683 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005684 }
Sean Callanana46ec452012-07-11 21:31:24 +00005685 } while (0);
5686
Jim Inghamcfc09352012-07-27 23:57:19 +00005687 if (event_explanation)
5688 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005689 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005690 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5691 }
5692
Jim Inghame4483cf2013-09-27 01:13:01 +00005693 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005694 {
5695 if (log)
5696 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5697 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5698 thread_plan_sp->SetPrivate (orig_plan_private);
5699 }
5700 else
5701 {
5702 if (log)
5703 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005704 }
5705 }
5706 else if (return_value == eExecutionSetupError)
5707 {
5708 if (log)
5709 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005710
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005711 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005712 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005713 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005714 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005715 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005716 }
5717 else
5718 {
Sean Callanana46ec452012-07-11 21:31:24 +00005719 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005720 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005721 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005722 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5723 return_value = eExecutionCompleted;
5724 }
5725 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5726 {
5727 if (log)
5728 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5729 return_value = eExecutionDiscarded;
5730 }
5731 else
5732 {
5733 if (log)
5734 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005735 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005736 {
5737 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005738 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005739 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5740 thread_plan_sp->SetPrivate (orig_plan_private);
5741 }
5742 }
5743 }
5744
5745 // Thread we ran the function in may have gone away because we ran the target
5746 // Check that it's still there, and if it is put it back in the context. Also restore the
5747 // frame in the context if it is still present.
5748 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5749 if (thread)
5750 {
5751 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5752 }
5753
5754 // Also restore the current process'es selected frame & thread, since this function calling may
5755 // be done behind the user's back.
5756
5757 if (selected_tid != LLDB_INVALID_THREAD_ID)
5758 {
5759 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5760 {
5761 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005762 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005763 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005764 if (old_frame_sp)
5765 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005766 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005767 }
5768 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005769
Sean Callanana46ec452012-07-11 21:31:24 +00005770 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005771
Sean Callanana46ec452012-07-11 21:31:24 +00005772 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005773 {
Sean Callanana46ec452012-07-11 21:31:24 +00005774 if (log)
5775 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5776 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005777 }
5778
5779 return return_value;
5780}
5781
5782const char *
5783Process::ExecutionResultAsCString (ExecutionResults result)
5784{
5785 const char *result_name;
5786
5787 switch (result)
5788 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005789 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005790 result_name = "eExecutionCompleted";
5791 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005792 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005793 result_name = "eExecutionDiscarded";
5794 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005795 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005796 result_name = "eExecutionInterrupted";
5797 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005798 case eExecutionHitBreakpoint:
5799 result_name = "eExecutionHitBreakpoint";
5800 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005801 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005802 result_name = "eExecutionSetupError";
5803 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005804 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005805 result_name = "eExecutionTimedOut";
5806 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005807 case eExecutionStoppedForDebug:
5808 result_name = "eExecutionStoppedForDebug";
5809 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005810 }
5811 return result_name;
5812}
5813
Greg Clayton7260f622011-04-18 08:33:37 +00005814void
5815Process::GetStatus (Stream &strm)
5816{
5817 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005818 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005819 {
5820 if (state == eStateExited)
5821 {
5822 int exit_status = GetExitStatus();
5823 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005824 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005825 GetID(),
5826 exit_status,
5827 exit_status,
5828 exit_description ? exit_description : "");
5829 }
5830 else
5831 {
5832 if (state == eStateConnected)
5833 strm.Printf ("Connected to remote target.\n");
5834 else
Daniel Malead01b2952012-11-29 21:49:15 +00005835 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005836 }
5837 }
5838 else
5839 {
Daniel Malead01b2952012-11-29 21:49:15 +00005840 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005841 }
5842}
5843
5844size_t
5845Process::GetThreadStatus (Stream &strm,
5846 bool only_threads_with_stop_reason,
5847 uint32_t start_frame,
5848 uint32_t num_frames,
5849 uint32_t num_frames_with_source)
5850{
5851 size_t num_thread_infos_dumped = 0;
5852
Jim Ingham41f2b942012-09-10 20:50:15 +00005853 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005854 const size_t num_threads = GetThreadList().GetSize();
5855 for (uint32_t i = 0; i < num_threads; i++)
5856 {
5857 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5858 if (thread)
5859 {
5860 if (only_threads_with_stop_reason)
5861 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005862 StopInfoSP stop_info_sp = thread->GetStopInfo();
5863 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005864 continue;
5865 }
5866 thread->GetStatus (strm,
5867 start_frame,
5868 num_frames,
5869 num_frames_with_source);
5870 ++num_thread_infos_dumped;
5871 }
5872 }
5873 return num_thread_infos_dumped;
5874}
5875
Greg Claytona9f40ad2012-02-22 04:37:26 +00005876void
5877Process::AddInvalidMemoryRegion (const LoadRange &region)
5878{
5879 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5880}
5881
5882bool
5883Process::RemoveInvalidMemoryRange (const LoadRange &region)
5884{
5885 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5886}
5887
Jim Ingham372787f2012-04-07 00:00:41 +00005888void
5889Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5890{
5891 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5892}
5893
5894bool
5895Process::RunPreResumeActions ()
5896{
5897 bool result = true;
5898 while (!m_pre_resume_actions.empty())
5899 {
5900 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5901 m_pre_resume_actions.pop_back();
5902 bool this_result = action.callback (action.baton);
5903 if (result == true) result = this_result;
5904 }
5905 return result;
5906}
5907
5908void
5909Process::ClearPreResumeActions ()
5910{
5911 m_pre_resume_actions.clear();
5912}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005913
Greg Claytonfa559e52012-05-18 02:38:05 +00005914void
5915Process::Flush ()
5916{
5917 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005918 m_extended_thread_list.Flush();
5919 m_extended_thread_stop_id = 0;
5920 m_queue_list.Clear();
5921 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005922}
Greg Clayton90ba8112012-12-05 00:16:59 +00005923
5924void
5925Process::DidExec ()
5926{
5927 Target &target = GetTarget();
5928 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005929 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005930 m_dynamic_checkers_ap.reset();
5931 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005932 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005933 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005934 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005935 m_image_tokens.clear();
5936 m_allocated_memory_cache.Clear();
5937 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005938 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005939 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005940 DoDidExec();
5941 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005942 // Flush the process (threads and all stack frames) after running CompleteAttach()
5943 // in case the dynamic loader loaded things in new locations.
5944 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005945
5946 // After we figure out what was loaded/unloaded in CompleteAttach,
5947 // we need to let the target know so it can do any cleanup it needs to.
5948 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005949}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005950
Jim Ingham1460e4b2014-01-10 23:46:59 +00005951addr_t
5952Process::ResolveIndirectFunction(const Address *address, Error &error)
5953{
5954 if (address == nullptr)
5955 {
5956 Symbol *symbol = address->CalculateSymbolContextSymbol();
5957 error.SetErrorStringWithFormat("unable to determine direct function call for indirect function %s",
5958 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5959 return LLDB_INVALID_ADDRESS;
5960 }
5961
5962 addr_t function_addr = LLDB_INVALID_ADDRESS;
5963
5964 addr_t addr = address->GetLoadAddress(&GetTarget());
5965 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5966 if (iter != m_resolved_indirect_addresses.end())
5967 {
5968 function_addr = (*iter).second;
5969 }
5970 else
5971 {
5972 if (!InferiorCall(this, address, function_addr))
5973 {
5974 Symbol *symbol = address->CalculateSymbolContextSymbol();
5975 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5976 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5977 function_addr = LLDB_INVALID_ADDRESS;
5978 }
5979 else
5980 {
5981 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5982 }
5983 }
5984 return function_addr;
5985}
5986