blob: c7bd0438b08a463b88a2568150f6b9975c270e52 [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),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001023 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024 m_exit_status (-1),
1025 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001026 m_thread_mutex (Mutex::eMutexTypeRecursive),
1027 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +00001029 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +00001030 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001031 m_queue_list (this),
1032 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001034 m_image_tokens (),
1035 m_listener (listener),
1036 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001037 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001038 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001039 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001040 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001041 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001042 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001043 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001044 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001045 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1046 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001047 m_memory_cache (*this),
1048 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001049 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001050 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001051 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001052 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001053 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001054 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001055 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +00001056 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +00001057 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001058 m_destroy_in_process (false),
1059 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001060{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001061 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001062
Greg Clayton5160ce52013-03-27 23:08:40 +00001063 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001064 if (log)
1065 log->Printf ("%p Process::Process()", this);
1066
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001067 SetEventName (eBroadcastBitStateChanged, "state-changed");
1068 SetEventName (eBroadcastBitInterrupt, "interrupt");
1069 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1070 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001071 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001072
Greg Clayton35a4cc52012-10-29 20:52:08 +00001073 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1074 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1075 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1076
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077 listener.StartListeningForEvents (this,
1078 eBroadcastBitStateChanged |
1079 eBroadcastBitInterrupt |
1080 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001081 eBroadcastBitSTDERR |
1082 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083
1084 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001085 eBroadcastBitStateChanged |
1086 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087
1088 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1089 eBroadcastInternalStateControlStop |
1090 eBroadcastInternalStateControlPause |
1091 eBroadcastInternalStateControlResume);
1092}
1093
1094//----------------------------------------------------------------------
1095// Destructor
1096//----------------------------------------------------------------------
1097Process::~Process()
1098{
Greg Clayton5160ce52013-03-27 23:08:40 +00001099 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 if (log)
1101 log->Printf ("%p Process::~Process()", this);
1102 StopPrivateStateThread();
1103}
1104
Greg Clayton67cc0632012-08-22 17:17:09 +00001105const ProcessPropertiesSP &
1106Process::GetGlobalProperties()
1107{
1108 static ProcessPropertiesSP g_settings_sp;
1109 if (!g_settings_sp)
1110 g_settings_sp.reset (new ProcessProperties (true));
1111 return g_settings_sp;
1112}
1113
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114void
1115Process::Finalize()
1116{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001117 switch (GetPrivateState())
1118 {
1119 case eStateConnected:
1120 case eStateAttaching:
1121 case eStateLaunching:
1122 case eStateStopped:
1123 case eStateRunning:
1124 case eStateStepping:
1125 case eStateCrashed:
1126 case eStateSuspended:
1127 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001128 {
1129 // FIXME: This will have to be a process setting:
1130 bool keep_stopped = false;
1131 Detach(keep_stopped);
1132 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001133 else
1134 Destroy();
1135 break;
1136
1137 case eStateInvalid:
1138 case eStateUnloaded:
1139 case eStateDetached:
1140 case eStateExited:
1141 break;
1142 }
1143
Greg Clayton1ed54f52011-10-01 00:45:15 +00001144 // Clear our broadcaster before we proceed with destroying
1145 Broadcaster::Clear();
1146
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147 // Do any cleanup needed prior to being destructed... Subclasses
1148 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001149
1150 // We need to destroy the loader before the derived Process class gets destroyed
1151 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001152 m_dynamic_checkers_ap.reset();
1153 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001154 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00001155 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001156 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001157 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001158 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +00001159 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001160 m_queue_list.Clear();
1161 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +00001162 std::vector<Notifications> empty_notifications;
1163 m_notifications.swap(empty_notifications);
1164 m_image_tokens.clear();
1165 m_memory_cache.Clear();
1166 m_allocated_memory_cache.Clear();
1167 m_language_runtimes.clear();
1168 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001169//#ifdef LLDB_CONFIGURATION_DEBUG
1170// StreamFile s(stdout, false);
1171// EventSP event_sp;
1172// while (m_private_state_listener.GetNextEvent(event_sp))
1173// {
1174// event_sp->Dump (&s);
1175// s.EOL();
1176// }
1177//#endif
1178 // We have to be very careful here as the m_private_state_listener might
1179 // contain events that have ProcessSP values in them which can keep this
1180 // process around forever. These events need to be cleared out.
1181 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001182 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1183 m_public_run_lock.SetStopped();
1184 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1185 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001186 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187}
1188
1189void
1190Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1191{
1192 m_notifications.push_back(callbacks);
1193 if (callbacks.initialize != NULL)
1194 callbacks.initialize (callbacks.baton, this);
1195}
1196
1197bool
1198Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1199{
1200 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1201 for (pos = m_notifications.begin(); pos != end; ++pos)
1202 {
1203 if (pos->baton == callbacks.baton &&
1204 pos->initialize == callbacks.initialize &&
1205 pos->process_state_changed == callbacks.process_state_changed)
1206 {
1207 m_notifications.erase(pos);
1208 return true;
1209 }
1210 }
1211 return false;
1212}
1213
1214void
1215Process::SynchronouslyNotifyStateChanged (StateType state)
1216{
1217 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1218 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1219 {
1220 if (notification_pos->process_state_changed)
1221 notification_pos->process_state_changed (notification_pos->baton, this, state);
1222 }
1223}
1224
1225// FIXME: We need to do some work on events before the general Listener sees them.
1226// For instance if we are continuing from a breakpoint, we need to ensure that we do
1227// the little "insert real insn, step & stop" trick. But we can't do that when the
1228// event is delivered by the broadcaster - since that is done on the thread that is
1229// waiting for new events, so if we needed more than one event for our handling, we would
1230// stall. So instead we do it when we fetch the event off of the queue.
1231//
1232
1233StateType
1234Process::GetNextEvent (EventSP &event_sp)
1235{
1236 StateType state = eStateInvalid;
1237
1238 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1239 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1240
1241 return state;
1242}
1243
1244
1245StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001246Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001247{
Jim Ingham4b536182011-08-09 02:12:22 +00001248 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1249 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1250 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001251 if (event_sp_ptr)
1252 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001253 StateType state = GetState();
1254 // If we are exited or detached, we won't ever get back to any
1255 // other valid state...
1256 if (state == eStateDetached || state == eStateExited)
1257 return state;
1258
Daniel Malea9e9919f2013-10-09 16:56:28 +00001259 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1260 if (log)
1261 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1262
1263 if (!wait_always &&
1264 StateIsStoppedState(state, true) &&
1265 StateIsStoppedState(GetPrivateState(), true)) {
1266 if (log)
1267 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1268 __FUNCTION__);
1269 return state;
1270 }
1271
Jim Ingham4b536182011-08-09 02:12:22 +00001272 while (state != eStateInvalid)
1273 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001274 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001275 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001276 if (event_sp_ptr && event_sp)
1277 *event_sp_ptr = event_sp;
1278
Jim Ingham4b536182011-08-09 02:12:22 +00001279 switch (state)
1280 {
1281 case eStateCrashed:
1282 case eStateDetached:
1283 case eStateExited:
1284 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001285 // We need to toggle the run lock as this won't get done in
1286 // SetPublicState() if the process is hijacked.
1287 if (hijack_listener)
1288 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001289 return state;
1290 case eStateStopped:
1291 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1292 continue;
1293 else
Greg Clayton44d93782014-01-27 23:43:24 +00001294 {
1295 // We need to toggle the run lock as this won't get done in
1296 // SetPublicState() if the process is hijacked.
1297 if (hijack_listener)
1298 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001299 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001300 }
Jim Ingham4b536182011-08-09 02:12:22 +00001301 default:
1302 continue;
1303 }
1304 }
1305 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001306}
1307
1308
1309StateType
1310Process::WaitForState
1311(
1312 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001313 const StateType *match_states,
1314 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315)
1316{
1317 EventSP event_sp;
1318 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001319 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 while (state != eStateInvalid)
1321 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001322 // If we are exited or detached, we won't ever get back to any
1323 // other valid state...
1324 if (state == eStateDetached || state == eStateExited)
1325 return state;
1326
Greg Clayton44d93782014-01-27 23:43:24 +00001327 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328
1329 for (i=0; i<num_match_states; ++i)
1330 {
1331 if (match_states[i] == state)
1332 return state;
1333 }
1334 }
1335 return state;
1336}
1337
Jim Ingham30f9b212010-10-11 23:53:14 +00001338bool
1339Process::HijackProcessEvents (Listener *listener)
1340{
1341 if (listener != NULL)
1342 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001343 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001344 }
1345 else
1346 return false;
1347}
1348
1349void
1350Process::RestoreProcessEvents ()
1351{
1352 RestoreBroadcaster();
1353}
1354
Jim Ingham0f16e732011-02-08 05:20:59 +00001355bool
1356Process::HijackPrivateProcessEvents (Listener *listener)
1357{
1358 if (listener != NULL)
1359 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001360 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001361 }
1362 else
1363 return false;
1364}
1365
1366void
1367Process::RestorePrivateProcessEvents ()
1368{
1369 m_private_state_broadcaster.RestoreBroadcaster();
1370}
1371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001373Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374{
Greg Clayton5160ce52013-03-27 23:08:40 +00001375 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376
1377 if (log)
1378 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1379
Greg Clayton44d93782014-01-27 23:43:24 +00001380 Listener *listener = hijack_listener;
1381 if (listener == NULL)
1382 listener = &m_listener;
1383
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001385 if (listener->WaitForEventForBroadcasterWithType (timeout,
1386 this,
1387 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1388 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001389 {
1390 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1391 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1392 else if (log)
1393 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1394 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395
1396 if (log)
1397 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1398 __FUNCTION__,
1399 timeout,
1400 StateAsCString(state));
1401 return state;
1402}
1403
1404Event *
1405Process::PeekAtStateChangedEvents ()
1406{
Greg Clayton5160ce52013-03-27 23:08:40 +00001407 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001408
1409 if (log)
1410 log->Printf ("Process::%s...", __FUNCTION__);
1411
1412 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001413 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1414 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415 if (log)
1416 {
1417 if (event_ptr)
1418 {
1419 log->Printf ("Process::%s (event_ptr) => %s",
1420 __FUNCTION__,
1421 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1422 }
1423 else
1424 {
1425 log->Printf ("Process::%s no events found",
1426 __FUNCTION__);
1427 }
1428 }
1429 return event_ptr;
1430}
1431
1432StateType
1433Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1434{
Greg Clayton5160ce52013-03-27 23:08:40 +00001435 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001436
1437 if (log)
1438 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1439
1440 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001441 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1442 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001443 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001444 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001445 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1446 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001447
1448 // This is a bit of a hack, but when we wait here we could very well return
1449 // to the command-line, and that could disable the log, which would render the
1450 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001451 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001452 {
1453 if (state == eStateInvalid)
1454 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1455 else
1456 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1457 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458 return state;
1459}
1460
1461bool
1462Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1463{
Greg Clayton5160ce52013-03-27 23:08:40 +00001464 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465
1466 if (log)
1467 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1468
1469 if (control_only)
1470 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1471 else
1472 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1473}
1474
1475bool
1476Process::IsRunning () const
1477{
1478 return StateIsRunningState (m_public_state.GetValue());
1479}
1480
1481int
1482Process::GetExitStatus ()
1483{
1484 if (m_public_state.GetValue() == eStateExited)
1485 return m_exit_status;
1486 return -1;
1487}
1488
Greg Clayton85851dd2010-12-04 00:10:17 +00001489
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490const char *
1491Process::GetExitDescription ()
1492{
1493 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1494 return m_exit_string.c_str();
1495 return NULL;
1496}
1497
Greg Clayton6779606a2011-01-22 23:43:18 +00001498bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499Process::SetExitStatus (int status, const char *cstr)
1500{
Greg Clayton5160ce52013-03-27 23:08:40 +00001501 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001502 if (log)
1503 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1504 status, status,
1505 cstr ? "\"" : "",
1506 cstr ? cstr : "NULL",
1507 cstr ? "\"" : "");
1508
Greg Clayton6779606a2011-01-22 23:43:18 +00001509 // We were already in the exited state
1510 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001511 {
Greg Clayton385d6032011-01-26 23:47:29 +00001512 if (log)
1513 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001514 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001515 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001516
1517 m_exit_status = status;
1518 if (cstr)
1519 m_exit_string = cstr;
1520 else
1521 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001522
Greg Clayton6779606a2011-01-22 23:43:18 +00001523 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001524
Greg Clayton6779606a2011-01-22 23:43:18 +00001525 SetPrivateState (eStateExited);
1526 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527}
1528
1529// This static callback can be used to watch for local child processes on
1530// the current host. The the child process exits, the process will be
1531// found in the global target list (we want to be completely sure that the
1532// lldb_private::Process doesn't go away before we can deliver the signal.
1533bool
Greg Claytone4e45922011-11-16 05:37:56 +00001534Process::SetProcessExitStatus (void *callback_baton,
1535 lldb::pid_t pid,
1536 bool exited,
1537 int signo, // Zero for no signal
1538 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001539)
1540{
Greg Clayton5160ce52013-03-27 23:08:40 +00001541 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001542 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001543 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001544 callback_baton,
1545 pid,
1546 exited,
1547 signo,
1548 exit_status);
1549
1550 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001551 {
Greg Clayton66111032010-06-23 01:19:29 +00001552 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001553 if (target_sp)
1554 {
1555 ProcessSP process_sp (target_sp->GetProcessSP());
1556 if (process_sp)
1557 {
1558 const char *signal_cstr = NULL;
1559 if (signo)
1560 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1561
1562 process_sp->SetExitStatus (exit_status, signal_cstr);
1563 }
1564 }
1565 return true;
1566 }
1567 return false;
1568}
1569
1570
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001571void
1572Process::UpdateThreadListIfNeeded ()
1573{
1574 const uint32_t stop_id = GetStopID();
1575 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1576 {
Greg Clayton2637f822011-11-17 01:23:07 +00001577 const StateType state = GetPrivateState();
1578 if (StateIsStoppedState (state, true))
1579 {
1580 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001581 // m_thread_list does have its own mutex, but we need to
1582 // hold onto the mutex between the call to UpdateThreadList(...)
1583 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001584 ThreadList &old_thread_list = m_thread_list;
1585 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001586 ThreadList new_thread_list(this);
1587 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001588 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001589 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001590 {
Jim Ingham09437922013-03-01 20:04:25 +00001591 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1592 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1593 // shutting us down, causing a deadlock.
1594 if (!m_destroy_in_process)
1595 {
1596 OperatingSystem *os = GetOperatingSystem ();
1597 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001598 {
1599 // Clear any old backing threads where memory threads might have been
1600 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001601 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001602 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001603 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001604
1605 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001606 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1607 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1608 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 +00001609 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001610 else
1611 {
1612 // No OS plug-in, the new thread list is the same as the real thread list
1613 new_thread_list = real_thread_list;
1614 }
Jim Ingham09437922013-03-01 20:04:25 +00001615 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001616
1617 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001618 m_thread_list.Update (new_thread_list);
1619 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001620
Jason Molenda4ff13262013-11-20 00:31:38 +00001621 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1622 {
1623 // Clear any extended threads that we may have accumulated previously
1624 m_extended_thread_list.Clear();
1625 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001626
1627 m_queue_list.Clear();
1628 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001629 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001630 }
Greg Clayton2637f822011-11-17 01:23:07 +00001631 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001632 }
1633}
1634
Jason Molenda5e8dce42013-12-13 00:29:16 +00001635void
1636Process::UpdateQueueListIfNeeded ()
1637{
1638 if (m_system_runtime_ap.get())
1639 {
1640 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1641 {
1642 const StateType state = GetPrivateState();
1643 if (StateIsStoppedState (state, true))
1644 {
1645 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1646 m_queue_list_stop_id = GetLastNaturalStopID();
1647 }
1648 }
1649 }
1650}
1651
Greg Claytona4d87472013-01-18 23:41:08 +00001652ThreadSP
1653Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1654{
1655 OperatingSystem *os = GetOperatingSystem ();
1656 if (os)
1657 return os->CreateThread(tid, context);
1658 return ThreadSP();
1659}
1660
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001661uint32_t
1662Process::GetNextThreadIndexID (uint64_t thread_id)
1663{
1664 return AssignIndexIDToThread(thread_id);
1665}
1666
1667bool
1668Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1669{
1670 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1671 if (iterator == m_thread_id_to_index_id_map.end())
1672 {
1673 return false;
1674 }
1675 else
1676 {
1677 return true;
1678 }
1679}
1680
1681uint32_t
1682Process::AssignIndexIDToThread(uint64_t thread_id)
1683{
1684 uint32_t result = 0;
1685 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1686 if (iterator == m_thread_id_to_index_id_map.end())
1687 {
1688 result = ++m_thread_index_id;
1689 m_thread_id_to_index_id_map[thread_id] = result;
1690 }
1691 else
1692 {
1693 result = iterator->second;
1694 }
1695
1696 return result;
1697}
1698
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001699StateType
1700Process::GetState()
1701{
1702 // If any other threads access this we will need a mutex for it
1703 return m_public_state.GetValue ();
1704}
1705
1706void
Jim Ingham221d51c2013-05-08 00:35:16 +00001707Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001708{
Greg Clayton5160ce52013-03-27 23:08:40 +00001709 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001711 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001712 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001714
1715 // On the transition from Run to Stopped, we unlock the writer end of the
1716 // run lock. The lock gets locked in Resume, which is the public API
1717 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001718 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1719 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001720 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001721 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001722 if (log)
1723 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001724 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001725 }
1726 else
1727 {
1728 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1729 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001730 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001731 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001732 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001733 {
1734 if (log)
1735 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001736 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001737 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001738 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001739 }
1740 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741}
1742
Jim Ingham3b8285d2012-04-19 01:40:33 +00001743Error
1744Process::Resume ()
1745{
Greg Clayton5160ce52013-03-27 23:08:40 +00001746 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001747 if (log)
1748 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001749 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001750 {
1751 Error error("Resume request failed - process still running.");
1752 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001753 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001754 return error;
1755 }
1756 return PrivateResume();
1757}
1758
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759StateType
1760Process::GetPrivateState ()
1761{
1762 return m_private_state.GetValue();
1763}
1764
1765void
1766Process::SetPrivateState (StateType new_state)
1767{
Greg Clayton5160ce52013-03-27 23:08:40 +00001768 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 bool state_changed = false;
1770
1771 if (log)
1772 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1773
Andrew Kaylor29d65742013-05-10 17:19:04 +00001774 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775 Mutex::Locker locker(m_private_state.GetMutex());
1776
1777 const StateType old_state = m_private_state.GetValueNoLock ();
1778 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001779
Greg Claytonaa49c832013-05-03 22:25:56 +00001780 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1781 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1782 if (old_state_is_stopped != new_state_is_stopped)
1783 {
1784 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001785 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001786 else
Ed Maste64fad602013-07-29 20:58:06 +00001787 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001788 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790 if (state_changed)
1791 {
1792 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001793 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001795 // Note, this currently assumes that all threads in the list
1796 // stop when the process stops. In the future we will want to
1797 // support a debugging model where some threads continue to run
1798 // while others are stopped. When that happens we will either need
1799 // a way for the thread list to identify which threads are stopping
1800 // or create a special thread list containing only threads which
1801 // actually stopped.
1802 //
1803 // The process plugin is responsible for managing the actual
1804 // behavior of the threads and should have stopped any threads
1805 // that are going to stop before we get here.
1806 m_thread_list.DidStop();
1807
Jim Ingham4b536182011-08-09 02:12:22 +00001808 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001809 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001810 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001811 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 }
1813 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001814 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1815 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1816 else
1817 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818 }
1819 else
1820 {
1821 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001822 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 }
1824}
1825
Jim Ingham0faa43f2011-11-08 03:00:11 +00001826void
1827Process::SetRunningUserExpression (bool on)
1828{
1829 m_mod_id.SetRunningUserExpression (on);
1830}
1831
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832addr_t
1833Process::GetImageInfoAddress()
1834{
1835 return LLDB_INVALID_ADDRESS;
1836}
1837
Greg Clayton8f343b02010-11-04 01:54:29 +00001838//----------------------------------------------------------------------
1839// LoadImage
1840//
1841// This function provides a default implementation that works for most
1842// unix variants. Any Process subclasses that need to do shared library
1843// loading differently should override LoadImage and UnloadImage and
1844// do what is needed.
1845//----------------------------------------------------------------------
1846uint32_t
1847Process::LoadImage (const FileSpec &image_spec, Error &error)
1848{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001849 char path[PATH_MAX];
1850 image_spec.GetPath(path, sizeof(path));
1851
Greg Clayton8f343b02010-11-04 01:54:29 +00001852 DynamicLoader *loader = GetDynamicLoader();
1853 if (loader)
1854 {
1855 error = loader->CanLoadImage();
1856 if (error.Fail())
1857 return LLDB_INVALID_IMAGE_TOKEN;
1858 }
1859
1860 if (error.Success())
1861 {
1862 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001863
1864 if (thread_sp)
1865 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001866 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001867
1868 if (frame_sp)
1869 {
1870 ExecutionContext exe_ctx;
1871 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001872 EvaluateExpressionOptions expr_options;
1873 expr_options.SetUnwindOnError(true);
1874 expr_options.SetIgnoreBreakpoints(true);
1875 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001876 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001877 expr.Printf("dlopen (\"%s\", 2)", path);
1878 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001879 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001880 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001881 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001882 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001883 expr.GetData(),
1884 prefix,
1885 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001886 expr_error);
1887 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001888 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001889 error = result_valobj_sp->GetError();
1890 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001891 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001892 Scalar scalar;
1893 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001894 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001895 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1896 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1897 {
1898 uint32_t image_token = m_image_tokens.size();
1899 m_image_tokens.push_back (image_ptr);
1900 return image_token;
1901 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001902 }
1903 }
1904 }
1905 }
1906 }
1907 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001908 if (!error.AsCString())
1909 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001910 return LLDB_INVALID_IMAGE_TOKEN;
1911}
1912
1913//----------------------------------------------------------------------
1914// UnloadImage
1915//
1916// This function provides a default implementation that works for most
1917// unix variants. Any Process subclasses that need to do shared library
1918// loading differently should override LoadImage and UnloadImage and
1919// do what is needed.
1920//----------------------------------------------------------------------
1921Error
1922Process::UnloadImage (uint32_t image_token)
1923{
1924 Error error;
1925 if (image_token < m_image_tokens.size())
1926 {
1927 const addr_t image_addr = m_image_tokens[image_token];
1928 if (image_addr == LLDB_INVALID_ADDRESS)
1929 {
1930 error.SetErrorString("image already unloaded");
1931 }
1932 else
1933 {
1934 DynamicLoader *loader = GetDynamicLoader();
1935 if (loader)
1936 error = loader->CanLoadImage();
1937
1938 if (error.Success())
1939 {
1940 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001941
1942 if (thread_sp)
1943 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001944 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001945
1946 if (frame_sp)
1947 {
1948 ExecutionContext exe_ctx;
1949 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001950 EvaluateExpressionOptions expr_options;
1951 expr_options.SetUnwindOnError(true);
1952 expr_options.SetIgnoreBreakpoints(true);
1953 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001954 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001955 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001956 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001957 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001958 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001959 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001960 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001961 expr.GetData(),
1962 prefix,
1963 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001964 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001965 if (result_valobj_sp->GetError().Success())
1966 {
1967 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001968 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001969 {
1970 if (scalar.UInt(1))
1971 {
1972 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1973 }
1974 else
1975 {
1976 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1977 }
1978 }
1979 }
1980 else
1981 {
1982 error = result_valobj_sp->GetError();
1983 }
1984 }
1985 }
1986 }
1987 }
1988 }
1989 else
1990 {
1991 error.SetErrorString("invalid image token");
1992 }
1993 return error;
1994}
1995
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001996const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997Process::GetABI()
1998{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001999 if (!m_abi_sp)
2000 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2001 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002}
2003
Jim Ingham22777012010-09-23 02:01:19 +00002004LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002005Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002006{
2007 LanguageRuntimeCollection::iterator pos;
2008 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002009 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002010 {
Jim Inghamab175242012-03-10 00:22:19 +00002011 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002012
Jim Inghamab175242012-03-10 00:22:19 +00002013 m_language_runtimes[language] = runtime_sp;
2014 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002015 }
2016 else
2017 return (*pos).second.get();
2018}
2019
2020CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002021Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002022{
Jim Inghamab175242012-03-10 00:22:19 +00002023 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002024 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2025 return static_cast<CPPLanguageRuntime *> (runtime);
2026 return NULL;
2027}
2028
2029ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002030Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002031{
Jim Inghamab175242012-03-10 00:22:19 +00002032 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002033 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2034 return static_cast<ObjCLanguageRuntime *> (runtime);
2035 return NULL;
2036}
2037
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002038bool
2039Process::IsPossibleDynamicValue (ValueObject& in_value)
2040{
2041 if (in_value.IsDynamic())
2042 return false;
2043 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2044
2045 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2046 {
2047 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2048 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2049 }
2050
2051 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2052 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2053 return true;
2054
2055 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2056 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2057}
2058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002059BreakpointSiteList &
2060Process::GetBreakpointSiteList()
2061{
2062 return m_breakpoint_site_list;
2063}
2064
2065const BreakpointSiteList &
2066Process::GetBreakpointSiteList() const
2067{
2068 return m_breakpoint_site_list;
2069}
2070
2071
2072void
2073Process::DisableAllBreakpointSites ()
2074{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002075 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2076// bp_site->SetEnabled(true);
2077 DisableBreakpointSite(bp_site);
2078 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079}
2080
2081Error
2082Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2083{
2084 Error error (DisableBreakpointSiteByID (break_id));
2085
2086 if (error.Success())
2087 m_breakpoint_site_list.Remove(break_id);
2088
2089 return error;
2090}
2091
2092Error
2093Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2094{
2095 Error error;
2096 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2097 if (bp_site_sp)
2098 {
2099 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002100 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101 }
2102 else
2103 {
Daniel Malead01b2952012-11-29 21:49:15 +00002104 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002105 }
2106
2107 return error;
2108}
2109
2110Error
2111Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2112{
2113 Error error;
2114 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2115 if (bp_site_sp)
2116 {
2117 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002118 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002119 }
2120 else
2121 {
Daniel Malead01b2952012-11-29 21:49:15 +00002122 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123 }
2124 return error;
2125}
2126
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002127lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002128Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002130 addr_t load_addr = LLDB_INVALID_ADDRESS;
2131
2132 bool show_error = true;
2133 switch (GetState())
2134 {
2135 case eStateInvalid:
2136 case eStateUnloaded:
2137 case eStateConnected:
2138 case eStateAttaching:
2139 case eStateLaunching:
2140 case eStateDetached:
2141 case eStateExited:
2142 show_error = false;
2143 break;
2144
2145 case eStateStopped:
2146 case eStateRunning:
2147 case eStateStepping:
2148 case eStateCrashed:
2149 case eStateSuspended:
2150 show_error = IsAlive();
2151 break;
2152 }
2153
2154 // Reset the IsIndirect flag here, in case the location changes from
2155 // pointing to a indirect symbol to a regular symbol.
2156 owner->SetIsIndirect (false);
2157
2158 if (owner->ShouldResolveIndirectFunctions())
2159 {
2160 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2161 if (symbol && symbol->IsIndirect())
2162 {
2163 Error error;
2164 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2165 if (!error.Success() && show_error)
2166 {
Greg Clayton44d93782014-01-27 23:43:24 +00002167 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2168 symbol->GetAddress().GetLoadAddress(&m_target),
2169 owner->GetBreakpoint().GetID(),
2170 owner->GetID(),
2171 error.AsCString() ? error.AsCString() : "unkown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002172 return LLDB_INVALID_BREAK_ID;
2173 }
2174 Address resolved_address(load_addr);
2175 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2176 owner->SetIsIndirect(true);
2177 }
2178 else
2179 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2180 }
2181 else
2182 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2183
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184 if (load_addr != LLDB_INVALID_ADDRESS)
2185 {
2186 BreakpointSiteSP bp_site_sp;
2187
2188 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2189 // create a new breakpoint site and add it.
2190
2191 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2192
2193 if (bp_site_sp)
2194 {
2195 bp_site_sp->AddOwner (owner);
2196 owner->SetBreakpointSite (bp_site_sp);
2197 return bp_site_sp->GetID();
2198 }
2199 else
2200 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002201 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202 if (bp_site_sp)
2203 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002204 Error error = EnableBreakpointSite (bp_site_sp.get());
2205 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206 {
2207 owner->SetBreakpointSite (bp_site_sp);
2208 return m_breakpoint_site_list.Add (bp_site_sp);
2209 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002210 else
2211 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002212 if (show_error)
2213 {
2214 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002215 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2216 load_addr,
2217 owner->GetBreakpoint().GetID(),
2218 owner->GetID(),
2219 error.AsCString() ? error.AsCString() : "unkown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002220 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002221 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222 }
2223 }
2224 }
2225 // We failed to enable the breakpoint
2226 return LLDB_INVALID_BREAK_ID;
2227
2228}
2229
2230void
2231Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2232{
2233 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2234 if (num_owners == 0)
2235 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002236 // Don't try to disable the site if we don't have a live process anymore.
2237 if (IsAlive())
2238 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2240 }
2241}
2242
2243
2244size_t
2245Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2246{
2247 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002248 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249
Jim Ingham20c77192011-06-29 19:42:28 +00002250 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002252 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2253 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002255 addr_t intersect_addr;
2256 size_t intersect_size;
2257 size_t opcode_offset;
2258 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002259 {
2260 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2261 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002262 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002263 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002264 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002265 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002267 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 }
2269 return bytes_removed;
2270}
2271
2272
Greg Claytonded470d2011-03-19 01:12:21 +00002273
2274size_t
2275Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2276{
2277 PlatformSP platform_sp (m_target.GetPlatform());
2278 if (platform_sp)
2279 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2280 return 0;
2281}
2282
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283Error
2284Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2285{
2286 Error error;
2287 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002288 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 const addr_t bp_addr = bp_site->GetLoadAddress();
2290 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002291 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 if (bp_site->IsEnabled())
2293 {
2294 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002295 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 +00002296 return error;
2297 }
2298
2299 if (bp_addr == LLDB_INVALID_ADDRESS)
2300 {
2301 error.SetErrorString("BreakpointSite contains an invalid load address.");
2302 return error;
2303 }
2304 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2305 // trap for the breakpoint site
2306 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2307
2308 if (bp_opcode_size == 0)
2309 {
Daniel Malead01b2952012-11-29 21:49:15 +00002310 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311 }
2312 else
2313 {
2314 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2315
2316 if (bp_opcode_bytes == NULL)
2317 {
2318 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2319 return error;
2320 }
2321
2322 // Save the original opcode by reading it
2323 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2324 {
2325 // Write a software breakpoint in place of the original opcode
2326 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2327 {
2328 uint8_t verify_bp_opcode_bytes[64];
2329 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2330 {
2331 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2332 {
2333 bp_site->SetEnabled(true);
2334 bp_site->SetType (BreakpointSite::eSoftware);
2335 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002336 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 bp_site->GetID(),
2338 (uint64_t)bp_addr);
2339 }
2340 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002341 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342 }
2343 else
2344 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2345 }
2346 else
2347 error.SetErrorString("Unable to write breakpoint trap to memory.");
2348 }
2349 else
2350 error.SetErrorString("Unable to read memory at breakpoint address.");
2351 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002352 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002353 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 bp_site->GetID(),
2355 (uint64_t)bp_addr,
2356 error.AsCString());
2357 return error;
2358}
2359
2360Error
2361Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2362{
2363 Error error;
2364 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002365 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 addr_t bp_addr = bp_site->GetLoadAddress();
2367 lldb::user_id_t breakID = bp_site->GetID();
2368 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002369 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370
2371 if (bp_site->IsHardware())
2372 {
2373 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2374 }
2375 else if (bp_site->IsEnabled())
2376 {
2377 const size_t break_op_size = bp_site->GetByteSize();
2378 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2379 if (break_op_size > 0)
2380 {
2381 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002382 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002383 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 bool break_op_found = false;
2385
2386 // Read the breakpoint opcode
2387 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2388 {
2389 bool verify = false;
2390 // Make sure we have the a breakpoint opcode exists at this address
2391 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2392 {
2393 break_op_found = true;
2394 // We found a valid breakpoint opcode at this address, now restore
2395 // the saved opcode.
2396 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2397 {
2398 verify = true;
2399 }
2400 else
2401 error.SetErrorString("Memory write failed when restoring original opcode.");
2402 }
2403 else
2404 {
2405 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2406 // Set verify to true and so we can check if the original opcode has already been restored
2407 verify = true;
2408 }
2409
2410 if (verify)
2411 {
Greg Claytonc982c762010-07-09 20:39:50 +00002412 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002413 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414 // Verify that our original opcode made it back to the inferior
2415 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2416 {
2417 // compare the memory we just read with the original opcode
2418 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2419 {
2420 // SUCCESS
2421 bp_site->SetEnabled(false);
2422 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002423 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 +00002424 return error;
2425 }
2426 else
2427 {
2428 if (break_op_found)
2429 error.SetErrorString("Failed to restore original opcode.");
2430 }
2431 }
2432 else
2433 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2434 }
2435 }
2436 else
2437 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2438 }
2439 }
2440 else
2441 {
2442 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002443 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 +00002444 return error;
2445 }
2446
2447 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002448 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002449 bp_site->GetID(),
2450 (uint64_t)bp_addr,
2451 error.AsCString());
2452 return error;
2453
2454}
2455
Greg Clayton58be07b2011-01-07 06:08:19 +00002456// Uncomment to verify memory caching works after making changes to caching code
2457//#define VERIFY_MEMORY_READS
2458
Sean Callanan64c0cf22012-06-07 22:26:42 +00002459size_t
2460Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2461{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002462 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002463 if (!GetDisableMemoryCache())
2464 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002465#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002466 // Memory caching is enabled, with debug verification
2467
2468 if (buf && size)
2469 {
2470 // Uncomment the line below to make sure memory caching is working.
2471 // I ran this through the test suite and got no assertions, so I am
2472 // pretty confident this is working well. If any changes are made to
2473 // memory caching, uncomment the line below and test your changes!
2474
2475 // Verify all memory reads by using the cache first, then redundantly
2476 // reading the same memory from the inferior and comparing to make sure
2477 // everything is exactly the same.
2478 std::string verify_buf (size, '\0');
2479 assert (verify_buf.size() == size);
2480 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2481 Error verify_error;
2482 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2483 assert (cache_bytes_read == verify_bytes_read);
2484 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2485 assert (verify_error.Success() == error.Success());
2486 return cache_bytes_read;
2487 }
2488 return 0;
2489#else // !defined(VERIFY_MEMORY_READS)
2490 // Memory caching is enabled, without debug verification
2491
2492 return m_memory_cache.Read (addr, buf, size, error);
2493#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002494 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002495 else
2496 {
2497 // Memory caching is disabled
2498
2499 return ReadMemoryFromInferior (addr, buf, size, error);
2500 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002501}
Greg Clayton58be07b2011-01-07 06:08:19 +00002502
Greg Clayton4c82d422012-05-18 23:20:01 +00002503size_t
2504Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2505{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002506 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002507 out_str.clear();
2508 addr_t curr_addr = addr;
2509 while (1)
2510 {
2511 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2512 if (length == 0)
2513 break;
2514 out_str.append(buf, length);
2515 // If we got "length - 1" bytes, we didn't get the whole C string, we
2516 // need to read some more characters
2517 if (length == sizeof(buf) - 1)
2518 curr_addr += length;
2519 else
2520 break;
2521 }
2522 return out_str.size();
2523}
2524
Greg Clayton58be07b2011-01-07 06:08:19 +00002525
2526size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002527Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2528 size_t type_width)
2529{
2530 size_t total_bytes_read = 0;
2531 if (dst && max_bytes && type_width && max_bytes >= type_width)
2532 {
2533 // Ensure a null terminator independent of the number of bytes that is read.
2534 memset (dst, 0, max_bytes);
2535 size_t bytes_left = max_bytes - type_width;
2536
2537 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2538 assert(sizeof(terminator) >= type_width &&
2539 "Attempting to validate a string with more than 4 bytes per character!");
2540
2541 addr_t curr_addr = addr;
2542 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2543 char *curr_dst = dst;
2544
2545 error.Clear();
2546 while (bytes_left > 0 && error.Success())
2547 {
2548 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2549 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2550 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2551
2552 if (bytes_read == 0)
2553 break;
2554
2555 // Search for a null terminator of correct size and alignment in bytes_read
2556 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2557 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2558 if (::strncmp(&dst[i], terminator, type_width) == 0)
2559 {
2560 error.Clear();
2561 return i;
2562 }
2563
2564 total_bytes_read += bytes_read;
2565 curr_dst += bytes_read;
2566 curr_addr += bytes_read;
2567 bytes_left -= bytes_read;
2568 }
2569 }
2570 else
2571 {
2572 if (max_bytes)
2573 error.SetErrorString("invalid arguments");
2574 }
2575 return total_bytes_read;
2576}
2577
2578// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2579// null terminators.
2580size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002581Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002582{
2583 size_t total_cstr_len = 0;
2584 if (dst && dst_max_len)
2585 {
Greg Claytone91b7952011-12-15 03:14:23 +00002586 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002587 // NULL out everything just to be safe
2588 memset (dst, 0, dst_max_len);
2589 Error error;
2590 addr_t curr_addr = addr;
2591 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2592 size_t bytes_left = dst_max_len - 1;
2593 char *curr_dst = dst;
2594
2595 while (bytes_left > 0)
2596 {
2597 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2598 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2599 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2600
2601 if (bytes_read == 0)
2602 {
Greg Claytone91b7952011-12-15 03:14:23 +00002603 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002604 dst[total_cstr_len] = '\0';
2605 break;
2606 }
2607 const size_t len = strlen(curr_dst);
2608
2609 total_cstr_len += len;
2610
2611 if (len < bytes_to_read)
2612 break;
2613
2614 curr_dst += bytes_read;
2615 curr_addr += bytes_read;
2616 bytes_left -= bytes_read;
2617 }
2618 }
Greg Claytone91b7952011-12-15 03:14:23 +00002619 else
2620 {
2621 if (dst == NULL)
2622 result_error.SetErrorString("invalid arguments");
2623 else
2624 result_error.Clear();
2625 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002626 return total_cstr_len;
2627}
2628
2629size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002630Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2631{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632 if (buf == NULL || size == 0)
2633 return 0;
2634
2635 size_t bytes_read = 0;
2636 uint8_t *bytes = (uint8_t *)buf;
2637
2638 while (bytes_read < size)
2639 {
2640 const size_t curr_size = size - bytes_read;
2641 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2642 bytes + bytes_read,
2643 curr_size,
2644 error);
2645 bytes_read += curr_bytes_read;
2646 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2647 break;
2648 }
2649
2650 // Replace any software breakpoint opcodes that fall into this range back
2651 // into "buf" before we return
2652 if (bytes_read > 0)
2653 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2654 return bytes_read;
2655}
2656
Greg Clayton58a4c462010-12-16 20:01:20 +00002657uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002658Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002659{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002660 Scalar scalar;
2661 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2662 return scalar.ULongLong(fail_value);
2663 return fail_value;
2664}
2665
2666addr_t
2667Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2668{
2669 Scalar scalar;
2670 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2671 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2672 return LLDB_INVALID_ADDRESS;
2673}
2674
2675
2676bool
2677Process::WritePointerToMemory (lldb::addr_t vm_addr,
2678 lldb::addr_t ptr_value,
2679 Error &error)
2680{
2681 Scalar scalar;
2682 const uint32_t addr_byte_size = GetAddressByteSize();
2683 if (addr_byte_size <= 4)
2684 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002685 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002686 scalar = ptr_value;
2687 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002688}
2689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002690size_t
2691Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2692{
2693 size_t bytes_written = 0;
2694 const uint8_t *bytes = (const uint8_t *)buf;
2695
2696 while (bytes_written < size)
2697 {
2698 const size_t curr_size = size - bytes_written;
2699 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2700 bytes + bytes_written,
2701 curr_size,
2702 error);
2703 bytes_written += curr_bytes_written;
2704 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2705 break;
2706 }
2707 return bytes_written;
2708}
2709
2710size_t
2711Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2712{
Greg Clayton58be07b2011-01-07 06:08:19 +00002713#if defined (ENABLE_MEMORY_CACHING)
2714 m_memory_cache.Flush (addr, size);
2715#endif
2716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 if (buf == NULL || size == 0)
2718 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002719
Jim Ingham4b536182011-08-09 02:12:22 +00002720 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722 // We need to write any data that would go where any current software traps
2723 // (enabled software breakpoints) any software traps (breakpoints) that we
2724 // may have placed in our tasks memory.
2725
Greg Claytond8cf1a12013-06-12 00:46:38 +00002726 BreakpointSiteList bp_sites_in_range;
2727
2728 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002730 // No breakpoint sites overlap
2731 if (bp_sites_in_range.IsEmpty())
2732 return WriteMemoryPrivate (addr, buf, size, error);
2733 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002735 const uint8_t *ubuf = (const uint8_t *)buf;
2736 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737
Greg Claytond8cf1a12013-06-12 00:46:38 +00002738 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2739
2740 if (error.Success())
2741 {
2742 addr_t intersect_addr;
2743 size_t intersect_size;
2744 size_t opcode_offset;
2745 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2746 assert(intersects);
2747 assert(addr <= intersect_addr && intersect_addr < addr + size);
2748 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2749 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2750
2751 // Check for bytes before this breakpoint
2752 const addr_t curr_addr = addr + bytes_written;
2753 if (intersect_addr > curr_addr)
2754 {
2755 // There are some bytes before this breakpoint that we need to
2756 // just write to memory
2757 size_t curr_size = intersect_addr - curr_addr;
2758 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2759 ubuf + bytes_written,
2760 curr_size,
2761 error);
2762 bytes_written += curr_bytes_written;
2763 if (curr_bytes_written != curr_size)
2764 {
2765 // We weren't able to write all of the requested bytes, we
2766 // are done looping and will return the number of bytes that
2767 // we have written so far.
2768 if (error.Success())
2769 error.SetErrorToGenericError();
2770 }
2771 }
2772 // Now write any bytes that would cover up any software breakpoints
2773 // directly into the breakpoint opcode buffer
2774 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2775 bytes_written += intersect_size;
2776 }
2777 });
2778
2779 if (bytes_written < size)
2780 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2781 ubuf + bytes_written,
2782 size - bytes_written,
2783 error);
2784 }
2785 }
2786 else
2787 {
2788 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789 }
2790
2791 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002792 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002794
2795size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002796Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002797{
2798 if (byte_size == UINT32_MAX)
2799 byte_size = scalar.GetByteSize();
2800 if (byte_size > 0)
2801 {
2802 uint8_t buf[32];
2803 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2804 if (mem_size > 0)
2805 return WriteMemory(addr, buf, mem_size, error);
2806 else
2807 error.SetErrorString ("failed to get scalar as memory data");
2808 }
2809 else
2810 {
2811 error.SetErrorString ("invalid scalar value");
2812 }
2813 return 0;
2814}
2815
2816size_t
2817Process::ReadScalarIntegerFromMemory (addr_t addr,
2818 uint32_t byte_size,
2819 bool is_signed,
2820 Scalar &scalar,
2821 Error &error)
2822{
Greg Clayton7060f892013-05-01 23:41:30 +00002823 uint64_t uval = 0;
2824 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002825 {
Greg Clayton7060f892013-05-01 23:41:30 +00002826 error.SetErrorString ("byte size is zero");
2827 }
2828 else if (byte_size & (byte_size - 1))
2829 {
2830 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2831 }
2832 else if (byte_size <= sizeof(uval))
2833 {
2834 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002835 if (bytes_read == byte_size)
2836 {
2837 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002838 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002839 if (byte_size <= 4)
2840 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002841 else
Greg Clayton7060f892013-05-01 23:41:30 +00002842 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002843 if (is_signed)
2844 scalar.SignExtend(byte_size * 8);
2845 return bytes_read;
2846 }
2847 }
2848 else
2849 {
2850 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2851 }
2852 return 0;
2853}
2854
Greg Claytond495c532011-05-17 03:37:42 +00002855#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002856addr_t
2857Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2858{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002859 if (GetPrivateState() != eStateStopped)
2860 return LLDB_INVALID_ADDRESS;
2861
Greg Claytond495c532011-05-17 03:37:42 +00002862#if defined (USE_ALLOCATE_MEMORY_CACHE)
2863 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2864#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002865 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002866 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002867 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002868 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 +00002869 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002870 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002871 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002872 m_mod_id.GetStopID(),
2873 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002874 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002875#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002876}
2877
Sean Callanan90539452011-09-20 23:01:51 +00002878bool
2879Process::CanJIT ()
2880{
Sean Callanana7b443a2012-02-14 22:50:38 +00002881 if (m_can_jit == eCanJITDontKnow)
2882 {
2883 Error err;
2884
2885 uint64_t allocated_memory = AllocateMemory(8,
2886 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2887 err);
2888
2889 if (err.Success())
2890 m_can_jit = eCanJITYes;
2891 else
2892 m_can_jit = eCanJITNo;
2893
2894 DeallocateMemory (allocated_memory);
2895 }
2896
Sean Callanan90539452011-09-20 23:01:51 +00002897 return m_can_jit == eCanJITYes;
2898}
2899
2900void
2901Process::SetCanJIT (bool can_jit)
2902{
2903 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2904}
2905
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002906Error
2907Process::DeallocateMemory (addr_t ptr)
2908{
Greg Claytond495c532011-05-17 03:37:42 +00002909 Error error;
2910#if defined (USE_ALLOCATE_MEMORY_CACHE)
2911 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2912 {
Daniel Malead01b2952012-11-29 21:49:15 +00002913 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002914 }
2915#else
2916 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002917
Greg Clayton5160ce52013-03-27 23:08:40 +00002918 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002919 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002920 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 +00002921 ptr,
2922 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002923 m_mod_id.GetStopID(),
2924 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002925#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002926 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927}
2928
Han Ming Ongc811d382012-11-17 00:33:14 +00002929
Greg Claytonc9660542012-02-05 02:38:54 +00002930ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002931Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002932 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002933{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002934 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002935 if (module_sp)
2936 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002937 Error error;
2938 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2939 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002940 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002941 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002942 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002943}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944
2945Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002946Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002947{
2948 Error error;
2949 error.SetErrorString("watchpoints are not supported");
2950 return error;
2951}
2952
2953Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002954Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002955{
2956 Error error;
2957 error.SetErrorString("watchpoints are not supported");
2958 return error;
2959}
2960
2961StateType
2962Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2963{
2964 StateType state;
2965 // Now wait for the process to launch and return control to us, and then
2966 // call DidLaunch:
2967 while (1)
2968 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002969 event_sp.reset();
2970 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2971
Greg Clayton2637f822011-11-17 01:23:07 +00002972 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002973 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002974
2975 // If state is invalid, then we timed out
2976 if (state == eStateInvalid)
2977 break;
2978
2979 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002980 HandlePrivateEvent (event_sp);
2981 }
2982 return state;
2983}
2984
2985Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002986Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987{
2988 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002990 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002991 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002992 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002993 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002994
Greg Claytonaa149cb2011-08-11 02:48:45 +00002995 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002996 if (exe_module)
2997 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002998 char local_exec_file_path[PATH_MAX];
2999 char platform_exec_file_path[PATH_MAX];
3000 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3001 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002 if (exe_module->GetFileSpec().Exists())
3003 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003004 // Install anything that might need to be installed prior to launching.
3005 // For host systems, this will do nothing, but if we are connected to a
3006 // remote platform it will install any needed binaries
3007 error = GetTarget().Install(&launch_info);
3008 if (error.Fail())
3009 return error;
3010
Greg Clayton71337622011-02-24 22:24:29 +00003011 if (PrivateStateThreadIsValid ())
3012 PausePrivateStateThread ();
3013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014 error = WillLaunch (exe_module);
3015 if (error.Success())
3016 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003017 const bool restarted = false;
3018 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003019 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003020
Ed Maste64fad602013-07-29 20:58:06 +00003021 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003022 {
3023 // Now launch using these arguments.
3024 error = DoLaunch (exe_module, launch_info);
3025 }
3026 else
3027 {
3028 // This shouldn't happen
3029 error.SetErrorString("failed to acquire process run lock");
3030 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003031
3032 if (error.Fail())
3033 {
3034 if (GetID() != LLDB_INVALID_PROCESS_ID)
3035 {
3036 SetID (LLDB_INVALID_PROCESS_ID);
3037 const char *error_string = error.AsCString();
3038 if (error_string == NULL)
3039 error_string = "launch failed";
3040 SetExitStatus (-1, error_string);
3041 }
3042 }
3043 else
3044 {
3045 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003046 TimeValue timeout_time;
3047 timeout_time = TimeValue::Now();
3048 timeout_time.OffsetWithSeconds(10);
3049 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050
Greg Clayton1a38ea72011-06-22 01:42:17 +00003051 if (state == eStateInvalid || event_sp.get() == NULL)
3052 {
3053 // We were able to launch the process, but we failed to
3054 // catch the initial stop.
3055 SetExitStatus (0, "failed to catch stop after launch");
3056 Destroy();
3057 }
3058 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003059 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003060
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 DidLaunch ();
3062
Greg Claytonc859e2d2012-02-13 23:10:39 +00003063 DynamicLoader *dyld = GetDynamicLoader ();
3064 if (dyld)
3065 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003066
Jason Molendaeef51062013-11-05 03:57:19 +00003067 SystemRuntime *system_runtime = GetSystemRuntime ();
3068 if (system_runtime)
3069 system_runtime->DidLaunch();
3070
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003071 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072 // This delays passing the stopped event to listeners till DidLaunch gets
3073 // a chance to complete...
3074 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00003075
3076 if (PrivateStateThreadIsValid ())
3077 ResumePrivateStateThread ();
3078 else
3079 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080 }
3081 else if (state == eStateExited)
3082 {
3083 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3084 // not likely to work, and return an invalid pid.
3085 HandlePrivateEvent (event_sp);
3086 }
3087 }
3088 }
3089 }
3090 else
3091 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003092 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003093 }
3094 }
3095 return error;
3096}
3097
Greg Claytonc3776bf2012-02-09 06:16:32 +00003098
3099Error
3100Process::LoadCore ()
3101{
3102 Error error = DoLoadCore();
3103 if (error.Success())
3104 {
3105 if (PrivateStateThreadIsValid ())
3106 ResumePrivateStateThread ();
3107 else
3108 StartPrivateStateThread ();
3109
Greg Claytonc859e2d2012-02-13 23:10:39 +00003110 DynamicLoader *dyld = GetDynamicLoader ();
3111 if (dyld)
3112 dyld->DidAttach();
3113
Jason Molendaeef51062013-11-05 03:57:19 +00003114 SystemRuntime *system_runtime = GetSystemRuntime ();
3115 if (system_runtime)
3116 system_runtime->DidAttach();
3117
Greg Claytonc859e2d2012-02-13 23:10:39 +00003118 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003119 // We successfully loaded a core file, now pretend we stopped so we can
3120 // show all of the threads in the core file and explore the crashed
3121 // state.
3122 SetPrivateState (eStateStopped);
3123
3124 }
3125 return error;
3126}
3127
Greg Claytonc859e2d2012-02-13 23:10:39 +00003128DynamicLoader *
3129Process::GetDynamicLoader ()
3130{
3131 if (m_dyld_ap.get() == NULL)
3132 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3133 return m_dyld_ap.get();
3134}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003135
Jason Molendaeef51062013-11-05 03:57:19 +00003136SystemRuntime *
3137Process::GetSystemRuntime ()
3138{
3139 if (m_system_runtime_ap.get() == NULL)
3140 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3141 return m_system_runtime_ap.get();
3142}
3143
Greg Claytonc3776bf2012-02-09 06:16:32 +00003144
Jim Inghambb3a2832011-01-29 01:49:25 +00003145Process::NextEventAction::EventActionResult
3146Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147{
Jim Inghambb3a2832011-01-29 01:49:25 +00003148 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3149 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003150 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003151 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003152 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003153 return eEventActionRetry;
3154
3155 case eStateStopped:
3156 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003157 {
3158 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003159 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003160 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003161 // We don't want these events to be reported, so go set the ShouldReportStop here:
3162 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3163
Greg Claytonc9ed4782011-11-12 02:10:56 +00003164 if (m_exec_count > 0)
3165 {
3166 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003167 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003168 return eEventActionRetry;
3169 }
3170 else
3171 {
3172 m_process->CompleteAttach ();
3173 return eEventActionSuccess;
3174 }
3175 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003176 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003177
Greg Clayton513c26c2011-01-29 07:10:55 +00003178 default:
3179 case eStateExited:
3180 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003181 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003182 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003183
3184 m_exit_string.assign ("No valid Process");
3185 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003186}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187
Jim Inghambb3a2832011-01-29 01:49:25 +00003188Process::NextEventAction::EventActionResult
3189Process::AttachCompletionHandler::HandleBeingInterrupted()
3190{
3191 return eEventActionSuccess;
3192}
3193
3194const char *
3195Process::AttachCompletionHandler::GetExitString ()
3196{
3197 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003198}
3199
3200Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003201Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003203 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003204 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003205 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003206 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003207 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003208
Greg Clayton144f3a92011-11-15 03:53:30 +00003209 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003210 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003211 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003212 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003213 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003214
Greg Clayton144f3a92011-11-15 03:53:30 +00003215 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003216 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003217 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3218
3219 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003220 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003221 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3222 if (error.Success())
3223 {
Ed Maste64fad602013-07-29 20:58:06 +00003224 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003225 {
3226 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003227 const bool restarted = false;
3228 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003229 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003230 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003231 }
3232 else
3233 {
3234 // This shouldn't happen
3235 error.SetErrorString("failed to acquire process run lock");
3236 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003237
Greg Clayton144f3a92011-11-15 03:53:30 +00003238 if (error.Fail())
3239 {
3240 if (GetID() != LLDB_INVALID_PROCESS_ID)
3241 {
3242 SetID (LLDB_INVALID_PROCESS_ID);
3243 if (error.AsCString() == NULL)
3244 error.SetErrorString("attach failed");
3245
3246 SetExitStatus(-1, error.AsCString());
3247 }
3248 }
3249 else
3250 {
3251 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3252 StartPrivateStateThread();
3253 }
3254 return error;
3255 }
Greg Claytone996fd32011-03-08 22:40:15 +00003256 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003257 else
Greg Claytone996fd32011-03-08 22:40:15 +00003258 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003259 ProcessInstanceInfoList process_infos;
3260 PlatformSP platform_sp (m_target.GetPlatform ());
3261
3262 if (platform_sp)
3263 {
3264 ProcessInstanceInfoMatch match_info;
3265 match_info.GetProcessInfo() = attach_info;
3266 match_info.SetNameMatchType (eNameMatchEquals);
3267 platform_sp->FindProcesses (match_info, process_infos);
3268 const uint32_t num_matches = process_infos.GetSize();
3269 if (num_matches == 1)
3270 {
3271 attach_pid = process_infos.GetProcessIDAtIndex(0);
3272 // Fall through and attach using the above process ID
3273 }
3274 else
3275 {
3276 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3277 if (num_matches > 1)
3278 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3279 else
3280 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3281 }
3282 }
3283 else
3284 {
3285 error.SetErrorString ("invalid platform, can't find processes by name");
3286 return error;
3287 }
Greg Claytone996fd32011-03-08 22:40:15 +00003288 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003289 }
3290 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003291 {
3292 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003293 }
3294 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003295
3296 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003297 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003298 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003299 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003300 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003301
Ed Maste64fad602013-07-29 20:58:06 +00003302 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003303 {
3304 // Now attach using these arguments.
3305 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003306 const bool restarted = false;
3307 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003308 error = DoAttachToProcessWithID (attach_pid, attach_info);
3309 }
3310 else
3311 {
3312 // This shouldn't happen
3313 error.SetErrorString("failed to acquire process run lock");
3314 }
3315
Greg Clayton144f3a92011-11-15 03:53:30 +00003316 if (error.Success())
3317 {
3318
3319 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3320 StartPrivateStateThread();
3321 }
3322 else
Greg Claytone996fd32011-03-08 22:40:15 +00003323 {
3324 if (GetID() != LLDB_INVALID_PROCESS_ID)
3325 {
3326 SetID (LLDB_INVALID_PROCESS_ID);
3327 const char *error_string = error.AsCString();
3328 if (error_string == NULL)
3329 error_string = "attach failed";
3330
3331 SetExitStatus(-1, error_string);
3332 }
3333 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003334 }
3335 }
3336 return error;
3337}
3338
Greg Clayton93d3c8332011-02-16 04:46:07 +00003339void
3340Process::CompleteAttach ()
3341{
3342 // Let the process subclass figure out at much as it can about the process
3343 // before we go looking for a dynamic loader plug-in.
3344 DidAttach();
3345
Jim Ingham4299fdb2011-09-15 01:10:17 +00003346 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3347 // the same as the one we've already set, switch architectures.
3348 PlatformSP platform_sp (m_target.GetPlatform ());
3349 assert (platform_sp.get());
3350 if (platform_sp)
3351 {
Greg Clayton70512312012-05-08 01:45:38 +00003352 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003353 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003354 {
3355 ArchSpec platform_arch;
3356 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3357 if (platform_sp)
3358 {
3359 m_target.SetPlatform (platform_sp);
3360 m_target.SetArchitecture(platform_arch);
3361 }
3362 }
3363 else
3364 {
3365 ProcessInstanceInfo process_info;
3366 platform_sp->GetProcessInfo (GetID(), process_info);
3367 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003368 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003369 m_target.SetArchitecture (process_arch);
3370 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003371 }
3372
3373 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003374 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003375 DynamicLoader *dyld = GetDynamicLoader ();
3376 if (dyld)
3377 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003378
Jason Molendaeef51062013-11-05 03:57:19 +00003379 SystemRuntime *system_runtime = GetSystemRuntime ();
3380 if (system_runtime)
3381 system_runtime->DidAttach();
3382
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003383 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003384 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003385 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003386 Mutex::Locker modules_locker(target_modules.GetMutex());
3387 size_t num_modules = target_modules.GetSize();
3388 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003389
Andy Gibbsa297a972013-06-19 19:04:53 +00003390 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003391 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003392 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003393 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003394 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003395 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003396 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003397 break;
3398 }
3399 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003400 if (new_executable_module_sp)
3401 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003402}
3403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003405Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003406{
Greg Claytonb766a732011-02-04 01:58:07 +00003407 m_abi_sp.reset();
3408 m_process_input_reader.reset();
3409
3410 // Find the process and its architecture. Make sure it matches the architecture
3411 // of the current Target, and if not adjust it.
3412
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003413 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003414 if (error.Success())
3415 {
Greg Clayton71337622011-02-24 22:24:29 +00003416 if (GetID() != LLDB_INVALID_PROCESS_ID)
3417 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003418 EventSP event_sp;
3419 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3420
3421 if (state == eStateStopped || state == eStateCrashed)
3422 {
3423 // If we attached and actually have a process on the other end, then
3424 // this ended up being the equivalent of an attach.
3425 CompleteAttach ();
3426
3427 // This delays passing the stopped event to listeners till
3428 // CompleteAttach gets a chance to complete...
3429 HandlePrivateEvent (event_sp);
3430
3431 }
Greg Clayton71337622011-02-24 22:24:29 +00003432 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003433
3434 if (PrivateStateThreadIsValid ())
3435 ResumePrivateStateThread ();
3436 else
3437 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003438 }
3439 return error;
3440}
3441
3442
3443Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003444Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003445{
Greg Clayton5160ce52013-03-27 23:08:40 +00003446 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003447 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003448 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003449 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003450 StateAsCString(m_public_state.GetValue()),
3451 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452
3453 Error error (WillResume());
3454 // Tell the process it is about to resume before the thread list
3455 if (error.Success())
3456 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003457 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003458 // can let all of our threads know that they are about to be
3459 // resumed. Threads will each be called with
3460 // Thread::WillResume(StateType) where StateType contains the state
3461 // that they are supposed to have when the process is resumed
3462 // (suspended/running/stepping). Threads should also check
3463 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003464 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465 if (m_thread_list.WillResume())
3466 {
Jim Ingham372787f2012-04-07 00:00:41 +00003467 // Last thing, do the PreResumeActions.
3468 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003469 {
Jim Ingham0161b492013-02-09 01:29:05 +00003470 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003471 }
3472 else
3473 {
3474 m_mod_id.BumpResumeID();
3475 error = DoResume();
3476 if (error.Success())
3477 {
3478 DidResume();
3479 m_thread_list.DidResume();
3480 if (log)
3481 log->Printf ("Process thinks the process has resumed.");
3482 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003483 }
3484 }
3485 else
3486 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003487 // Somebody wanted to run without running. So generate a continue & a stopped event,
3488 // and let the world handle them.
3489 if (log)
3490 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3491
3492 SetPrivateState(eStateRunning);
3493 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003494 }
3495 }
Jim Ingham444586b2011-01-24 06:34:17 +00003496 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003497 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498 return error;
3499}
3500
3501Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003502Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003503{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003504 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3505 // in case it was already set and some thread plan logic calls halt on its
3506 // own.
3507 m_clear_thread_plans_on_stop |= clear_thread_plans;
3508
Jim Inghamaacc3182012-06-06 00:29:30 +00003509 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3510 // we could just straightaway get another event. It just narrows the window...
3511 m_currently_handling_event.WaitForValueEqualTo(false);
3512
3513
Jim Inghambb3a2832011-01-29 01:49:25 +00003514 // Pause our private state thread so we can ensure no one else eats
3515 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003516 Listener halt_listener ("lldb.process.halt_listener");
3517 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003518
Jim Inghambb3a2832011-01-29 01:49:25 +00003519 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003520 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003521
Greg Clayton513c26c2011-01-29 07:10:55 +00003522 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003523 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003524
Greg Clayton513c26c2011-01-29 07:10:55 +00003525 bool caused_stop = false;
3526
3527 // Ask the process subclass to actually halt our process
3528 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003530 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003531 if (m_public_state.GetValue() == eStateAttaching)
3532 {
3533 SetExitStatus(SIGKILL, "Cancelled async attach.");
3534 Destroy ();
3535 }
3536 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003537 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003538 // If "caused_stop" is true, then DoHalt stopped the process. If
3539 // "caused_stop" is false, the process was already stopped.
3540 // If the DoHalt caused the process to stop, then we want to catch
3541 // this event and set the interrupted bool to true before we pass
3542 // this along so clients know that the process was interrupted by
3543 // a halt command.
3544 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003545 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003546 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003547 TimeValue timeout_time;
3548 timeout_time = TimeValue::Now();
3549 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003550 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3551 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003552
Jim Ingham0f16e732011-02-08 05:20:59 +00003553 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003554 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003555 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003556 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003557 }
3558 else
3559 {
Greg Clayton2637f822011-11-17 01:23:07 +00003560 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003561 {
3562 // We caused the process to interrupt itself, so mark this
3563 // as such in the stop event so clients can tell an interrupted
3564 // process from a natural stop
3565 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3566 }
3567 else
3568 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003569 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003570 if (log)
3571 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3572 error.SetErrorString ("Did not get stopped event after halt.");
3573 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003574 }
3575 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003576 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003577 }
3578 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003579 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003580 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003581 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003582
3583 // Post any event we might have consumed. If all goes well, we will have
3584 // stopped the process, intercepted the event and set the interrupted
3585 // bool in the event. Post it to the private event queue and that will end up
3586 // correctly setting the state.
3587 if (event_sp)
3588 m_private_state_broadcaster.BroadcastEvent(event_sp);
3589
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003590 return error;
3591}
3592
3593Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003594Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3595{
3596 Error error;
3597 if (m_public_state.GetValue() == eStateRunning)
3598 {
3599 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3600 if (log)
3601 log->Printf("Process::Destroy() About to halt.");
3602 error = Halt();
3603 if (error.Success())
3604 {
3605 // Consume the halt event.
3606 TimeValue timeout (TimeValue::Now());
3607 timeout.OffsetWithSeconds(1);
3608 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3609
3610 // If the process exited while we were waiting for it to stop, put the exited event into
3611 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3612 // they don't have a process anymore...
3613
3614 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3615 {
3616 if (log)
3617 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3618 return error;
3619 }
3620 else
3621 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3622
3623 if (state != eStateStopped)
3624 {
3625 if (log)
3626 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3627 // If we really couldn't stop the process then we should just error out here, but if the
3628 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3629 StateType private_state = m_private_state.GetValue();
3630 if (private_state != eStateStopped)
3631 {
3632 return error;
3633 }
3634 }
3635 }
3636 else
3637 {
3638 if (log)
3639 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3640 }
3641 }
3642 return error;
3643}
3644
3645Error
Jim Inghamacff8952013-05-02 00:27:30 +00003646Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003648 EventSP exit_event_sp;
3649 Error error;
3650 m_destroy_in_process = true;
3651
3652 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003653
3654 if (error.Success())
3655 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003656 if (DetachRequiresHalt())
3657 {
3658 error = HaltForDestroyOrDetach (exit_event_sp);
3659 if (!error.Success())
3660 {
3661 m_destroy_in_process = false;
3662 return error;
3663 }
3664 else if (exit_event_sp)
3665 {
3666 // We shouldn't need to do anything else here. There's no process left to detach from...
3667 StopPrivateStateThread();
3668 m_destroy_in_process = false;
3669 return error;
3670 }
3671 }
3672
Jim Inghamacff8952013-05-02 00:27:30 +00003673 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003674 if (error.Success())
3675 {
3676 DidDetach();
3677 StopPrivateStateThread();
3678 }
Jim Inghamacff8952013-05-02 00:27:30 +00003679 else
3680 {
3681 return error;
3682 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003684 m_destroy_in_process = false;
3685
3686 // If we exited when we were waiting for a process to stop, then
3687 // forward the event here so we don't lose the event
3688 if (exit_event_sp)
3689 {
3690 // Directly broadcast our exited event because we shut down our
3691 // private state thread above
3692 BroadcastEvent(exit_event_sp);
3693 }
3694
3695 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3696 // the last events through the event system, in which case we might strand the write lock. Unlock
3697 // it here so when we do to tear down the process we don't get an error destroying the lock.
3698
Ed Maste64fad602013-07-29 20:58:06 +00003699 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003700 return error;
3701}
3702
3703Error
3704Process::Destroy ()
3705{
Jim Ingham09437922013-03-01 20:04:25 +00003706
3707 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3708 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3709 // failed and the process stays around for some reason it won't be in a confused state.
3710
3711 m_destroy_in_process = true;
3712
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003713 Error error (WillDestroy());
3714 if (error.Success())
3715 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003716 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003717 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003718 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003719 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003720 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003721
Jim Inghamaacc3182012-06-06 00:29:30 +00003722 if (m_public_state.GetValue() != eStateRunning)
3723 {
3724 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3725 // kill it, we don't want it hitting a breakpoint...
3726 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3727 // we're not going to have much luck doing this now.
3728 m_thread_list.DiscardThreadPlans();
3729 DisableAllBreakpointSites();
3730 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732 error = DoDestroy();
3733 if (error.Success())
3734 {
3735 DidDestroy();
3736 StopPrivateStateThread();
3737 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003738 m_stdio_communication.StopReadThread();
3739 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003740
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003741 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003742 {
3743 m_process_input_reader->SetIsDone(true);
3744 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003745 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003746 }
3747
Greg Clayton85fb1b92012-09-11 02:33:37 +00003748 // If we exited when we were waiting for a process to stop, then
3749 // forward the event here so we don't lose the event
3750 if (exit_event_sp)
3751 {
3752 // Directly broadcast our exited event because we shut down our
3753 // private state thread above
3754 BroadcastEvent(exit_event_sp);
3755 }
3756
Jim Inghamb1e2e842012-04-12 18:49:31 +00003757 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3758 // the last events through the event system, in which case we might strand the write lock. Unlock
3759 // 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 +00003760 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 }
Jim Ingham09437922013-03-01 20:04:25 +00003762
3763 m_destroy_in_process = false;
3764
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 return error;
3766}
3767
3768Error
3769Process::Signal (int signal)
3770{
3771 Error error (WillSignal());
3772 if (error.Success())
3773 {
3774 error = DoSignal(signal);
3775 if (error.Success())
3776 DidSignal();
3777 }
3778 return error;
3779}
3780
Greg Clayton514487e2011-02-15 21:59:32 +00003781lldb::ByteOrder
3782Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783{
Greg Clayton514487e2011-02-15 21:59:32 +00003784 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785}
3786
3787uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003788Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789{
Greg Clayton514487e2011-02-15 21:59:32 +00003790 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791}
3792
Greg Clayton514487e2011-02-15 21:59:32 +00003793
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003794bool
3795Process::ShouldBroadcastEvent (Event *event_ptr)
3796{
3797 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3798 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003799 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003800
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003801 switch (state)
3802 {
Greg Claytonb766a732011-02-04 01:58:07 +00003803 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003804 case eStateAttaching:
3805 case eStateLaunching:
3806 case eStateDetached:
3807 case eStateExited:
3808 case eStateUnloaded:
3809 // These events indicate changes in the state of the debugging session, always report them.
3810 return_value = true;
3811 break;
3812 case eStateInvalid:
3813 // We stopped for no apparent reason, don't report it.
3814 return_value = false;
3815 break;
3816 case eStateRunning:
3817 case eStateStepping:
3818 // If we've started the target running, we handle the cases where we
3819 // are already running and where there is a transition from stopped to
3820 // running differently.
3821 // running -> running: Automatically suppress extra running events
3822 // stopped -> running: Report except when there is one or more no votes
3823 // and no yes votes.
3824 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003825 if (m_force_next_event_delivery)
3826 return_value = true;
3827 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003829 switch (m_last_broadcast_state)
3830 {
3831 case eStateRunning:
3832 case eStateStepping:
3833 // We always suppress multiple runnings with no PUBLIC stop in between.
3834 return_value = false;
3835 break;
3836 default:
3837 // TODO: make this work correctly. For now always report
3838 // run if we aren't running so we don't miss any runnning
3839 // events. If I run the lldb/test/thread/a.out file and
3840 // break at main.cpp:58, run and hit the breakpoints on
3841 // multiple threads, then somehow during the stepping over
3842 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843
Jim Ingham1460e4b2014-01-10 23:46:59 +00003844 // This is a transition from stop to run.
3845 switch (m_thread_list.ShouldReportRun (event_ptr))
3846 {
3847 case eVoteYes:
3848 case eVoteNoOpinion:
3849 return_value = true;
3850 break;
3851 case eVoteNo:
3852 return_value = false;
3853 break;
3854 }
3855 break;
3856 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003857 }
3858 break;
3859 case eStateStopped:
3860 case eStateCrashed:
3861 case eStateSuspended:
3862 {
3863 // We've stopped. First see if we're going to restart the target.
3864 // If we are going to stop, then we always broadcast the event.
3865 // 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 +00003866 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003867
Jim Inghamcb4ca112012-05-16 01:32:14 +00003868 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003869 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003870 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003871 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003872 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3873 event_ptr,
3874 StateAsCString(state));
3875 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003876 }
3877 else
3878 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003879 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3880 bool should_resume = false;
3881
Jim Ingham0161b492013-02-09 01:29:05 +00003882 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3883 // Asking the thread list is also not likely to go well, since we are running again.
3884 // So in that case just report the event.
3885
Jim Ingham0161b492013-02-09 01:29:05 +00003886 if (!was_restarted)
3887 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003888
3889 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890 {
Jim Ingham0161b492013-02-09 01:29:05 +00003891 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3892 if (log)
3893 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3894 should_resume,
3895 StateAsCString(state),
3896 was_restarted,
3897 stop_vote);
3898
3899 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900 {
3901 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003902 return_value = true;
3903 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003904 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003905 case eVoteNo:
3906 return_value = false;
3907 break;
3908 }
Jim Ingham0161b492013-02-09 01:29:05 +00003909
Jim Inghamcb95f342012-09-05 21:13:56 +00003910 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003911 {
3912 if (log)
3913 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3914 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003915 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003916 }
3917
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003918 }
3919 else
3920 {
3921 return_value = true;
3922 SynchronouslyNotifyStateChanged (state);
3923 }
3924 }
3925 }
Jim Ingham0161b492013-02-09 01:29:05 +00003926 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003927 }
Jim Ingham0161b492013-02-09 01:29:05 +00003928
Jim Ingham1460e4b2014-01-10 23:46:59 +00003929 // Forcing the next event delivery is a one shot deal. So reset it here.
3930 m_force_next_event_delivery = false;
3931
Jim Ingham0161b492013-02-09 01:29:05 +00003932 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3933 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3934 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3935 // because the PublicState reflects the last event pulled off the queue, and there may be several
3936 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3937 // yet. m_last_broadcast_state gets updated here.
3938
3939 if (return_value)
3940 m_last_broadcast_state = state;
3941
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003942 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003943 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3944 event_ptr,
3945 StateAsCString(state),
3946 StateAsCString(m_last_broadcast_state),
3947 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003948 return return_value;
3949}
3950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003951
3952bool
Jim Ingham372787f2012-04-07 00:00:41 +00003953Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003954{
Greg Clayton5160ce52013-03-27 23:08:40 +00003955 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003956
Greg Clayton8b82f082011-04-12 05:54:46 +00003957 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003958 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003959 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3960
Jim Ingham372787f2012-04-07 00:00:41 +00003961 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003962 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003963
3964 // Create a thread that watches our internal state and controls which
3965 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003966 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003967 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003968 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003969 else
Daniel Malead01b2952012-11-29 21:49:15 +00003970 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003971
3972 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003973 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003974 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3975 if (success)
3976 {
3977 ResumePrivateStateThread();
3978 return true;
3979 }
3980 else
3981 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982}
3983
3984void
3985Process::PausePrivateStateThread ()
3986{
3987 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3988}
3989
3990void
3991Process::ResumePrivateStateThread ()
3992{
3993 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3994}
3995
3996void
3997Process::StopPrivateStateThread ()
3998{
Greg Clayton8b82f082011-04-12 05:54:46 +00003999 if (PrivateStateThreadIsValid ())
4000 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004001 else
4002 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004003 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004004 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004005 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004006 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004007}
4008
4009void
4010Process::ControlPrivateStateThread (uint32_t signal)
4011{
Greg Clayton5160ce52013-03-27 23:08:40 +00004012 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004013
4014 assert (signal == eBroadcastInternalStateControlStop ||
4015 signal == eBroadcastInternalStateControlPause ||
4016 signal == eBroadcastInternalStateControlResume);
4017
4018 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004019 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004020
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004021 // Signal the private state thread. First we should copy this is case the
4022 // thread starts exiting since the private state thread will NULL this out
4023 // when it exits
4024 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00004025 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004026 {
4027 TimeValue timeout_time;
4028 bool timed_out;
4029
4030 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4031
4032 timeout_time = TimeValue::Now();
4033 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004034 if (log)
4035 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004036 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4037 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4038
4039 if (signal == eBroadcastInternalStateControlStop)
4040 {
4041 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004042 {
4043 Error error;
4044 Host::ThreadCancel (private_state_thread, &error);
4045 if (log)
4046 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4047 }
4048 else
4049 {
4050 if (log)
4051 log->Printf ("The control event killed the private state thread without having to cancel.");
4052 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053
4054 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004055 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00004056 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004057 }
4058 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004059 else
4060 {
4061 if (log)
4062 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4063 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004064}
4065
4066void
Jim Inghamcfc09352012-07-27 23:57:19 +00004067Process::SendAsyncInterrupt ()
4068{
4069 if (PrivateStateThreadIsValid())
4070 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4071 else
4072 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4073}
4074
4075void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004076Process::HandlePrivateEvent (EventSP &event_sp)
4077{
Greg Clayton5160ce52013-03-27 23:08:40 +00004078 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004079 m_resume_requested = false;
4080
Jim Inghamaacc3182012-06-06 00:29:30 +00004081 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004082
Greg Clayton414f5d32011-01-25 02:58:48 +00004083 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004084
4085 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004086 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004087 {
Jim Ingham754ab982011-01-29 04:05:41 +00004088 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004089 if (log)
4090 log->Printf ("Ran next event action, result was %d.", action_result);
4091
Jim Inghambb3a2832011-01-29 01:49:25 +00004092 switch (action_result)
4093 {
4094 case NextEventAction::eEventActionSuccess:
4095 SetNextEventAction(NULL);
4096 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004097
Jim Inghambb3a2832011-01-29 01:49:25 +00004098 case NextEventAction::eEventActionRetry:
4099 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004100
Jim Inghambb3a2832011-01-29 01:49:25 +00004101 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004102 // Handle Exiting Here. If we already got an exited event,
4103 // we should just propagate it. Otherwise, swallow this event,
4104 // and set our state to exit so the next event will kill us.
4105 if (new_state != eStateExited)
4106 {
4107 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004108 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004109 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004110 SetNextEventAction(NULL);
4111 return;
4112 }
4113 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004114 break;
4115 }
4116 }
4117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004118 // See if we should broadcast this state to external clients?
4119 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004120
4121 if (should_broadcast)
4122 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004123 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004124 if (log)
4125 {
Daniel Malead01b2952012-11-29 21:49:15 +00004126 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004127 __FUNCTION__,
4128 GetID(),
4129 StateAsCString(new_state),
4130 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004131 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004132 }
Jim Ingham9575d842011-03-11 03:53:59 +00004133 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004134 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004135 {
4136 // Only push the input handler if we aren't fowarding events,
4137 // as this means the curses GUI is in use...
4138 if (!GetTarget().GetDebugger().IsForwardingEvents())
4139 PushProcessIOHandler ();
4140 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004141 else if (StateIsStoppedState(new_state, false))
4142 {
4143 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4144 {
4145 // If the lldb_private::Debugger is handling the events, we don't
4146 // want to pop the process IOHandler here, we want to do it when
4147 // we receive the stopped event so we can carefully control when
4148 // the process IOHandler is popped because when we stop we want to
4149 // display some text stating how and why we stopped, then maybe some
4150 // process/thread/frame info, and then we want the "(lldb) " prompt
4151 // to show up. If we pop the process IOHandler here, then we will
4152 // cause the command interpreter to become the top IOHandler after
4153 // the process pops off and it will update its prompt right away...
4154 // See the Debugger.cpp file where it calls the function as
4155 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4156 // Otherwise we end up getting overlapping "(lldb) " prompts and
4157 // garbled output.
4158 //
4159 // If we aren't handling the events in the debugger (which is indicated
4160 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4161 // are hijacked, then we always pop the process IO handler manually.
4162 // Hijacking happens when the internal process state thread is running
4163 // thread plans, or when commands want to run in synchronous mode
4164 // and they call "process->WaitForProcessToStop()". An example of something
4165 // that will hijack the events is a simple expression:
4166 //
4167 // (lldb) expr (int)puts("hello")
4168 //
4169 // This will cause the internal process state thread to resume and halt
4170 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4171 // events) and we do need the IO handler to be pushed and popped
4172 // correctly.
4173
4174 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4175 PopProcessIOHandler ();
4176 }
4177 }
Jim Ingham9575d842011-03-11 03:53:59 +00004178
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004179 BroadcastEvent (event_sp);
4180 }
4181 else
4182 {
4183 if (log)
4184 {
Daniel Malead01b2952012-11-29 21:49:15 +00004185 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004186 __FUNCTION__,
4187 GetID(),
4188 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004189 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004190 }
4191 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004192 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004193}
4194
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004195thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004196Process::PrivateStateThread (void *arg)
4197{
4198 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004199 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004200 return result;
4201}
4202
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004203thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004204Process::RunPrivateStateThread ()
4205{
Jim Ingham076b3042012-04-10 01:21:57 +00004206 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004207 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004208
Greg Clayton5160ce52013-03-27 23:08:40 +00004209 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004210 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004211 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004212
4213 bool exit_now = false;
4214 while (!exit_now)
4215 {
4216 EventSP event_sp;
4217 WaitForEventsPrivate (NULL, event_sp, control_only);
4218 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4219 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004220 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004221 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 +00004222
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004223 switch (event_sp->GetType())
4224 {
4225 case eBroadcastInternalStateControlStop:
4226 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004227 break; // doing any internal state managment below
4228
4229 case eBroadcastInternalStateControlPause:
4230 control_only = true;
4231 break;
4232
4233 case eBroadcastInternalStateControlResume:
4234 control_only = false;
4235 break;
4236 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004237
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004238 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004239 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004240 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004241 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4242 {
4243 if (m_public_state.GetValue() == eStateAttaching)
4244 {
4245 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004246 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 +00004247 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4248 }
4249 else
4250 {
4251 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004252 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004253 Halt();
4254 }
4255 continue;
4256 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004257
4258 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4259
4260 if (internal_state != eStateInvalid)
4261 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004262 if (m_clear_thread_plans_on_stop &&
4263 StateIsStoppedState(internal_state, true))
4264 {
4265 m_clear_thread_plans_on_stop = false;
4266 m_thread_list.DiscardThreadPlans();
4267 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004268 HandlePrivateEvent (event_sp);
4269 }
4270
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004271 if (internal_state == eStateInvalid ||
4272 internal_state == eStateExited ||
4273 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004274 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004275 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004276 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 +00004277
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004279 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004280 }
4281
Caroline Tice20ad3c42010-10-29 21:48:37 +00004282 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004283 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004284 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004285
Ed Maste64fad602013-07-29 20:58:06 +00004286 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004287 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4288 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004289 return NULL;
4290}
4291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004292//------------------------------------------------------------------
4293// Process Event Data
4294//------------------------------------------------------------------
4295
4296Process::ProcessEventData::ProcessEventData () :
4297 EventData (),
4298 m_process_sp (),
4299 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004300 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004301 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004302 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004303{
4304}
4305
4306Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4307 EventData (),
4308 m_process_sp (process_sp),
4309 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004310 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004311 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004312 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004313{
4314}
4315
4316Process::ProcessEventData::~ProcessEventData()
4317{
4318}
4319
4320const ConstString &
4321Process::ProcessEventData::GetFlavorString ()
4322{
4323 static ConstString g_flavor ("Process::ProcessEventData");
4324 return g_flavor;
4325}
4326
4327const ConstString &
4328Process::ProcessEventData::GetFlavor () const
4329{
4330 return ProcessEventData::GetFlavorString ();
4331}
4332
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004333void
4334Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4335{
4336 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004337 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4338 // the public event queue, then other times when we're pretending that this is where we stopped at the
4339 // end of expression evaluation. m_update_state is used to distinguish these
4340 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004341 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004342 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004343 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004344
Jim Ingham221d51c2013-05-08 00:35:16 +00004345 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004346
4347 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4348 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004349 {
4350 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004351 uint32_t num_threads = curr_thread_list.GetSize();
4352 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004353
Jim Ingham4b536182011-08-09 02:12:22 +00004354 // The actions might change one of the thread's stop_info's opinions about whether we should
4355 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004356
4357 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4358 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4359 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4360 // 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
4361 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004362 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004363 for (idx = 0; idx < num_threads; ++idx)
4364 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4365
Jim Inghamc7078c22012-12-13 22:24:15 +00004366 // Use this to track whether we should continue from here. We will only continue the target running if
4367 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4368 // then it doesn't matter what the other threads say...
4369
4370 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004371
Jim Ingham0ad7e052013-04-25 02:04:59 +00004372 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4373 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4374 // thing to do is, and it's better to let the user decide than continue behind their backs.
4375
4376 bool does_anybody_have_an_opinion = false;
4377
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004378 for (idx = 0; idx < num_threads; ++idx)
4379 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004380 curr_thread_list = m_process_sp->GetThreadList();
4381 if (curr_thread_list.GetSize() != num_threads)
4382 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004383 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004384 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004385 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 +00004386 break;
4387 }
4388
4389 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4390
4391 if (thread_sp->GetIndexID() != thread_index_array[idx])
4392 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004393 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004394 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004395 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004396 idx,
4397 thread_index_array[idx],
4398 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004399 break;
4400 }
4401
Jim Inghamb15bfc72010-10-20 00:39:53 +00004402 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004403 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004404 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004405 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004406 bool this_thread_wants_to_stop;
4407 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004408 {
Jim Ingham0161b492013-02-09 01:29:05 +00004409 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4410 }
4411 else
4412 {
4413 stop_info_sp->PerformAction(event_ptr);
4414 // The stop action might restart the target. If it does, then we want to mark that in the
4415 // event so that whoever is receiving it will know to wait for the running event and reflect
4416 // that state appropriately.
4417 // We also need to stop processing actions, since they aren't expecting the target to be running.
4418
4419 // FIXME: we might have run.
4420 if (stop_info_sp->HasTargetRunSinceMe())
4421 {
4422 SetRestarted (true);
4423 break;
4424 }
4425
4426 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004427 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004428
Jim Inghamc7078c22012-12-13 22:24:15 +00004429 if (still_should_stop == false)
4430 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004431 }
4432 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004433
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004434
Jim Inghama8ca6e22013-05-03 23:04:37 +00004435 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004436 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004437 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004438 {
4439 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004440 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004441 // Use the public resume method here, since this is just
4442 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004443 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004444 }
4445 else
4446 {
4447 // If we didn't restart, run the Stop Hooks here:
4448 // They might also restart the target, so watch for that.
4449 m_process_sp->GetTarget().RunStopHooks();
4450 if (m_process_sp->GetPrivateState() == eStateRunning)
4451 SetRestarted(true);
4452 }
Jim Ingham9575d842011-03-11 03:53:59 +00004453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004454 }
4455}
4456
4457void
4458Process::ProcessEventData::Dump (Stream *s) const
4459{
4460 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004461 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004462
Greg Clayton8b82f082011-04-12 05:54:46 +00004463 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004464}
4465
4466const Process::ProcessEventData *
4467Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4468{
4469 if (event_ptr)
4470 {
4471 const EventData *event_data = event_ptr->GetData();
4472 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4473 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4474 }
4475 return NULL;
4476}
4477
4478ProcessSP
4479Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4480{
4481 ProcessSP process_sp;
4482 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4483 if (data)
4484 process_sp = data->GetProcessSP();
4485 return process_sp;
4486}
4487
4488StateType
4489Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4490{
4491 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4492 if (data == NULL)
4493 return eStateInvalid;
4494 else
4495 return data->GetState();
4496}
4497
4498bool
4499Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4500{
4501 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4502 if (data == NULL)
4503 return false;
4504 else
4505 return data->GetRestarted();
4506}
4507
4508void
4509Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4510{
4511 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4512 if (data != NULL)
4513 data->SetRestarted(new_value);
4514}
4515
Jim Ingham0161b492013-02-09 01:29:05 +00004516size_t
4517Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4518{
4519 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4520 if (data != NULL)
4521 return data->GetNumRestartedReasons();
4522 else
4523 return 0;
4524}
4525
4526const char *
4527Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4528{
4529 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4530 if (data != NULL)
4531 return data->GetRestartedReasonAtIndex(idx);
4532 else
4533 return NULL;
4534}
4535
4536void
4537Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4538{
4539 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4540 if (data != NULL)
4541 data->AddRestartedReason(reason);
4542}
4543
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004544bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004545Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4546{
4547 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4548 if (data == NULL)
4549 return false;
4550 else
4551 return data->GetInterrupted ();
4552}
4553
4554void
4555Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4556{
4557 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4558 if (data != NULL)
4559 data->SetInterrupted(new_value);
4560}
4561
4562bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004563Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4564{
4565 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4566 if (data)
4567 {
4568 data->SetUpdateStateOnRemoval();
4569 return true;
4570 }
4571 return false;
4572}
4573
Greg Claytond9e416c2012-02-18 05:35:26 +00004574lldb::TargetSP
4575Process::CalculateTarget ()
4576{
4577 return m_target.shared_from_this();
4578}
4579
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004580void
Greg Clayton0603aa92010-10-04 01:05:56 +00004581Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004582{
Greg Claytonc14ee322011-09-22 04:58:26 +00004583 exe_ctx.SetTargetPtr (&m_target);
4584 exe_ctx.SetProcessPtr (this);
4585 exe_ctx.SetThreadPtr(NULL);
4586 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004587}
4588
Greg Claytone996fd32011-03-08 22:40:15 +00004589//uint32_t
4590//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4591//{
4592// return 0;
4593//}
4594//
4595//ArchSpec
4596//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4597//{
4598// return Host::GetArchSpecForExistingProcess (pid);
4599//}
4600//
4601//ArchSpec
4602//Process::GetArchSpecForExistingProcess (const char *process_name)
4603//{
4604// return Host::GetArchSpecForExistingProcess (process_name);
4605//}
4606//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004607void
4608Process::AppendSTDOUT (const char * s, size_t len)
4609{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004610 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004611 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004612 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004613}
4614
4615void
Greg Clayton93e86192011-11-13 04:45:22 +00004616Process::AppendSTDERR (const char * s, size_t len)
4617{
4618 Mutex::Locker locker (m_stdio_communication_mutex);
4619 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004620 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004621}
4622
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004623void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004624Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004625{
4626 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004627 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004628 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4629}
4630
4631size_t
4632Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4633{
4634 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004635 if (m_profile_data.empty())
4636 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004637
4638 std::string &one_profile_data = m_profile_data.front();
4639 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004640 if (bytes_available > 0)
4641 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004642 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004643 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004644 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004645 if (bytes_available > buf_size)
4646 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004647 memcpy(buf, one_profile_data.c_str(), buf_size);
4648 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004649 bytes_available = buf_size;
4650 }
4651 else
4652 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004653 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004654 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004655 }
4656 }
4657 return bytes_available;
4658}
4659
4660
Greg Clayton93e86192011-11-13 04:45:22 +00004661//------------------------------------------------------------------
4662// Process STDIO
4663//------------------------------------------------------------------
4664
4665size_t
4666Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4667{
4668 Mutex::Locker locker(m_stdio_communication_mutex);
4669 size_t bytes_available = m_stdout_data.size();
4670 if (bytes_available > 0)
4671 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004672 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004673 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004674 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004675 if (bytes_available > buf_size)
4676 {
4677 memcpy(buf, m_stdout_data.c_str(), buf_size);
4678 m_stdout_data.erase(0, buf_size);
4679 bytes_available = buf_size;
4680 }
4681 else
4682 {
4683 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4684 m_stdout_data.clear();
4685 }
4686 }
4687 return bytes_available;
4688}
4689
4690
4691size_t
4692Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4693{
4694 Mutex::Locker locker(m_stdio_communication_mutex);
4695 size_t bytes_available = m_stderr_data.size();
4696 if (bytes_available > 0)
4697 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004698 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004699 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004700 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004701 if (bytes_available > buf_size)
4702 {
4703 memcpy(buf, m_stderr_data.c_str(), buf_size);
4704 m_stderr_data.erase(0, buf_size);
4705 bytes_available = buf_size;
4706 }
4707 else
4708 {
4709 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4710 m_stderr_data.clear();
4711 }
4712 }
4713 return bytes_available;
4714}
4715
4716void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004717Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4718{
4719 Process *process = (Process *) baton;
4720 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4721}
4722
Greg Clayton44d93782014-01-27 23:43:24 +00004723class IOHandlerProcessSTDIO :
4724 public IOHandler
4725{
4726public:
4727 IOHandlerProcessSTDIO (Process *process,
4728 int write_fd) :
4729 IOHandler(process->GetTarget().GetDebugger()),
4730 m_process (process),
4731 m_read_file (),
4732 m_write_file (write_fd, false),
4733 m_pipe_read(),
4734 m_pipe_write()
4735 {
4736 m_read_file.SetDescriptor(GetInputFD(), false);
4737 }
4738
4739 virtual
4740 ~IOHandlerProcessSTDIO ()
4741 {
4742
4743 }
4744
4745 bool
4746 OpenPipes ()
4747 {
4748 if (m_pipe_read.IsValid() && m_pipe_write.IsValid())
4749 return true;
4750
4751 int fds[2];
Deepak Panickal914b8d92014-01-31 18:48:46 +00004752#ifdef _MSC_VER
4753 // pipe is not supported on windows so default to a fail condition
4754 int err = 1;
4755#else
Greg Clayton44d93782014-01-27 23:43:24 +00004756 int err = pipe(fds);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004757#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004758 if (err == 0)
4759 {
4760 m_pipe_read.SetDescriptor(fds[0], true);
4761 m_pipe_write.SetDescriptor(fds[1], true);
4762 return true;
4763 }
4764 return false;
4765 }
4766
4767 void
4768 ClosePipes()
4769 {
4770 m_pipe_read.Close();
4771 m_pipe_write.Close();
4772 }
4773
4774 // Each IOHandler gets to run until it is done. It should read data
4775 // from the "in" and place output into "out" and "err and return
4776 // when done.
4777 virtual void
4778 Run ()
4779 {
4780 if (m_read_file.IsValid() && m_write_file.IsValid())
4781 {
4782 SetIsDone(false);
4783 if (OpenPipes())
4784 {
4785 const int read_fd = m_read_file.GetDescriptor();
4786 const int pipe_read_fd = m_pipe_read.GetDescriptor();
4787 TerminalState terminal_state;
4788 terminal_state.Save (read_fd, false);
4789 Terminal terminal(read_fd);
4790 terminal.SetCanonical(false);
4791 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004792// FD_ZERO, FD_SET are not supported on windows
4793#ifndef _MSC_VER
Greg Clayton44d93782014-01-27 23:43:24 +00004794 while (!GetIsDone())
4795 {
4796 fd_set read_fdset;
4797 FD_ZERO (&read_fdset);
4798 FD_SET (read_fd, &read_fdset);
4799 FD_SET (pipe_read_fd, &read_fdset);
4800 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4801 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4802 if (num_set_fds < 0)
4803 {
4804 const int select_errno = errno;
4805
4806 if (select_errno != EINTR)
4807 SetIsDone(true);
4808 }
4809 else if (num_set_fds > 0)
4810 {
4811 char ch = 0;
4812 size_t n;
4813 if (FD_ISSET (read_fd, &read_fdset))
4814 {
4815 n = 1;
4816 if (m_read_file.Read(&ch, n).Success() && n == 1)
4817 {
4818 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4819 SetIsDone(true);
4820 }
4821 else
4822 SetIsDone(true);
4823 }
4824 if (FD_ISSET (pipe_read_fd, &read_fdset))
4825 {
4826 // Consume the interrupt byte
4827 n = 1;
4828 m_pipe_read.Read (&ch, n);
Greg Clayton19e11352014-02-26 22:47:33 +00004829 switch (ch)
4830 {
4831 case 'q':
4832 SetIsDone(true);
4833 break;
4834 case 'i':
4835 if (StateIsRunningState(m_process->GetState()))
4836 m_process->Halt();
4837 break;
4838 }
Greg Clayton44d93782014-01-27 23:43:24 +00004839 }
4840 }
4841 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004842#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004843 terminal_state.Restore();
4844
4845 }
4846 else
4847 SetIsDone(true);
4848 }
4849 else
4850 SetIsDone(true);
4851 }
4852
4853 // Hide any characters that have been displayed so far so async
4854 // output can be displayed. Refresh() will be called after the
4855 // output has been displayed.
4856 virtual void
4857 Hide ()
4858 {
4859
4860 }
4861 // Called when the async output has been received in order to update
4862 // the input reader (refresh the prompt and redisplay any current
4863 // line(s) that are being edited
4864 virtual void
4865 Refresh ()
4866 {
4867
4868 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004869
Greg Clayton44d93782014-01-27 23:43:24 +00004870 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004871 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004872 {
4873 size_t n = 1;
Greg Clayton19e11352014-02-26 22:47:33 +00004874 char ch = 'q'; // Send 'q' for quit
Greg Clayton44d93782014-01-27 23:43:24 +00004875 m_pipe_write.Write (&ch, n);
4876 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004877
4878 virtual void
4879 Interrupt ()
4880 {
Greg Clayton19e11352014-02-26 22:47:33 +00004881#ifdef _MSC_VER
4882 // Windows doesn't support pipes, so we will send an async interrupt
4883 // event to stop the process
Greg Claytone68f5d62014-02-24 22:50:57 +00004884 if (StateIsRunningState(m_process->GetState()))
Ed Maste96e51b82014-02-25 14:20:14 +00004885 m_process->SendAsyncInterrupt();
Greg Clayton19e11352014-02-26 22:47:33 +00004886#else
4887 // Do only things that are safe to do in an interrupt context (like in
4888 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4889 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4890 // that was written to the pipe and then call m_process->Halt() from a
4891 // much safer location in code.
4892 size_t n = 1;
4893 char ch = 'i'; // Send 'i' for interrupt
4894 m_pipe_write.Write (&ch, n);
4895#endif
Greg Claytone68f5d62014-02-24 22:50:57 +00004896 }
Greg Clayton44d93782014-01-27 23:43:24 +00004897
4898 virtual void
4899 GotEOF()
4900 {
4901
4902 }
4903
4904protected:
4905 Process *m_process;
4906 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4907 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
4908 File m_pipe_read;
4909 File m_pipe_write;
4910
4911};
4912
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004913void
Greg Clayton44d93782014-01-27 23:43:24 +00004914Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004915{
4916 // First set up the Read Thread for reading/handling process I/O
4917
Greg Clayton44d93782014-01-27 23:43:24 +00004918 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004919
4920 if (conn_ap.get())
4921 {
4922 m_stdio_communication.SetConnection (conn_ap.release());
4923 if (m_stdio_communication.IsConnected())
4924 {
4925 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4926 m_stdio_communication.StartReadThread();
4927
4928 // Now read thread is set up, set up input reader.
4929
4930 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004931 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004932 }
4933 }
4934}
4935
Greg Claytonb4874f12014-02-28 18:22:24 +00004936bool
Greg Clayton44d93782014-01-27 23:43:24 +00004937Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004938{
Greg Clayton44d93782014-01-27 23:43:24 +00004939 IOHandlerSP io_handler_sp (m_process_input_reader);
4940 if (io_handler_sp)
4941 {
4942 io_handler_sp->SetIsDone(false);
4943 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004944 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004945 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004946 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004947}
4948
Greg Claytonb4874f12014-02-28 18:22:24 +00004949bool
Greg Clayton44d93782014-01-27 23:43:24 +00004950Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004951{
Greg Clayton44d93782014-01-27 23:43:24 +00004952 IOHandlerSP io_handler_sp (m_process_input_reader);
4953 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004954 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4955 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004956}
4957
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004958// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004959void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004960Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004961{
Greg Clayton6920b522012-08-22 18:39:03 +00004962 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004963}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004964
Greg Clayton99d0faf2010-11-18 23:32:35 +00004965void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004966Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004967{
Greg Clayton6920b522012-08-22 18:39:03 +00004968 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004969}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004970
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004971ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004972Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004973 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004974 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004975 Stream &errors)
4976{
4977 ExecutionResults return_value = eExecutionSetupError;
4978
Jim Ingham77787032011-01-20 02:03:18 +00004979 if (thread_plan_sp.get() == NULL)
4980 {
4981 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004982 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004983 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004984
4985 if (!thread_plan_sp->ValidatePlan(NULL))
4986 {
4987 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4988 return eExecutionSetupError;
4989 }
4990
Greg Claytonc14ee322011-09-22 04:58:26 +00004991 if (exe_ctx.GetProcessPtr() != this)
4992 {
4993 errors.Printf("RunThreadPlan called on wrong process.");
4994 return eExecutionSetupError;
4995 }
4996
4997 Thread *thread = exe_ctx.GetThreadPtr();
4998 if (thread == NULL)
4999 {
5000 errors.Printf("RunThreadPlan called with invalid thread.");
5001 return eExecutionSetupError;
5002 }
Jim Ingham77787032011-01-20 02:03:18 +00005003
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005004 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5005 // For that to be true the plan can't be private - since private plans suppress themselves in the
5006 // GetCompletedPlan call.
5007
5008 bool orig_plan_private = thread_plan_sp->GetPrivate();
5009 thread_plan_sp->SetPrivate(false);
5010
Jim Ingham444586b2011-01-24 06:34:17 +00005011 if (m_private_state.GetValue() != eStateStopped)
5012 {
5013 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00005014 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005015 }
5016
Jim Ingham66243842011-08-13 00:56:10 +00005017 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005018 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005019 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005020 if (!selected_frame_sp)
5021 {
5022 thread->SetSelectedFrame(0);
5023 selected_frame_sp = thread->GetSelectedFrame();
5024 if (!selected_frame_sp)
5025 {
5026 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
5027 return eExecutionSetupError;
5028 }
5029 }
5030
5031 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005032
5033 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5034 // so we should arrange to reset them as well.
5035
Greg Claytonc14ee322011-09-22 04:58:26 +00005036 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00005037
Jim Ingham66243842011-08-13 00:56:10 +00005038 uint32_t selected_tid;
5039 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005040 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005041 {
5042 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005043 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005044 }
5045 else
5046 {
5047 selected_tid = LLDB_INVALID_THREAD_ID;
5048 }
5049
Jim Ingham372787f2012-04-07 00:00:41 +00005050 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00005051 lldb::StateType old_state;
5052 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005053
Greg Clayton5160ce52013-03-27 23:08:40 +00005054 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00005055 if (Host::GetCurrentThread() == m_private_state_thread)
5056 {
Jim Ingham076b3042012-04-10 01:21:57 +00005057 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5058 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005059 // 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 +00005060 // we are fielding public events here.
5061 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005062 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 +00005063
5064
Jim Ingham372787f2012-04-07 00:00:41 +00005065 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005066
5067 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5068 // returning control here.
5069 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5070 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5071 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5072 // do just what we want.
5073 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5074 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5075 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5076 old_state = m_public_state.GetValue();
5077 m_public_state.SetValueNoLock(eStateStopped);
5078
5079 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005080 StartPrivateStateThread(true);
5081 }
5082
5083 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00005084
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005085 if (options.GetDebug())
5086 {
5087 // In this case, we aren't actually going to run, we just want to stop right away.
5088 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5089 // FIXME: To make this prettier we should invent some stop reason for this, but that
5090 // is only cosmetic, and this functionality is only of use to lldb developers who can
5091 // live with not pretty...
5092 thread->Flush();
5093 return eExecutionStoppedForDebug;
5094 }
5095
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005096 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00005097
Sean Callanana46ec452012-07-11 21:31:24 +00005098 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00005099
Jim Ingham77787032011-01-20 02:03:18 +00005100 {
Sean Callanana46ec452012-07-11 21:31:24 +00005101 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5102 // restored on exit to the function.
5103 //
5104 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5105 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00005106
Sean Callanana46ec452012-07-11 21:31:24 +00005107 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00005108
Jim Inghamf48169b2010-11-30 02:22:11 +00005109 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005110 {
5111 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005112 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005113 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005114 thread->GetIndexID(),
5115 thread->GetID(),
5116 s.GetData());
5117 }
5118
5119 bool got_event;
5120 lldb::EventSP event_sp;
5121 lldb::StateType stop_state = lldb::eStateInvalid;
5122
5123 TimeValue* timeout_ptr = NULL;
5124 TimeValue real_timeout;
5125
Jim Ingham0161b492013-02-09 01:29:05 +00005126 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 +00005127 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005128 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005129 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00005130
Jim Ingham0161b492013-02-09 01:29:05 +00005131 // This is just for accounting:
5132 uint32_t num_resumes = 0;
5133
5134 TimeValue one_thread_timeout = TimeValue::Now();
5135 TimeValue final_timeout = one_thread_timeout;
5136
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005137 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Ingham286fb1e2014-02-28 02:52:06 +00005138 if (!options.GetStopOthers())
5139 {
5140 before_first_timeout = false;
5141 final_timeout.OffsetWithMicroSeconds(timeout_usec);
5142 }
5143 else if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005144 {
5145 // If we are running all threads then we take half the time to run all threads, bounded by
5146 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005147 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00005148 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
5149 else
5150 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00005151 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00005152 if (computed_timeout > default_one_thread_timeout_usec)
5153 computed_timeout = default_one_thread_timeout_usec;
5154 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
5155 }
5156 final_timeout.OffsetWithMicroSeconds (timeout_usec);
5157 }
5158 else
5159 {
5160 if (timeout_usec != 0)
5161 final_timeout.OffsetWithMicroSeconds(timeout_usec);
5162 }
5163
Jim Ingham1460e4b2014-01-10 23:46:59 +00005164 // This isn't going to work if there are unfetched events on the queue.
5165 // Are there cases where we might want to run the remaining events here, and then try to
5166 // call the function? That's probably being too tricky for our own good.
5167
5168 Event *other_events = listener.PeekAtNextEvent();
5169 if (other_events != NULL)
5170 {
5171 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
5172 return eExecutionSetupError;
5173 }
5174
5175 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5176 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5177 // event coalescing to cause us to lose OUR running event...
5178 ForceNextEventDelivery();
5179
Jim Ingham8559a352012-11-26 23:52:18 +00005180 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5181 // So don't call return anywhere within it.
5182
Sean Callanana46ec452012-07-11 21:31:24 +00005183 while (1)
5184 {
5185 // We usually want to resume the process if we get to the top of the loop.
5186 // The only exception is if we get two running events with no intervening
5187 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005188 if (log)
5189 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5190 do_resume,
5191 handle_running_event,
5192 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00005193
Jim Ingham184e9812013-01-15 02:47:48 +00005194 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005195 {
5196 // Do the initial resume and wait for the running event before going further.
5197
Jim Ingham184e9812013-01-15 02:47:48 +00005198 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005199 {
Jim Ingham0161b492013-02-09 01:29:05 +00005200 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005201 Error resume_error = PrivateResume ();
5202 if (!resume_error.Success())
5203 {
Jim Ingham0161b492013-02-09 01:29:05 +00005204 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5205 num_resumes,
5206 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00005207 return_value = eExecutionSetupError;
5208 break;
5209 }
Sean Callanana46ec452012-07-11 21:31:24 +00005210 }
Sean Callanana46ec452012-07-11 21:31:24 +00005211
Jim Ingham0161b492013-02-09 01:29:05 +00005212 TimeValue resume_timeout = TimeValue::Now();
5213 resume_timeout.OffsetWithMicroSeconds(500000);
5214
5215 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005216 if (!got_event)
5217 {
5218 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005219 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5220 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005221
Jim Ingham0161b492013-02-09 01:29:05 +00005222 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005223 return_value = eExecutionSetupError;
5224 break;
5225 }
5226
5227 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005228
Sean Callanana46ec452012-07-11 21:31:24 +00005229 if (stop_state != eStateRunning)
5230 {
Jim Ingham0161b492013-02-09 01:29:05 +00005231 bool restarted = false;
5232
5233 if (stop_state == eStateStopped)
5234 {
5235 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5236 if (log)
5237 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5238 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5239 num_resumes,
5240 StateAsCString(stop_state),
5241 restarted,
5242 do_resume,
5243 handle_running_event);
5244 }
5245
5246 if (restarted)
5247 {
5248 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5249 // event here. But if I do, the best thing is to Halt and then get out of here.
5250 Halt();
5251 }
5252
Jim Ingham35e1bda2012-10-16 21:41:58 +00005253 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5254 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00005255 return_value = eExecutionSetupError;
5256 break;
5257 }
5258
5259 if (log)
5260 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5261 // We need to call the function synchronously, so spin waiting for it to return.
5262 // If we get interrupted while executing, we're going to lose our context, and
5263 // won't be able to gather the result at this point.
5264 // We set the timeout AFTER the resume, since the resume takes some time and we
5265 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005266 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005267 else
5268 {
Sean Callanana46ec452012-07-11 21:31:24 +00005269 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005270 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005271 }
Jim Ingham0161b492013-02-09 01:29:05 +00005272
5273 if (before_first_timeout)
5274 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005275 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005276 timeout_ptr = &one_thread_timeout;
5277 else
5278 {
5279 if (timeout_usec == 0)
5280 timeout_ptr = NULL;
5281 else
5282 timeout_ptr = &final_timeout;
5283 }
5284 }
5285 else
5286 {
5287 if (timeout_usec == 0)
5288 timeout_ptr = NULL;
5289 else
5290 timeout_ptr = &final_timeout;
5291 }
5292
5293 do_resume = true;
5294 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005295
Sean Callanana46ec452012-07-11 21:31:24 +00005296 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005297 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005298
Jim Ingham0f16e732011-02-08 05:20:59 +00005299 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005300 {
Sean Callanana46ec452012-07-11 21:31:24 +00005301 if (timeout_ptr)
5302 {
Matt Kopec676a4872013-02-21 23:55:31 +00005303 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005304 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5305 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005306 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005307 else
Sean Callanana46ec452012-07-11 21:31:24 +00005308 {
5309 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5310 }
5311 }
5312
5313 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5314
5315 if (got_event)
5316 {
5317 if (event_sp.get())
5318 {
5319 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005320 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005321 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005322 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005323 return_value = eExecutionInterrupted;
5324 errors.Printf ("Execution halted by user interrupt.");
5325 if (log)
5326 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005327 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005328 }
5329 else
5330 {
5331 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5332 if (log)
5333 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5334
5335 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005336 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005337 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005338 {
Jim Ingham0161b492013-02-09 01:29:05 +00005339 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005340 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5341 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005342 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005343 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005344 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005345 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5346 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005347 }
5348 else
5349 {
Jim Ingham0161b492013-02-09 01:29:05 +00005350 // If we were restarted, we just need to go back up to fetch another event.
5351 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005352 {
5353 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005354 {
5355 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5356 }
5357 keep_going = true;
5358 do_resume = false;
5359 handle_running_event = true;
5360
Jim Inghamcfc09352012-07-27 23:57:19 +00005361 }
5362 else
5363 {
Jim Ingham0161b492013-02-09 01:29:05 +00005364
5365 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5366 StopReason stop_reason = eStopReasonInvalid;
5367 if (stop_info_sp)
5368 stop_reason = stop_info_sp->GetStopReason();
5369
5370
5371 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5372 // it is OUR plan that is complete?
5373 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005374 {
5375 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005376 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5377 // Now mark this plan as private so it doesn't get reported as the stop reason
5378 // after this point.
5379 if (thread_plan_sp)
5380 thread_plan_sp->SetPrivate (orig_plan_private);
5381 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005382 }
5383 else
5384 {
Jim Ingham0161b492013-02-09 01:29:05 +00005385 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005386 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005387 {
5388 if (log)
5389 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005390 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005391 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005392 {
5393 event_to_broadcast_sp = event_sp;
5394 }
Jim Ingham0161b492013-02-09 01:29:05 +00005395 }
Jim Ingham184e9812013-01-15 02:47:48 +00005396 else
Jim Ingham0161b492013-02-09 01:29:05 +00005397 {
5398 if (log)
5399 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005400 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005401 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005402 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005403 }
Jim Ingham184e9812013-01-15 02:47:48 +00005404 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005405 }
Sean Callanana46ec452012-07-11 21:31:24 +00005406 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005407 }
5408 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005409
Jim Inghamcfc09352012-07-27 23:57:19 +00005410 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005411 // This shouldn't really happen, but sometimes we do get two running events without an
5412 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005413 do_resume = false;
5414 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005415 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005416 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005417
Jim Inghamcfc09352012-07-27 23:57:19 +00005418 default:
5419 if (log)
5420 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5421
5422 if (stop_state == eStateExited)
5423 event_to_broadcast_sp = event_sp;
5424
Sean Callananbf154da2012-08-08 17:35:10 +00005425 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005426 return_value = eExecutionInterrupted;
5427 break;
5428 }
Sean Callanana46ec452012-07-11 21:31:24 +00005429 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005430
Sean Callanana46ec452012-07-11 21:31:24 +00005431 if (keep_going)
5432 continue;
5433 else
5434 break;
5435 }
5436 else
5437 {
5438 if (log)
5439 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5440 return_value = eExecutionInterrupted;
5441 break;
5442 }
5443 }
5444 else
5445 {
5446 // If we didn't get an event that means we've timed out...
5447 // We will interrupt the process here. Depending on what we were asked to do we will
5448 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005449
5450 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005451 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005452 {
Jim Ingham0161b492013-02-09 01:29:05 +00005453 uint64_t remaining_time = final_timeout - TimeValue::Now();
5454 if (before_first_timeout)
5455 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005456 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005457 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005458 else
5459 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005460 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005461 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005462 }
5463 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005464 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005465 "abandoning execution.",
5466 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005467 }
5468
Jim Ingham0161b492013-02-09 01:29:05 +00005469 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5470 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5471 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5472 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5473 // stopped event. That's what this while loop does.
5474
5475 bool back_to_top = true;
5476 uint32_t try_halt_again = 0;
5477 bool do_halt = true;
5478 const uint32_t num_retries = 5;
5479 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005480 {
Jim Ingham0161b492013-02-09 01:29:05 +00005481 Error halt_error;
5482 if (do_halt)
5483 {
5484 if (log)
5485 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5486 halt_error = Halt();
5487 }
5488 if (halt_error.Success())
5489 {
5490 if (log)
5491 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5492
5493 real_timeout = TimeValue::Now();
5494 real_timeout.OffsetWithMicroSeconds(500000);
5495
5496 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005497
Jim Ingham0161b492013-02-09 01:29:05 +00005498 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005499 {
Jim Ingham0161b492013-02-09 01:29:05 +00005500 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5501 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005502 {
Jim Ingham0161b492013-02-09 01:29:05 +00005503 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5504 if (stop_state == lldb::eStateStopped
5505 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5506 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005507 }
5508
Jim Ingham0161b492013-02-09 01:29:05 +00005509 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005510 {
Jim Ingham0161b492013-02-09 01:29:05 +00005511 // Between the time we initiated the Halt and the time we delivered it, the process could have
5512 // already finished its job. Check that here:
5513
5514 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5515 {
5516 if (log)
5517 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5518 "Exiting wait loop.");
5519 return_value = eExecutionCompleted;
5520 back_to_top = false;
5521 break;
5522 }
5523
5524 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5525 {
5526 if (log)
5527 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5528 "Exiting wait loop.");
5529 try_halt_again++;
5530 do_halt = false;
5531 continue;
5532 }
Sean Callanana46ec452012-07-11 21:31:24 +00005533
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005534 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005535 {
5536 if (log)
5537 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5538 return_value = eExecutionInterrupted;
5539 back_to_top = false;
5540 break;
5541 }
5542
5543 if (before_first_timeout)
5544 {
5545 // Set all the other threads to run, and return to the top of the loop, which will continue;
5546 before_first_timeout = false;
5547 thread_plan_sp->SetStopOthers (false);
5548 if (log)
5549 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005550
Jim Ingham0161b492013-02-09 01:29:05 +00005551 back_to_top = true;
5552 break;
5553 }
5554 else
5555 {
5556 // Running all threads failed, so return Interrupted.
5557 if (log)
5558 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5559 return_value = eExecutionInterrupted;
5560 back_to_top = false;
5561 break;
5562 }
Sean Callanana46ec452012-07-11 21:31:24 +00005563 }
5564 }
5565 else
Jim Ingham0161b492013-02-09 01:29:05 +00005566 { if (log)
5567 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5568 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005569 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005570 back_to_top = false;
5571 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005572 }
5573 }
Jim Ingham0161b492013-02-09 01:29:05 +00005574 else
5575 {
5576 try_halt_again++;
5577 continue;
5578 }
Sean Callanana46ec452012-07-11 21:31:24 +00005579 }
Jim Ingham0161b492013-02-09 01:29:05 +00005580
5581 if (!back_to_top || try_halt_again > num_retries)
5582 break;
5583 else
5584 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005585 }
Sean Callanana46ec452012-07-11 21:31:24 +00005586 } // END WAIT LOOP
5587
5588 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5589 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5590 {
5591 StopPrivateStateThread();
5592 Error error;
5593 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005594 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005595 {
5596 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5597 }
5598 m_public_state.SetValueNoLock(old_state);
5599
5600 }
5601
Jim Ingham184e9812013-01-15 02:47:48 +00005602 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5603 // could happen:
5604 // 1) The execution successfully completed
5605 // 2) We hit a breakpoint, and ignore_breakpoints was true
5606 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005607 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5608 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005609
Jim Ingham184e9812013-01-15 02:47:48 +00005610 if (return_value == eExecutionCompleted
5611 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005612 {
5613 thread_plan_sp->RestoreThreadState();
5614 }
Sean Callanana46ec452012-07-11 21:31:24 +00005615
5616 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005617 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005618 {
5619 if (log)
5620 {
5621 StreamString s;
5622 if (event_sp)
5623 event_sp->Dump (&s);
5624 else
5625 {
5626 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5627 }
5628
5629 StreamString ts;
5630
5631 const char *event_explanation = NULL;
5632
5633 do
5634 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005635 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005636 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005637 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005638 break;
5639 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005640 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005641 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005642 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005643 break;
5644 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005645 else
Sean Callanana46ec452012-07-11 21:31:24 +00005646 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005647 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5648
5649 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005650 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005651 event_explanation = "<no event data>";
5652 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005653 }
5654
Jim Inghamcfc09352012-07-27 23:57:19 +00005655 Process *process = event_data->GetProcessSP().get();
5656
5657 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005658 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005659 event_explanation = "<no process>";
5660 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005661 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005662
5663 ThreadList &thread_list = process->GetThreadList();
5664
5665 uint32_t num_threads = thread_list.GetSize();
5666 uint32_t thread_index;
5667
5668 ts.Printf("<%u threads> ", num_threads);
5669
5670 for (thread_index = 0;
5671 thread_index < num_threads;
5672 ++thread_index)
5673 {
5674 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5675
5676 if (!thread)
5677 {
5678 ts.Printf("<?> ");
5679 continue;
5680 }
5681
Daniel Malead01b2952012-11-29 21:49:15 +00005682 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005683 RegisterContext *register_context = thread->GetRegisterContext().get();
5684
5685 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005686 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005687 else
5688 ts.Printf("[ip unknown] ");
5689
5690 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5691 if (stop_info_sp)
5692 {
5693 const char *stop_desc = stop_info_sp->GetDescription();
5694 if (stop_desc)
5695 ts.PutCString (stop_desc);
5696 }
5697 ts.Printf(">");
5698 }
5699
5700 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005701 }
Sean Callanana46ec452012-07-11 21:31:24 +00005702 } while (0);
5703
Jim Inghamcfc09352012-07-27 23:57:19 +00005704 if (event_explanation)
5705 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005706 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005707 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5708 }
5709
Jim Inghame4483cf2013-09-27 01:13:01 +00005710 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005711 {
5712 if (log)
5713 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5714 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5715 thread_plan_sp->SetPrivate (orig_plan_private);
5716 }
5717 else
5718 {
5719 if (log)
5720 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005721 }
5722 }
5723 else if (return_value == eExecutionSetupError)
5724 {
5725 if (log)
5726 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005727
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005728 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005729 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005730 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005731 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005732 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005733 }
5734 else
5735 {
Sean Callanana46ec452012-07-11 21:31:24 +00005736 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005737 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005738 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005739 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5740 return_value = eExecutionCompleted;
5741 }
5742 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5743 {
5744 if (log)
5745 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5746 return_value = eExecutionDiscarded;
5747 }
5748 else
5749 {
5750 if (log)
5751 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005752 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005753 {
5754 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005755 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005756 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5757 thread_plan_sp->SetPrivate (orig_plan_private);
5758 }
5759 }
5760 }
5761
5762 // Thread we ran the function in may have gone away because we ran the target
5763 // Check that it's still there, and if it is put it back in the context. Also restore the
5764 // frame in the context if it is still present.
5765 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5766 if (thread)
5767 {
5768 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5769 }
5770
5771 // Also restore the current process'es selected frame & thread, since this function calling may
5772 // be done behind the user's back.
5773
5774 if (selected_tid != LLDB_INVALID_THREAD_ID)
5775 {
5776 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5777 {
5778 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005779 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005780 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005781 if (old_frame_sp)
5782 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005783 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005784 }
5785 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005786
Sean Callanana46ec452012-07-11 21:31:24 +00005787 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005788
Sean Callanana46ec452012-07-11 21:31:24 +00005789 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005790 {
Sean Callanana46ec452012-07-11 21:31:24 +00005791 if (log)
5792 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5793 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005794 }
5795
5796 return return_value;
5797}
5798
5799const char *
5800Process::ExecutionResultAsCString (ExecutionResults result)
5801{
5802 const char *result_name;
5803
5804 switch (result)
5805 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005806 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005807 result_name = "eExecutionCompleted";
5808 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005809 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005810 result_name = "eExecutionDiscarded";
5811 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005812 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005813 result_name = "eExecutionInterrupted";
5814 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005815 case eExecutionHitBreakpoint:
5816 result_name = "eExecutionHitBreakpoint";
5817 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005818 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005819 result_name = "eExecutionSetupError";
5820 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005821 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005822 result_name = "eExecutionTimedOut";
5823 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005824 case eExecutionStoppedForDebug:
5825 result_name = "eExecutionStoppedForDebug";
5826 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005827 }
5828 return result_name;
5829}
5830
Greg Clayton7260f622011-04-18 08:33:37 +00005831void
5832Process::GetStatus (Stream &strm)
5833{
5834 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005835 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005836 {
5837 if (state == eStateExited)
5838 {
5839 int exit_status = GetExitStatus();
5840 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005841 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005842 GetID(),
5843 exit_status,
5844 exit_status,
5845 exit_description ? exit_description : "");
5846 }
5847 else
5848 {
5849 if (state == eStateConnected)
5850 strm.Printf ("Connected to remote target.\n");
5851 else
Daniel Malead01b2952012-11-29 21:49:15 +00005852 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005853 }
5854 }
5855 else
5856 {
Daniel Malead01b2952012-11-29 21:49:15 +00005857 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005858 }
5859}
5860
5861size_t
5862Process::GetThreadStatus (Stream &strm,
5863 bool only_threads_with_stop_reason,
5864 uint32_t start_frame,
5865 uint32_t num_frames,
5866 uint32_t num_frames_with_source)
5867{
5868 size_t num_thread_infos_dumped = 0;
5869
Jim Ingham41f2b942012-09-10 20:50:15 +00005870 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005871 const size_t num_threads = GetThreadList().GetSize();
5872 for (uint32_t i = 0; i < num_threads; i++)
5873 {
5874 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5875 if (thread)
5876 {
5877 if (only_threads_with_stop_reason)
5878 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005879 StopInfoSP stop_info_sp = thread->GetStopInfo();
5880 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005881 continue;
5882 }
5883 thread->GetStatus (strm,
5884 start_frame,
5885 num_frames,
5886 num_frames_with_source);
5887 ++num_thread_infos_dumped;
5888 }
5889 }
5890 return num_thread_infos_dumped;
5891}
5892
Greg Claytona9f40ad2012-02-22 04:37:26 +00005893void
5894Process::AddInvalidMemoryRegion (const LoadRange &region)
5895{
5896 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5897}
5898
5899bool
5900Process::RemoveInvalidMemoryRange (const LoadRange &region)
5901{
5902 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5903}
5904
Jim Ingham372787f2012-04-07 00:00:41 +00005905void
5906Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5907{
5908 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5909}
5910
5911bool
5912Process::RunPreResumeActions ()
5913{
5914 bool result = true;
5915 while (!m_pre_resume_actions.empty())
5916 {
5917 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5918 m_pre_resume_actions.pop_back();
5919 bool this_result = action.callback (action.baton);
5920 if (result == true) result = this_result;
5921 }
5922 return result;
5923}
5924
5925void
5926Process::ClearPreResumeActions ()
5927{
5928 m_pre_resume_actions.clear();
5929}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005930
Greg Claytonfa559e52012-05-18 02:38:05 +00005931void
5932Process::Flush ()
5933{
5934 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005935 m_extended_thread_list.Flush();
5936 m_extended_thread_stop_id = 0;
5937 m_queue_list.Clear();
5938 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005939}
Greg Clayton90ba8112012-12-05 00:16:59 +00005940
5941void
5942Process::DidExec ()
5943{
5944 Target &target = GetTarget();
5945 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005946 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005947 m_dynamic_checkers_ap.reset();
5948 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005949 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005950 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005951 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005952 m_image_tokens.clear();
5953 m_allocated_memory_cache.Clear();
5954 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005955 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005956 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005957 DoDidExec();
5958 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005959 // Flush the process (threads and all stack frames) after running CompleteAttach()
5960 // in case the dynamic loader loaded things in new locations.
5961 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005962
5963 // After we figure out what was loaded/unloaded in CompleteAttach,
5964 // we need to let the target know so it can do any cleanup it needs to.
5965 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005966}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005967
Jim Ingham1460e4b2014-01-10 23:46:59 +00005968addr_t
5969Process::ResolveIndirectFunction(const Address *address, Error &error)
5970{
5971 if (address == nullptr)
5972 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005973 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005974 return LLDB_INVALID_ADDRESS;
5975 }
5976
5977 addr_t function_addr = LLDB_INVALID_ADDRESS;
5978
5979 addr_t addr = address->GetLoadAddress(&GetTarget());
5980 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5981 if (iter != m_resolved_indirect_addresses.end())
5982 {
5983 function_addr = (*iter).second;
5984 }
5985 else
5986 {
5987 if (!InferiorCall(this, address, function_addr))
5988 {
5989 Symbol *symbol = address->CalculateSymbolContextSymbol();
5990 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5991 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5992 function_addr = LLDB_INVALID_ADDRESS;
5993 }
5994 else
5995 {
5996 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5997 }
5998 }
5999 return function_addr;
6000}
6001