blob: 40d3e4950c6d384a66bd045db702296e68fad6c2 [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);
Greg Clayton44d93782014-01-27 23:43:24 +00001526 CancelWatchForSTDIN (true);
Greg Clayton6779606a2011-01-22 23:43:18 +00001527 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001528}
1529
1530// This static callback can be used to watch for local child processes on
1531// the current host. The the child process exits, the process will be
1532// found in the global target list (we want to be completely sure that the
1533// lldb_private::Process doesn't go away before we can deliver the signal.
1534bool
Greg Claytone4e45922011-11-16 05:37:56 +00001535Process::SetProcessExitStatus (void *callback_baton,
1536 lldb::pid_t pid,
1537 bool exited,
1538 int signo, // Zero for no signal
1539 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540)
1541{
Greg Clayton5160ce52013-03-27 23:08:40 +00001542 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001543 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001544 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001545 callback_baton,
1546 pid,
1547 exited,
1548 signo,
1549 exit_status);
1550
1551 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001552 {
Greg Clayton66111032010-06-23 01:19:29 +00001553 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001554 if (target_sp)
1555 {
1556 ProcessSP process_sp (target_sp->GetProcessSP());
1557 if (process_sp)
1558 {
1559 const char *signal_cstr = NULL;
1560 if (signo)
1561 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1562
1563 process_sp->SetExitStatus (exit_status, signal_cstr);
1564 }
1565 }
1566 return true;
1567 }
1568 return false;
1569}
1570
1571
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001572void
1573Process::UpdateThreadListIfNeeded ()
1574{
1575 const uint32_t stop_id = GetStopID();
1576 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1577 {
Greg Clayton2637f822011-11-17 01:23:07 +00001578 const StateType state = GetPrivateState();
1579 if (StateIsStoppedState (state, true))
1580 {
1581 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001582 // m_thread_list does have its own mutex, but we need to
1583 // hold onto the mutex between the call to UpdateThreadList(...)
1584 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001585 ThreadList &old_thread_list = m_thread_list;
1586 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001587 ThreadList new_thread_list(this);
1588 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001589 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001590 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001591 {
Jim Ingham09437922013-03-01 20:04:25 +00001592 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1593 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1594 // shutting us down, causing a deadlock.
1595 if (!m_destroy_in_process)
1596 {
1597 OperatingSystem *os = GetOperatingSystem ();
1598 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001599 {
1600 // Clear any old backing threads where memory threads might have been
1601 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001602 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001603 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001604 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001605
1606 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001607 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1608 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1609 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 +00001610 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001611 else
1612 {
1613 // No OS plug-in, the new thread list is the same as the real thread list
1614 new_thread_list = real_thread_list;
1615 }
Jim Ingham09437922013-03-01 20:04:25 +00001616 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001617
1618 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001619 m_thread_list.Update (new_thread_list);
1620 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001621
Jason Molenda4ff13262013-11-20 00:31:38 +00001622 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1623 {
1624 // Clear any extended threads that we may have accumulated previously
1625 m_extended_thread_list.Clear();
1626 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001627
1628 m_queue_list.Clear();
1629 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001630 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001631 }
Greg Clayton2637f822011-11-17 01:23:07 +00001632 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001633 }
1634}
1635
Jason Molenda5e8dce42013-12-13 00:29:16 +00001636void
1637Process::UpdateQueueListIfNeeded ()
1638{
1639 if (m_system_runtime_ap.get())
1640 {
1641 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1642 {
1643 const StateType state = GetPrivateState();
1644 if (StateIsStoppedState (state, true))
1645 {
1646 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1647 m_queue_list_stop_id = GetLastNaturalStopID();
1648 }
1649 }
1650 }
1651}
1652
Greg Claytona4d87472013-01-18 23:41:08 +00001653ThreadSP
1654Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1655{
1656 OperatingSystem *os = GetOperatingSystem ();
1657 if (os)
1658 return os->CreateThread(tid, context);
1659 return ThreadSP();
1660}
1661
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001662uint32_t
1663Process::GetNextThreadIndexID (uint64_t thread_id)
1664{
1665 return AssignIndexIDToThread(thread_id);
1666}
1667
1668bool
1669Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1670{
1671 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1672 if (iterator == m_thread_id_to_index_id_map.end())
1673 {
1674 return false;
1675 }
1676 else
1677 {
1678 return true;
1679 }
1680}
1681
1682uint32_t
1683Process::AssignIndexIDToThread(uint64_t thread_id)
1684{
1685 uint32_t result = 0;
1686 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1687 if (iterator == m_thread_id_to_index_id_map.end())
1688 {
1689 result = ++m_thread_index_id;
1690 m_thread_id_to_index_id_map[thread_id] = result;
1691 }
1692 else
1693 {
1694 result = iterator->second;
1695 }
1696
1697 return result;
1698}
1699
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001700StateType
1701Process::GetState()
1702{
1703 // If any other threads access this we will need a mutex for it
1704 return m_public_state.GetValue ();
1705}
1706
1707void
Jim Ingham221d51c2013-05-08 00:35:16 +00001708Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001709{
Greg Clayton5160ce52013-03-27 23:08:40 +00001710 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001711 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001712 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001713 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001714 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001715
1716 // On the transition from Run to Stopped, we unlock the writer end of the
1717 // run lock. The lock gets locked in Resume, which is the public API
1718 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001719 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1720 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001721 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001722 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001723 if (log)
1724 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001725 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001726 }
1727 else
1728 {
1729 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1730 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001731 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001732 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001733 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001734 {
1735 if (log)
1736 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001737 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001738 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001739 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001740 }
1741 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742}
1743
Jim Ingham3b8285d2012-04-19 01:40:33 +00001744Error
1745Process::Resume ()
1746{
Greg Clayton5160ce52013-03-27 23:08:40 +00001747 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001748 if (log)
1749 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001750 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001751 {
1752 Error error("Resume request failed - process still running.");
1753 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001754 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001755 return error;
1756 }
1757 return PrivateResume();
1758}
1759
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001760StateType
1761Process::GetPrivateState ()
1762{
1763 return m_private_state.GetValue();
1764}
1765
1766void
1767Process::SetPrivateState (StateType new_state)
1768{
Greg Clayton5160ce52013-03-27 23:08:40 +00001769 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770 bool state_changed = false;
1771
1772 if (log)
1773 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1774
Andrew Kaylor29d65742013-05-10 17:19:04 +00001775 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001776 Mutex::Locker locker(m_private_state.GetMutex());
1777
1778 const StateType old_state = m_private_state.GetValueNoLock ();
1779 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001780
Greg Claytonaa49c832013-05-03 22:25:56 +00001781 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1782 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1783 if (old_state_is_stopped != new_state_is_stopped)
1784 {
1785 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001786 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001787 else
Ed Maste64fad602013-07-29 20:58:06 +00001788 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001789 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001790
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001791 if (state_changed)
1792 {
1793 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001794 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001796 // Note, this currently assumes that all threads in the list
1797 // stop when the process stops. In the future we will want to
1798 // support a debugging model where some threads continue to run
1799 // while others are stopped. When that happens we will either need
1800 // a way for the thread list to identify which threads are stopping
1801 // or create a special thread list containing only threads which
1802 // actually stopped.
1803 //
1804 // The process plugin is responsible for managing the actual
1805 // behavior of the threads and should have stopped any threads
1806 // that are going to stop before we get here.
1807 m_thread_list.DidStop();
1808
Jim Ingham4b536182011-08-09 02:12:22 +00001809 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001810 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001812 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813 }
1814 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001815 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1816 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1817 else
1818 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 }
1820 else
1821 {
1822 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001823 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 }
1825}
1826
Jim Ingham0faa43f2011-11-08 03:00:11 +00001827void
1828Process::SetRunningUserExpression (bool on)
1829{
1830 m_mod_id.SetRunningUserExpression (on);
1831}
1832
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833addr_t
1834Process::GetImageInfoAddress()
1835{
1836 return LLDB_INVALID_ADDRESS;
1837}
1838
Greg Clayton8f343b02010-11-04 01:54:29 +00001839//----------------------------------------------------------------------
1840// LoadImage
1841//
1842// This function provides a default implementation that works for most
1843// unix variants. Any Process subclasses that need to do shared library
1844// loading differently should override LoadImage and UnloadImage and
1845// do what is needed.
1846//----------------------------------------------------------------------
1847uint32_t
1848Process::LoadImage (const FileSpec &image_spec, Error &error)
1849{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001850 char path[PATH_MAX];
1851 image_spec.GetPath(path, sizeof(path));
1852
Greg Clayton8f343b02010-11-04 01:54:29 +00001853 DynamicLoader *loader = GetDynamicLoader();
1854 if (loader)
1855 {
1856 error = loader->CanLoadImage();
1857 if (error.Fail())
1858 return LLDB_INVALID_IMAGE_TOKEN;
1859 }
1860
1861 if (error.Success())
1862 {
1863 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001864
1865 if (thread_sp)
1866 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001867 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001868
1869 if (frame_sp)
1870 {
1871 ExecutionContext exe_ctx;
1872 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001873 EvaluateExpressionOptions expr_options;
1874 expr_options.SetUnwindOnError(true);
1875 expr_options.SetIgnoreBreakpoints(true);
1876 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001877 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001878 expr.Printf("dlopen (\"%s\", 2)", path);
1879 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001880 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001881 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001882 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001883 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001884 expr.GetData(),
1885 prefix,
1886 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001887 expr_error);
1888 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001889 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001890 error = result_valobj_sp->GetError();
1891 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001892 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001893 Scalar scalar;
1894 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001895 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001896 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1897 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1898 {
1899 uint32_t image_token = m_image_tokens.size();
1900 m_image_tokens.push_back (image_ptr);
1901 return image_token;
1902 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001903 }
1904 }
1905 }
1906 }
1907 }
1908 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001909 if (!error.AsCString())
1910 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001911 return LLDB_INVALID_IMAGE_TOKEN;
1912}
1913
1914//----------------------------------------------------------------------
1915// UnloadImage
1916//
1917// This function provides a default implementation that works for most
1918// unix variants. Any Process subclasses that need to do shared library
1919// loading differently should override LoadImage and UnloadImage and
1920// do what is needed.
1921//----------------------------------------------------------------------
1922Error
1923Process::UnloadImage (uint32_t image_token)
1924{
1925 Error error;
1926 if (image_token < m_image_tokens.size())
1927 {
1928 const addr_t image_addr = m_image_tokens[image_token];
1929 if (image_addr == LLDB_INVALID_ADDRESS)
1930 {
1931 error.SetErrorString("image already unloaded");
1932 }
1933 else
1934 {
1935 DynamicLoader *loader = GetDynamicLoader();
1936 if (loader)
1937 error = loader->CanLoadImage();
1938
1939 if (error.Success())
1940 {
1941 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001942
1943 if (thread_sp)
1944 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001945 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001946
1947 if (frame_sp)
1948 {
1949 ExecutionContext exe_ctx;
1950 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001951 EvaluateExpressionOptions expr_options;
1952 expr_options.SetUnwindOnError(true);
1953 expr_options.SetIgnoreBreakpoints(true);
1954 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001955 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001956 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001957 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001958 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001959 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001960 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001961 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001962 expr.GetData(),
1963 prefix,
1964 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001965 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001966 if (result_valobj_sp->GetError().Success())
1967 {
1968 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001969 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001970 {
1971 if (scalar.UInt(1))
1972 {
1973 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1974 }
1975 else
1976 {
1977 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1978 }
1979 }
1980 }
1981 else
1982 {
1983 error = result_valobj_sp->GetError();
1984 }
1985 }
1986 }
1987 }
1988 }
1989 }
1990 else
1991 {
1992 error.SetErrorString("invalid image token");
1993 }
1994 return error;
1995}
1996
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001997const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001998Process::GetABI()
1999{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002000 if (!m_abi_sp)
2001 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2002 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003}
2004
Jim Ingham22777012010-09-23 02:01:19 +00002005LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002006Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002007{
2008 LanguageRuntimeCollection::iterator pos;
2009 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002010 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002011 {
Jim Inghamab175242012-03-10 00:22:19 +00002012 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002013
Jim Inghamab175242012-03-10 00:22:19 +00002014 m_language_runtimes[language] = runtime_sp;
2015 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002016 }
2017 else
2018 return (*pos).second.get();
2019}
2020
2021CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002022Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002023{
Jim Inghamab175242012-03-10 00:22:19 +00002024 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002025 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2026 return static_cast<CPPLanguageRuntime *> (runtime);
2027 return NULL;
2028}
2029
2030ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002031Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002032{
Jim Inghamab175242012-03-10 00:22:19 +00002033 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002034 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2035 return static_cast<ObjCLanguageRuntime *> (runtime);
2036 return NULL;
2037}
2038
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002039bool
2040Process::IsPossibleDynamicValue (ValueObject& in_value)
2041{
2042 if (in_value.IsDynamic())
2043 return false;
2044 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2045
2046 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2047 {
2048 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2049 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2050 }
2051
2052 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2053 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2054 return true;
2055
2056 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2057 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2058}
2059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060BreakpointSiteList &
2061Process::GetBreakpointSiteList()
2062{
2063 return m_breakpoint_site_list;
2064}
2065
2066const BreakpointSiteList &
2067Process::GetBreakpointSiteList() const
2068{
2069 return m_breakpoint_site_list;
2070}
2071
2072
2073void
2074Process::DisableAllBreakpointSites ()
2075{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002076 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2077// bp_site->SetEnabled(true);
2078 DisableBreakpointSite(bp_site);
2079 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080}
2081
2082Error
2083Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2084{
2085 Error error (DisableBreakpointSiteByID (break_id));
2086
2087 if (error.Success())
2088 m_breakpoint_site_list.Remove(break_id);
2089
2090 return error;
2091}
2092
2093Error
2094Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2095{
2096 Error error;
2097 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2098 if (bp_site_sp)
2099 {
2100 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002101 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102 }
2103 else
2104 {
Daniel Malead01b2952012-11-29 21:49:15 +00002105 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106 }
2107
2108 return error;
2109}
2110
2111Error
2112Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2113{
2114 Error error;
2115 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2116 if (bp_site_sp)
2117 {
2118 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002119 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002120 }
2121 else
2122 {
Daniel Malead01b2952012-11-29 21:49:15 +00002123 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124 }
2125 return error;
2126}
2127
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002128lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002129Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002131 addr_t load_addr = LLDB_INVALID_ADDRESS;
2132
2133 bool show_error = true;
2134 switch (GetState())
2135 {
2136 case eStateInvalid:
2137 case eStateUnloaded:
2138 case eStateConnected:
2139 case eStateAttaching:
2140 case eStateLaunching:
2141 case eStateDetached:
2142 case eStateExited:
2143 show_error = false;
2144 break;
2145
2146 case eStateStopped:
2147 case eStateRunning:
2148 case eStateStepping:
2149 case eStateCrashed:
2150 case eStateSuspended:
2151 show_error = IsAlive();
2152 break;
2153 }
2154
2155 // Reset the IsIndirect flag here, in case the location changes from
2156 // pointing to a indirect symbol to a regular symbol.
2157 owner->SetIsIndirect (false);
2158
2159 if (owner->ShouldResolveIndirectFunctions())
2160 {
2161 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2162 if (symbol && symbol->IsIndirect())
2163 {
2164 Error error;
2165 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2166 if (!error.Success() && show_error)
2167 {
Greg Clayton44d93782014-01-27 23:43:24 +00002168 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2169 symbol->GetAddress().GetLoadAddress(&m_target),
2170 owner->GetBreakpoint().GetID(),
2171 owner->GetID(),
2172 error.AsCString() ? error.AsCString() : "unkown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002173 return LLDB_INVALID_BREAK_ID;
2174 }
2175 Address resolved_address(load_addr);
2176 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2177 owner->SetIsIndirect(true);
2178 }
2179 else
2180 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2181 }
2182 else
2183 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2184
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002185 if (load_addr != LLDB_INVALID_ADDRESS)
2186 {
2187 BreakpointSiteSP bp_site_sp;
2188
2189 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2190 // create a new breakpoint site and add it.
2191
2192 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2193
2194 if (bp_site_sp)
2195 {
2196 bp_site_sp->AddOwner (owner);
2197 owner->SetBreakpointSite (bp_site_sp);
2198 return bp_site_sp->GetID();
2199 }
2200 else
2201 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002202 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002203 if (bp_site_sp)
2204 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002205 Error error = EnableBreakpointSite (bp_site_sp.get());
2206 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207 {
2208 owner->SetBreakpointSite (bp_site_sp);
2209 return m_breakpoint_site_list.Add (bp_site_sp);
2210 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002211 else
2212 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002213 if (show_error)
2214 {
2215 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002216 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2217 load_addr,
2218 owner->GetBreakpoint().GetID(),
2219 owner->GetID(),
2220 error.AsCString() ? error.AsCString() : "unkown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002221 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002222 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002223 }
2224 }
2225 }
2226 // We failed to enable the breakpoint
2227 return LLDB_INVALID_BREAK_ID;
2228
2229}
2230
2231void
2232Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2233{
2234 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2235 if (num_owners == 0)
2236 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002237 // Don't try to disable the site if we don't have a live process anymore.
2238 if (IsAlive())
2239 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2241 }
2242}
2243
2244
2245size_t
2246Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2247{
2248 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002249 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002250
Jim Ingham20c77192011-06-29 19:42:28 +00002251 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002253 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2254 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002255 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002256 addr_t intersect_addr;
2257 size_t intersect_size;
2258 size_t opcode_offset;
2259 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002260 {
2261 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2262 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002263 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002264 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002265 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002266 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002267 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002268 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 }
2270 return bytes_removed;
2271}
2272
2273
Greg Claytonded470d2011-03-19 01:12:21 +00002274
2275size_t
2276Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2277{
2278 PlatformSP platform_sp (m_target.GetPlatform());
2279 if (platform_sp)
2280 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2281 return 0;
2282}
2283
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002284Error
2285Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2286{
2287 Error error;
2288 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002289 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290 const addr_t bp_addr = bp_site->GetLoadAddress();
2291 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002292 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 if (bp_site->IsEnabled())
2294 {
2295 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002296 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 +00002297 return error;
2298 }
2299
2300 if (bp_addr == LLDB_INVALID_ADDRESS)
2301 {
2302 error.SetErrorString("BreakpointSite contains an invalid load address.");
2303 return error;
2304 }
2305 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2306 // trap for the breakpoint site
2307 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2308
2309 if (bp_opcode_size == 0)
2310 {
Daniel Malead01b2952012-11-29 21:49:15 +00002311 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 }
2313 else
2314 {
2315 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2316
2317 if (bp_opcode_bytes == NULL)
2318 {
2319 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2320 return error;
2321 }
2322
2323 // Save the original opcode by reading it
2324 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2325 {
2326 // Write a software breakpoint in place of the original opcode
2327 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2328 {
2329 uint8_t verify_bp_opcode_bytes[64];
2330 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2331 {
2332 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2333 {
2334 bp_site->SetEnabled(true);
2335 bp_site->SetType (BreakpointSite::eSoftware);
2336 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002337 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 bp_site->GetID(),
2339 (uint64_t)bp_addr);
2340 }
2341 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002342 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002343 }
2344 else
2345 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2346 }
2347 else
2348 error.SetErrorString("Unable to write breakpoint trap to memory.");
2349 }
2350 else
2351 error.SetErrorString("Unable to read memory at breakpoint address.");
2352 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002353 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002354 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355 bp_site->GetID(),
2356 (uint64_t)bp_addr,
2357 error.AsCString());
2358 return error;
2359}
2360
2361Error
2362Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2363{
2364 Error error;
2365 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002366 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002367 addr_t bp_addr = bp_site->GetLoadAddress();
2368 lldb::user_id_t breakID = bp_site->GetID();
2369 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002370 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371
2372 if (bp_site->IsHardware())
2373 {
2374 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2375 }
2376 else if (bp_site->IsEnabled())
2377 {
2378 const size_t break_op_size = bp_site->GetByteSize();
2379 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2380 if (break_op_size > 0)
2381 {
2382 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002383 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002384 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385 bool break_op_found = false;
2386
2387 // Read the breakpoint opcode
2388 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2389 {
2390 bool verify = false;
2391 // Make sure we have the a breakpoint opcode exists at this address
2392 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2393 {
2394 break_op_found = true;
2395 // We found a valid breakpoint opcode at this address, now restore
2396 // the saved opcode.
2397 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2398 {
2399 verify = true;
2400 }
2401 else
2402 error.SetErrorString("Memory write failed when restoring original opcode.");
2403 }
2404 else
2405 {
2406 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2407 // Set verify to true and so we can check if the original opcode has already been restored
2408 verify = true;
2409 }
2410
2411 if (verify)
2412 {
Greg Claytonc982c762010-07-09 20:39:50 +00002413 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002414 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 // Verify that our original opcode made it back to the inferior
2416 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2417 {
2418 // compare the memory we just read with the original opcode
2419 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2420 {
2421 // SUCCESS
2422 bp_site->SetEnabled(false);
2423 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002424 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 +00002425 return error;
2426 }
2427 else
2428 {
2429 if (break_op_found)
2430 error.SetErrorString("Failed to restore original opcode.");
2431 }
2432 }
2433 else
2434 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2435 }
2436 }
2437 else
2438 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2439 }
2440 }
2441 else
2442 {
2443 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002444 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 +00002445 return error;
2446 }
2447
2448 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002449 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450 bp_site->GetID(),
2451 (uint64_t)bp_addr,
2452 error.AsCString());
2453 return error;
2454
2455}
2456
Greg Clayton58be07b2011-01-07 06:08:19 +00002457// Uncomment to verify memory caching works after making changes to caching code
2458//#define VERIFY_MEMORY_READS
2459
Sean Callanan64c0cf22012-06-07 22:26:42 +00002460size_t
2461Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2462{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002463 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002464 if (!GetDisableMemoryCache())
2465 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002466#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002467 // Memory caching is enabled, with debug verification
2468
2469 if (buf && size)
2470 {
2471 // Uncomment the line below to make sure memory caching is working.
2472 // I ran this through the test suite and got no assertions, so I am
2473 // pretty confident this is working well. If any changes are made to
2474 // memory caching, uncomment the line below and test your changes!
2475
2476 // Verify all memory reads by using the cache first, then redundantly
2477 // reading the same memory from the inferior and comparing to make sure
2478 // everything is exactly the same.
2479 std::string verify_buf (size, '\0');
2480 assert (verify_buf.size() == size);
2481 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2482 Error verify_error;
2483 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2484 assert (cache_bytes_read == verify_bytes_read);
2485 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2486 assert (verify_error.Success() == error.Success());
2487 return cache_bytes_read;
2488 }
2489 return 0;
2490#else // !defined(VERIFY_MEMORY_READS)
2491 // Memory caching is enabled, without debug verification
2492
2493 return m_memory_cache.Read (addr, buf, size, error);
2494#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002495 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002496 else
2497 {
2498 // Memory caching is disabled
2499
2500 return ReadMemoryFromInferior (addr, buf, size, error);
2501 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002502}
Greg Clayton58be07b2011-01-07 06:08:19 +00002503
Greg Clayton4c82d422012-05-18 23:20:01 +00002504size_t
2505Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2506{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002507 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002508 out_str.clear();
2509 addr_t curr_addr = addr;
2510 while (1)
2511 {
2512 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2513 if (length == 0)
2514 break;
2515 out_str.append(buf, length);
2516 // If we got "length - 1" bytes, we didn't get the whole C string, we
2517 // need to read some more characters
2518 if (length == sizeof(buf) - 1)
2519 curr_addr += length;
2520 else
2521 break;
2522 }
2523 return out_str.size();
2524}
2525
Greg Clayton58be07b2011-01-07 06:08:19 +00002526
2527size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002528Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2529 size_t type_width)
2530{
2531 size_t total_bytes_read = 0;
2532 if (dst && max_bytes && type_width && max_bytes >= type_width)
2533 {
2534 // Ensure a null terminator independent of the number of bytes that is read.
2535 memset (dst, 0, max_bytes);
2536 size_t bytes_left = max_bytes - type_width;
2537
2538 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2539 assert(sizeof(terminator) >= type_width &&
2540 "Attempting to validate a string with more than 4 bytes per character!");
2541
2542 addr_t curr_addr = addr;
2543 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2544 char *curr_dst = dst;
2545
2546 error.Clear();
2547 while (bytes_left > 0 && error.Success())
2548 {
2549 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2550 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2551 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2552
2553 if (bytes_read == 0)
2554 break;
2555
2556 // Search for a null terminator of correct size and alignment in bytes_read
2557 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2558 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2559 if (::strncmp(&dst[i], terminator, type_width) == 0)
2560 {
2561 error.Clear();
2562 return i;
2563 }
2564
2565 total_bytes_read += bytes_read;
2566 curr_dst += bytes_read;
2567 curr_addr += bytes_read;
2568 bytes_left -= bytes_read;
2569 }
2570 }
2571 else
2572 {
2573 if (max_bytes)
2574 error.SetErrorString("invalid arguments");
2575 }
2576 return total_bytes_read;
2577}
2578
2579// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2580// null terminators.
2581size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002582Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002583{
2584 size_t total_cstr_len = 0;
2585 if (dst && dst_max_len)
2586 {
Greg Claytone91b7952011-12-15 03:14:23 +00002587 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002588 // NULL out everything just to be safe
2589 memset (dst, 0, dst_max_len);
2590 Error error;
2591 addr_t curr_addr = addr;
2592 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2593 size_t bytes_left = dst_max_len - 1;
2594 char *curr_dst = dst;
2595
2596 while (bytes_left > 0)
2597 {
2598 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2599 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2600 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2601
2602 if (bytes_read == 0)
2603 {
Greg Claytone91b7952011-12-15 03:14:23 +00002604 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002605 dst[total_cstr_len] = '\0';
2606 break;
2607 }
2608 const size_t len = strlen(curr_dst);
2609
2610 total_cstr_len += len;
2611
2612 if (len < bytes_to_read)
2613 break;
2614
2615 curr_dst += bytes_read;
2616 curr_addr += bytes_read;
2617 bytes_left -= bytes_read;
2618 }
2619 }
Greg Claytone91b7952011-12-15 03:14:23 +00002620 else
2621 {
2622 if (dst == NULL)
2623 result_error.SetErrorString("invalid arguments");
2624 else
2625 result_error.Clear();
2626 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002627 return total_cstr_len;
2628}
2629
2630size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002631Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2632{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633 if (buf == NULL || size == 0)
2634 return 0;
2635
2636 size_t bytes_read = 0;
2637 uint8_t *bytes = (uint8_t *)buf;
2638
2639 while (bytes_read < size)
2640 {
2641 const size_t curr_size = size - bytes_read;
2642 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2643 bytes + bytes_read,
2644 curr_size,
2645 error);
2646 bytes_read += curr_bytes_read;
2647 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2648 break;
2649 }
2650
2651 // Replace any software breakpoint opcodes that fall into this range back
2652 // into "buf" before we return
2653 if (bytes_read > 0)
2654 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2655 return bytes_read;
2656}
2657
Greg Clayton58a4c462010-12-16 20:01:20 +00002658uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002659Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002660{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002661 Scalar scalar;
2662 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2663 return scalar.ULongLong(fail_value);
2664 return fail_value;
2665}
2666
2667addr_t
2668Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2669{
2670 Scalar scalar;
2671 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2672 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2673 return LLDB_INVALID_ADDRESS;
2674}
2675
2676
2677bool
2678Process::WritePointerToMemory (lldb::addr_t vm_addr,
2679 lldb::addr_t ptr_value,
2680 Error &error)
2681{
2682 Scalar scalar;
2683 const uint32_t addr_byte_size = GetAddressByteSize();
2684 if (addr_byte_size <= 4)
2685 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002686 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002687 scalar = ptr_value;
2688 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002689}
2690
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691size_t
2692Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2693{
2694 size_t bytes_written = 0;
2695 const uint8_t *bytes = (const uint8_t *)buf;
2696
2697 while (bytes_written < size)
2698 {
2699 const size_t curr_size = size - bytes_written;
2700 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2701 bytes + bytes_written,
2702 curr_size,
2703 error);
2704 bytes_written += curr_bytes_written;
2705 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2706 break;
2707 }
2708 return bytes_written;
2709}
2710
2711size_t
2712Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2713{
Greg Clayton58be07b2011-01-07 06:08:19 +00002714#if defined (ENABLE_MEMORY_CACHING)
2715 m_memory_cache.Flush (addr, size);
2716#endif
2717
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718 if (buf == NULL || size == 0)
2719 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002720
Jim Ingham4b536182011-08-09 02:12:22 +00002721 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002722
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002723 // We need to write any data that would go where any current software traps
2724 // (enabled software breakpoints) any software traps (breakpoints) that we
2725 // may have placed in our tasks memory.
2726
Greg Claytond8cf1a12013-06-12 00:46:38 +00002727 BreakpointSiteList bp_sites_in_range;
2728
2729 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002730 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002731 // No breakpoint sites overlap
2732 if (bp_sites_in_range.IsEmpty())
2733 return WriteMemoryPrivate (addr, buf, size, error);
2734 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002736 const uint8_t *ubuf = (const uint8_t *)buf;
2737 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738
Greg Claytond8cf1a12013-06-12 00:46:38 +00002739 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2740
2741 if (error.Success())
2742 {
2743 addr_t intersect_addr;
2744 size_t intersect_size;
2745 size_t opcode_offset;
2746 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2747 assert(intersects);
2748 assert(addr <= intersect_addr && intersect_addr < addr + size);
2749 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2750 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2751
2752 // Check for bytes before this breakpoint
2753 const addr_t curr_addr = addr + bytes_written;
2754 if (intersect_addr > curr_addr)
2755 {
2756 // There are some bytes before this breakpoint that we need to
2757 // just write to memory
2758 size_t curr_size = intersect_addr - curr_addr;
2759 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2760 ubuf + bytes_written,
2761 curr_size,
2762 error);
2763 bytes_written += curr_bytes_written;
2764 if (curr_bytes_written != curr_size)
2765 {
2766 // We weren't able to write all of the requested bytes, we
2767 // are done looping and will return the number of bytes that
2768 // we have written so far.
2769 if (error.Success())
2770 error.SetErrorToGenericError();
2771 }
2772 }
2773 // Now write any bytes that would cover up any software breakpoints
2774 // directly into the breakpoint opcode buffer
2775 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2776 bytes_written += intersect_size;
2777 }
2778 });
2779
2780 if (bytes_written < size)
2781 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2782 ubuf + bytes_written,
2783 size - bytes_written,
2784 error);
2785 }
2786 }
2787 else
2788 {
2789 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002790 }
2791
2792 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002793 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002794}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002795
2796size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002797Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002798{
2799 if (byte_size == UINT32_MAX)
2800 byte_size = scalar.GetByteSize();
2801 if (byte_size > 0)
2802 {
2803 uint8_t buf[32];
2804 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2805 if (mem_size > 0)
2806 return WriteMemory(addr, buf, mem_size, error);
2807 else
2808 error.SetErrorString ("failed to get scalar as memory data");
2809 }
2810 else
2811 {
2812 error.SetErrorString ("invalid scalar value");
2813 }
2814 return 0;
2815}
2816
2817size_t
2818Process::ReadScalarIntegerFromMemory (addr_t addr,
2819 uint32_t byte_size,
2820 bool is_signed,
2821 Scalar &scalar,
2822 Error &error)
2823{
Greg Clayton7060f892013-05-01 23:41:30 +00002824 uint64_t uval = 0;
2825 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002826 {
Greg Clayton7060f892013-05-01 23:41:30 +00002827 error.SetErrorString ("byte size is zero");
2828 }
2829 else if (byte_size & (byte_size - 1))
2830 {
2831 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2832 }
2833 else if (byte_size <= sizeof(uval))
2834 {
2835 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002836 if (bytes_read == byte_size)
2837 {
2838 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002839 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002840 if (byte_size <= 4)
2841 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002842 else
Greg Clayton7060f892013-05-01 23:41:30 +00002843 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002844 if (is_signed)
2845 scalar.SignExtend(byte_size * 8);
2846 return bytes_read;
2847 }
2848 }
2849 else
2850 {
2851 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2852 }
2853 return 0;
2854}
2855
Greg Claytond495c532011-05-17 03:37:42 +00002856#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857addr_t
2858Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2859{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002860 if (GetPrivateState() != eStateStopped)
2861 return LLDB_INVALID_ADDRESS;
2862
Greg Claytond495c532011-05-17 03:37:42 +00002863#if defined (USE_ALLOCATE_MEMORY_CACHE)
2864 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2865#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002866 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002867 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002868 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002869 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 +00002870 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002871 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002872 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002873 m_mod_id.GetStopID(),
2874 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002875 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002876#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002877}
2878
Sean Callanan90539452011-09-20 23:01:51 +00002879bool
2880Process::CanJIT ()
2881{
Sean Callanana7b443a2012-02-14 22:50:38 +00002882 if (m_can_jit == eCanJITDontKnow)
2883 {
2884 Error err;
2885
2886 uint64_t allocated_memory = AllocateMemory(8,
2887 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2888 err);
2889
2890 if (err.Success())
2891 m_can_jit = eCanJITYes;
2892 else
2893 m_can_jit = eCanJITNo;
2894
2895 DeallocateMemory (allocated_memory);
2896 }
2897
Sean Callanan90539452011-09-20 23:01:51 +00002898 return m_can_jit == eCanJITYes;
2899}
2900
2901void
2902Process::SetCanJIT (bool can_jit)
2903{
2904 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2905}
2906
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002907Error
2908Process::DeallocateMemory (addr_t ptr)
2909{
Greg Claytond495c532011-05-17 03:37:42 +00002910 Error error;
2911#if defined (USE_ALLOCATE_MEMORY_CACHE)
2912 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2913 {
Daniel Malead01b2952012-11-29 21:49:15 +00002914 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002915 }
2916#else
2917 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002918
Greg Clayton5160ce52013-03-27 23:08:40 +00002919 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002920 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002921 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 +00002922 ptr,
2923 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002924 m_mod_id.GetStopID(),
2925 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002926#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002927 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002928}
2929
Han Ming Ongc811d382012-11-17 00:33:14 +00002930
Greg Claytonc9660542012-02-05 02:38:54 +00002931ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002932Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002933 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002934{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002935 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002936 if (module_sp)
2937 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002938 Error error;
2939 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2940 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002941 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002942 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002943 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002944}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945
2946Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002947Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948{
2949 Error error;
2950 error.SetErrorString("watchpoints are not supported");
2951 return error;
2952}
2953
2954Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002955Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002956{
2957 Error error;
2958 error.SetErrorString("watchpoints are not supported");
2959 return error;
2960}
2961
2962StateType
2963Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2964{
2965 StateType state;
2966 // Now wait for the process to launch and return control to us, and then
2967 // call DidLaunch:
2968 while (1)
2969 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002970 event_sp.reset();
2971 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2972
Greg Clayton2637f822011-11-17 01:23:07 +00002973 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002974 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002975
2976 // If state is invalid, then we timed out
2977 if (state == eStateInvalid)
2978 break;
2979
2980 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002981 HandlePrivateEvent (event_sp);
2982 }
2983 return state;
2984}
2985
2986Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002987Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002988{
2989 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002990 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002991 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002992 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002993 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002994 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995
Greg Claytonaa149cb2011-08-11 02:48:45 +00002996 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 if (exe_module)
2998 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002999 char local_exec_file_path[PATH_MAX];
3000 char platform_exec_file_path[PATH_MAX];
3001 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3002 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003003 if (exe_module->GetFileSpec().Exists())
3004 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003005 // Install anything that might need to be installed prior to launching.
3006 // For host systems, this will do nothing, but if we are connected to a
3007 // remote platform it will install any needed binaries
3008 error = GetTarget().Install(&launch_info);
3009 if (error.Fail())
3010 return error;
3011
Greg Clayton71337622011-02-24 22:24:29 +00003012 if (PrivateStateThreadIsValid ())
3013 PausePrivateStateThread ();
3014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 error = WillLaunch (exe_module);
3016 if (error.Success())
3017 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003018 const bool restarted = false;
3019 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003020 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021
Ed Maste64fad602013-07-29 20:58:06 +00003022 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003023 {
3024 // Now launch using these arguments.
3025 error = DoLaunch (exe_module, launch_info);
3026 }
3027 else
3028 {
3029 // This shouldn't happen
3030 error.SetErrorString("failed to acquire process run lock");
3031 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032
3033 if (error.Fail())
3034 {
3035 if (GetID() != LLDB_INVALID_PROCESS_ID)
3036 {
3037 SetID (LLDB_INVALID_PROCESS_ID);
3038 const char *error_string = error.AsCString();
3039 if (error_string == NULL)
3040 error_string = "launch failed";
3041 SetExitStatus (-1, error_string);
3042 }
3043 }
3044 else
3045 {
3046 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003047 TimeValue timeout_time;
3048 timeout_time = TimeValue::Now();
3049 timeout_time.OffsetWithSeconds(10);
3050 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051
Greg Clayton1a38ea72011-06-22 01:42:17 +00003052 if (state == eStateInvalid || event_sp.get() == NULL)
3053 {
3054 // We were able to launch the process, but we failed to
3055 // catch the initial stop.
3056 SetExitStatus (0, "failed to catch stop after launch");
3057 Destroy();
3058 }
3059 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003061
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062 DidLaunch ();
3063
Greg Claytonc859e2d2012-02-13 23:10:39 +00003064 DynamicLoader *dyld = GetDynamicLoader ();
3065 if (dyld)
3066 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003067
Jason Molendaeef51062013-11-05 03:57:19 +00003068 SystemRuntime *system_runtime = GetSystemRuntime ();
3069 if (system_runtime)
3070 system_runtime->DidLaunch();
3071
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003072 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073 // This delays passing the stopped event to listeners till DidLaunch gets
3074 // a chance to complete...
3075 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00003076
3077 if (PrivateStateThreadIsValid ())
3078 ResumePrivateStateThread ();
3079 else
3080 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 }
3082 else if (state == eStateExited)
3083 {
3084 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3085 // not likely to work, and return an invalid pid.
3086 HandlePrivateEvent (event_sp);
3087 }
3088 }
3089 }
3090 }
3091 else
3092 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003093 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003094 }
3095 }
3096 return error;
3097}
3098
Greg Claytonc3776bf2012-02-09 06:16:32 +00003099
3100Error
3101Process::LoadCore ()
3102{
3103 Error error = DoLoadCore();
3104 if (error.Success())
3105 {
3106 if (PrivateStateThreadIsValid ())
3107 ResumePrivateStateThread ();
3108 else
3109 StartPrivateStateThread ();
3110
Greg Claytonc859e2d2012-02-13 23:10:39 +00003111 DynamicLoader *dyld = GetDynamicLoader ();
3112 if (dyld)
3113 dyld->DidAttach();
3114
Jason Molendaeef51062013-11-05 03:57:19 +00003115 SystemRuntime *system_runtime = GetSystemRuntime ();
3116 if (system_runtime)
3117 system_runtime->DidAttach();
3118
Greg Claytonc859e2d2012-02-13 23:10:39 +00003119 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003120 // We successfully loaded a core file, now pretend we stopped so we can
3121 // show all of the threads in the core file and explore the crashed
3122 // state.
3123 SetPrivateState (eStateStopped);
3124
3125 }
3126 return error;
3127}
3128
Greg Claytonc859e2d2012-02-13 23:10:39 +00003129DynamicLoader *
3130Process::GetDynamicLoader ()
3131{
3132 if (m_dyld_ap.get() == NULL)
3133 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3134 return m_dyld_ap.get();
3135}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003136
Jason Molendaeef51062013-11-05 03:57:19 +00003137SystemRuntime *
3138Process::GetSystemRuntime ()
3139{
3140 if (m_system_runtime_ap.get() == NULL)
3141 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3142 return m_system_runtime_ap.get();
3143}
3144
Greg Claytonc3776bf2012-02-09 06:16:32 +00003145
Jim Inghambb3a2832011-01-29 01:49:25 +00003146Process::NextEventAction::EventActionResult
3147Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148{
Jim Inghambb3a2832011-01-29 01:49:25 +00003149 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3150 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003151 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003152 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003153 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003154 return eEventActionRetry;
3155
3156 case eStateStopped:
3157 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003158 {
3159 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003160 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003161 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003162 // We don't want these events to be reported, so go set the ShouldReportStop here:
3163 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3164
Greg Claytonc9ed4782011-11-12 02:10:56 +00003165 if (m_exec_count > 0)
3166 {
3167 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003168 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003169 return eEventActionRetry;
3170 }
3171 else
3172 {
3173 m_process->CompleteAttach ();
3174 return eEventActionSuccess;
3175 }
3176 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003177 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003178
Greg Clayton513c26c2011-01-29 07:10:55 +00003179 default:
3180 case eStateExited:
3181 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003182 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003183 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003184
3185 m_exit_string.assign ("No valid Process");
3186 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003187}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003188
Jim Inghambb3a2832011-01-29 01:49:25 +00003189Process::NextEventAction::EventActionResult
3190Process::AttachCompletionHandler::HandleBeingInterrupted()
3191{
3192 return eEventActionSuccess;
3193}
3194
3195const char *
3196Process::AttachCompletionHandler::GetExitString ()
3197{
3198 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003199}
3200
3201Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003202Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003203{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003205 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003206 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003207 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003208 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003209
Greg Clayton144f3a92011-11-15 03:53:30 +00003210 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003211 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003212 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003213 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003214 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003215
Greg Clayton144f3a92011-11-15 03:53:30 +00003216 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003217 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003218 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3219
3220 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003221 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003222 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3223 if (error.Success())
3224 {
Ed Maste64fad602013-07-29 20:58:06 +00003225 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003226 {
3227 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003228 const bool restarted = false;
3229 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003230 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003231 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003232 }
3233 else
3234 {
3235 // This shouldn't happen
3236 error.SetErrorString("failed to acquire process run lock");
3237 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003238
Greg Clayton144f3a92011-11-15 03:53:30 +00003239 if (error.Fail())
3240 {
3241 if (GetID() != LLDB_INVALID_PROCESS_ID)
3242 {
3243 SetID (LLDB_INVALID_PROCESS_ID);
3244 if (error.AsCString() == NULL)
3245 error.SetErrorString("attach failed");
3246
3247 SetExitStatus(-1, error.AsCString());
3248 }
3249 }
3250 else
3251 {
3252 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3253 StartPrivateStateThread();
3254 }
3255 return error;
3256 }
Greg Claytone996fd32011-03-08 22:40:15 +00003257 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003258 else
Greg Claytone996fd32011-03-08 22:40:15 +00003259 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003260 ProcessInstanceInfoList process_infos;
3261 PlatformSP platform_sp (m_target.GetPlatform ());
3262
3263 if (platform_sp)
3264 {
3265 ProcessInstanceInfoMatch match_info;
3266 match_info.GetProcessInfo() = attach_info;
3267 match_info.SetNameMatchType (eNameMatchEquals);
3268 platform_sp->FindProcesses (match_info, process_infos);
3269 const uint32_t num_matches = process_infos.GetSize();
3270 if (num_matches == 1)
3271 {
3272 attach_pid = process_infos.GetProcessIDAtIndex(0);
3273 // Fall through and attach using the above process ID
3274 }
3275 else
3276 {
3277 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3278 if (num_matches > 1)
3279 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3280 else
3281 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3282 }
3283 }
3284 else
3285 {
3286 error.SetErrorString ("invalid platform, can't find processes by name");
3287 return error;
3288 }
Greg Claytone996fd32011-03-08 22:40:15 +00003289 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 }
3291 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003292 {
3293 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003294 }
3295 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003296
3297 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003298 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003299 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003300 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003301 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003302
Ed Maste64fad602013-07-29 20:58:06 +00003303 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003304 {
3305 // Now attach using these arguments.
3306 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003307 const bool restarted = false;
3308 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003309 error = DoAttachToProcessWithID (attach_pid, attach_info);
3310 }
3311 else
3312 {
3313 // This shouldn't happen
3314 error.SetErrorString("failed to acquire process run lock");
3315 }
3316
Greg Clayton144f3a92011-11-15 03:53:30 +00003317 if (error.Success())
3318 {
3319
3320 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3321 StartPrivateStateThread();
3322 }
3323 else
Greg Claytone996fd32011-03-08 22:40:15 +00003324 {
3325 if (GetID() != LLDB_INVALID_PROCESS_ID)
3326 {
3327 SetID (LLDB_INVALID_PROCESS_ID);
3328 const char *error_string = error.AsCString();
3329 if (error_string == NULL)
3330 error_string = "attach failed";
3331
3332 SetExitStatus(-1, error_string);
3333 }
3334 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335 }
3336 }
3337 return error;
3338}
3339
Greg Clayton93d3c8332011-02-16 04:46:07 +00003340void
3341Process::CompleteAttach ()
3342{
3343 // Let the process subclass figure out at much as it can about the process
3344 // before we go looking for a dynamic loader plug-in.
3345 DidAttach();
3346
Jim Ingham4299fdb2011-09-15 01:10:17 +00003347 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3348 // the same as the one we've already set, switch architectures.
3349 PlatformSP platform_sp (m_target.GetPlatform ());
3350 assert (platform_sp.get());
3351 if (platform_sp)
3352 {
Greg Clayton70512312012-05-08 01:45:38 +00003353 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003354 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003355 {
3356 ArchSpec platform_arch;
3357 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3358 if (platform_sp)
3359 {
3360 m_target.SetPlatform (platform_sp);
3361 m_target.SetArchitecture(platform_arch);
3362 }
3363 }
3364 else
3365 {
3366 ProcessInstanceInfo process_info;
3367 platform_sp->GetProcessInfo (GetID(), process_info);
3368 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003369 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003370 m_target.SetArchitecture (process_arch);
3371 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003372 }
3373
3374 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003375 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003376 DynamicLoader *dyld = GetDynamicLoader ();
3377 if (dyld)
3378 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003379
Jason Molendaeef51062013-11-05 03:57:19 +00003380 SystemRuntime *system_runtime = GetSystemRuntime ();
3381 if (system_runtime)
3382 system_runtime->DidAttach();
3383
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003384 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003385 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003386 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003387 Mutex::Locker modules_locker(target_modules.GetMutex());
3388 size_t num_modules = target_modules.GetSize();
3389 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003390
Andy Gibbsa297a972013-06-19 19:04:53 +00003391 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003392 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003393 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003394 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003395 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003396 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003397 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003398 break;
3399 }
3400 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003401 if (new_executable_module_sp)
3402 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003403}
3404
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003405Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003406Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003407{
Greg Claytonb766a732011-02-04 01:58:07 +00003408 m_abi_sp.reset();
3409 m_process_input_reader.reset();
3410
3411 // Find the process and its architecture. Make sure it matches the architecture
3412 // of the current Target, and if not adjust it.
3413
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003414 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003415 if (error.Success())
3416 {
Greg Clayton71337622011-02-24 22:24:29 +00003417 if (GetID() != LLDB_INVALID_PROCESS_ID)
3418 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003419 EventSP event_sp;
3420 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3421
3422 if (state == eStateStopped || state == eStateCrashed)
3423 {
3424 // If we attached and actually have a process on the other end, then
3425 // this ended up being the equivalent of an attach.
3426 CompleteAttach ();
3427
3428 // This delays passing the stopped event to listeners till
3429 // CompleteAttach gets a chance to complete...
3430 HandlePrivateEvent (event_sp);
3431
3432 }
Greg Clayton71337622011-02-24 22:24:29 +00003433 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003434
3435 if (PrivateStateThreadIsValid ())
3436 ResumePrivateStateThread ();
3437 else
3438 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003439 }
3440 return error;
3441}
3442
3443
3444Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003445Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003446{
Greg Clayton5160ce52013-03-27 23:08:40 +00003447 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003448 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003449 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003450 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003451 StateAsCString(m_public_state.GetValue()),
3452 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003453
3454 Error error (WillResume());
3455 // Tell the process it is about to resume before the thread list
3456 if (error.Success())
3457 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003458 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 // can let all of our threads know that they are about to be
3460 // resumed. Threads will each be called with
3461 // Thread::WillResume(StateType) where StateType contains the state
3462 // that they are supposed to have when the process is resumed
3463 // (suspended/running/stepping). Threads should also check
3464 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003465 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003466 if (m_thread_list.WillResume())
3467 {
Jim Ingham372787f2012-04-07 00:00:41 +00003468 // Last thing, do the PreResumeActions.
3469 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003470 {
Jim Ingham0161b492013-02-09 01:29:05 +00003471 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003472 }
3473 else
3474 {
3475 m_mod_id.BumpResumeID();
3476 error = DoResume();
3477 if (error.Success())
3478 {
3479 DidResume();
3480 m_thread_list.DidResume();
3481 if (log)
3482 log->Printf ("Process thinks the process has resumed.");
3483 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484 }
3485 }
3486 else
3487 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003488 // Somebody wanted to run without running. So generate a continue & a stopped event,
3489 // and let the world handle them.
3490 if (log)
3491 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3492
3493 SetPrivateState(eStateRunning);
3494 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003495 }
3496 }
Jim Ingham444586b2011-01-24 06:34:17 +00003497 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003498 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003499 return error;
3500}
3501
3502Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003503Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003504{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003505 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3506 // in case it was already set and some thread plan logic calls halt on its
3507 // own.
3508 m_clear_thread_plans_on_stop |= clear_thread_plans;
3509
Jim Inghamaacc3182012-06-06 00:29:30 +00003510 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3511 // we could just straightaway get another event. It just narrows the window...
3512 m_currently_handling_event.WaitForValueEqualTo(false);
3513
3514
Jim Inghambb3a2832011-01-29 01:49:25 +00003515 // Pause our private state thread so we can ensure no one else eats
3516 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003517 Listener halt_listener ("lldb.process.halt_listener");
3518 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003519
Jim Inghambb3a2832011-01-29 01:49:25 +00003520 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003521 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003522
Greg Clayton513c26c2011-01-29 07:10:55 +00003523 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003524 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003525
Greg Clayton513c26c2011-01-29 07:10:55 +00003526 bool caused_stop = false;
3527
3528 // Ask the process subclass to actually halt our process
3529 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003530 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003531 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003532 if (m_public_state.GetValue() == eStateAttaching)
3533 {
3534 SetExitStatus(SIGKILL, "Cancelled async attach.");
3535 Destroy ();
3536 }
3537 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003538 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003539 // If "caused_stop" is true, then DoHalt stopped the process. If
3540 // "caused_stop" is false, the process was already stopped.
3541 // If the DoHalt caused the process to stop, then we want to catch
3542 // this event and set the interrupted bool to true before we pass
3543 // this along so clients know that the process was interrupted by
3544 // a halt command.
3545 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003546 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003547 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003548 TimeValue timeout_time;
3549 timeout_time = TimeValue::Now();
3550 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003551 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3552 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003553
Jim Ingham0f16e732011-02-08 05:20:59 +00003554 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003555 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003556 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003557 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003558 }
3559 else
3560 {
Greg Clayton2637f822011-11-17 01:23:07 +00003561 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003562 {
3563 // We caused the process to interrupt itself, so mark this
3564 // as such in the stop event so clients can tell an interrupted
3565 // process from a natural stop
3566 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3567 }
3568 else
3569 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003570 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003571 if (log)
3572 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3573 error.SetErrorString ("Did not get stopped event after halt.");
3574 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003575 }
3576 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003577 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003578 }
3579 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003581 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003582 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003583
3584 // Post any event we might have consumed. If all goes well, we will have
3585 // stopped the process, intercepted the event and set the interrupted
3586 // bool in the event. Post it to the private event queue and that will end up
3587 // correctly setting the state.
3588 if (event_sp)
3589 m_private_state_broadcaster.BroadcastEvent(event_sp);
3590
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003591 return error;
3592}
3593
3594Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003595Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3596{
3597 Error error;
3598 if (m_public_state.GetValue() == eStateRunning)
3599 {
3600 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3601 if (log)
3602 log->Printf("Process::Destroy() About to halt.");
3603 error = Halt();
3604 if (error.Success())
3605 {
3606 // Consume the halt event.
3607 TimeValue timeout (TimeValue::Now());
3608 timeout.OffsetWithSeconds(1);
3609 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3610
3611 // If the process exited while we were waiting for it to stop, put the exited event into
3612 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3613 // they don't have a process anymore...
3614
3615 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3616 {
3617 if (log)
3618 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3619 return error;
3620 }
3621 else
3622 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3623
3624 if (state != eStateStopped)
3625 {
3626 if (log)
3627 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3628 // If we really couldn't stop the process then we should just error out here, but if the
3629 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3630 StateType private_state = m_private_state.GetValue();
3631 if (private_state != eStateStopped)
3632 {
3633 return error;
3634 }
3635 }
3636 }
3637 else
3638 {
3639 if (log)
3640 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3641 }
3642 }
3643 return error;
3644}
3645
3646Error
Jim Inghamacff8952013-05-02 00:27:30 +00003647Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003649 EventSP exit_event_sp;
3650 Error error;
3651 m_destroy_in_process = true;
3652
3653 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003654
3655 if (error.Success())
3656 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003657 if (DetachRequiresHalt())
3658 {
3659 error = HaltForDestroyOrDetach (exit_event_sp);
3660 if (!error.Success())
3661 {
3662 m_destroy_in_process = false;
3663 return error;
3664 }
3665 else if (exit_event_sp)
3666 {
3667 // We shouldn't need to do anything else here. There's no process left to detach from...
3668 StopPrivateStateThread();
3669 m_destroy_in_process = false;
3670 return error;
3671 }
3672 }
3673
Jim Inghamacff8952013-05-02 00:27:30 +00003674 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675 if (error.Success())
3676 {
3677 DidDetach();
3678 StopPrivateStateThread();
3679 }
Jim Inghamacff8952013-05-02 00:27:30 +00003680 else
3681 {
3682 return error;
3683 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003684 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003685 m_destroy_in_process = false;
3686
3687 // If we exited when we were waiting for a process to stop, then
3688 // forward the event here so we don't lose the event
3689 if (exit_event_sp)
3690 {
3691 // Directly broadcast our exited event because we shut down our
3692 // private state thread above
3693 BroadcastEvent(exit_event_sp);
3694 }
3695
3696 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3697 // the last events through the event system, in which case we might strand the write lock. Unlock
3698 // it here so when we do to tear down the process we don't get an error destroying the lock.
3699
Ed Maste64fad602013-07-29 20:58:06 +00003700 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003701 return error;
3702}
3703
3704Error
3705Process::Destroy ()
3706{
Jim Ingham09437922013-03-01 20:04:25 +00003707
3708 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3709 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3710 // failed and the process stays around for some reason it won't be in a confused state.
3711
3712 m_destroy_in_process = true;
3713
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003714 Error error (WillDestroy());
3715 if (error.Success())
3716 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003717 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003718 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003719 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003720 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003721 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003722
Jim Inghamaacc3182012-06-06 00:29:30 +00003723 if (m_public_state.GetValue() != eStateRunning)
3724 {
3725 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3726 // kill it, we don't want it hitting a breakpoint...
3727 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3728 // we're not going to have much luck doing this now.
3729 m_thread_list.DiscardThreadPlans();
3730 DisableAllBreakpointSites();
3731 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003732
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733 error = DoDestroy();
3734 if (error.Success())
3735 {
3736 DidDestroy();
3737 StopPrivateStateThread();
3738 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003739 m_stdio_communication.StopReadThread();
3740 m_stdio_communication.Disconnect();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003741 if (m_process_input_reader)
3742 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003743
3744 // If we exited when we were waiting for a process to stop, then
3745 // forward the event here so we don't lose the event
3746 if (exit_event_sp)
3747 {
3748 // Directly broadcast our exited event because we shut down our
3749 // private state thread above
3750 BroadcastEvent(exit_event_sp);
3751 }
3752
Jim Inghamb1e2e842012-04-12 18:49:31 +00003753 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3754 // the last events through the event system, in which case we might strand the write lock. Unlock
3755 // 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 +00003756 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003757 }
Jim Ingham09437922013-03-01 20:04:25 +00003758
3759 m_destroy_in_process = false;
3760
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 return error;
3762}
3763
3764Error
3765Process::Signal (int signal)
3766{
3767 Error error (WillSignal());
3768 if (error.Success())
3769 {
3770 error = DoSignal(signal);
3771 if (error.Success())
3772 DidSignal();
3773 }
3774 return error;
3775}
3776
Greg Clayton514487e2011-02-15 21:59:32 +00003777lldb::ByteOrder
3778Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003779{
Greg Clayton514487e2011-02-15 21:59:32 +00003780 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003781}
3782
3783uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003784Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785{
Greg Clayton514487e2011-02-15 21:59:32 +00003786 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787}
3788
Greg Clayton514487e2011-02-15 21:59:32 +00003789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790bool
3791Process::ShouldBroadcastEvent (Event *event_ptr)
3792{
3793 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3794 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003795 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003796
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003797 switch (state)
3798 {
Greg Claytonb766a732011-02-04 01:58:07 +00003799 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003800 case eStateAttaching:
3801 case eStateLaunching:
3802 case eStateDetached:
3803 case eStateExited:
3804 case eStateUnloaded:
3805 // These events indicate changes in the state of the debugging session, always report them.
3806 return_value = true;
3807 break;
3808 case eStateInvalid:
3809 // We stopped for no apparent reason, don't report it.
3810 return_value = false;
3811 break;
3812 case eStateRunning:
3813 case eStateStepping:
3814 // If we've started the target running, we handle the cases where we
3815 // are already running and where there is a transition from stopped to
3816 // running differently.
3817 // running -> running: Automatically suppress extra running events
3818 // stopped -> running: Report except when there is one or more no votes
3819 // and no yes votes.
3820 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003821 if (m_force_next_event_delivery)
3822 return_value = true;
3823 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003825 switch (m_last_broadcast_state)
3826 {
3827 case eStateRunning:
3828 case eStateStepping:
3829 // We always suppress multiple runnings with no PUBLIC stop in between.
3830 return_value = false;
3831 break;
3832 default:
3833 // TODO: make this work correctly. For now always report
3834 // run if we aren't running so we don't miss any runnning
3835 // events. If I run the lldb/test/thread/a.out file and
3836 // break at main.cpp:58, run and hit the breakpoints on
3837 // multiple threads, then somehow during the stepping over
3838 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003839
Jim Ingham1460e4b2014-01-10 23:46:59 +00003840 // This is a transition from stop to run.
3841 switch (m_thread_list.ShouldReportRun (event_ptr))
3842 {
3843 case eVoteYes:
3844 case eVoteNoOpinion:
3845 return_value = true;
3846 break;
3847 case eVoteNo:
3848 return_value = false;
3849 break;
3850 }
3851 break;
3852 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003853 }
3854 break;
3855 case eStateStopped:
3856 case eStateCrashed:
3857 case eStateSuspended:
3858 {
3859 // We've stopped. First see if we're going to restart the target.
3860 // If we are going to stop, then we always broadcast the event.
3861 // 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 +00003862 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003863
Jim Inghamcb4ca112012-05-16 01:32:14 +00003864 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003865 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003867 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003868 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3869 event_ptr,
3870 StateAsCString(state));
3871 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003872 }
3873 else
3874 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003875 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3876 bool should_resume = false;
3877
Jim Ingham0161b492013-02-09 01:29:05 +00003878 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3879 // Asking the thread list is also not likely to go well, since we are running again.
3880 // So in that case just report the event.
3881
Jim Ingham0161b492013-02-09 01:29:05 +00003882 if (!was_restarted)
3883 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003884
3885 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003886 {
Jim Ingham0161b492013-02-09 01:29:05 +00003887 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3888 if (log)
3889 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3890 should_resume,
3891 StateAsCString(state),
3892 was_restarted,
3893 stop_vote);
3894
3895 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896 {
3897 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003898 return_value = true;
3899 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003901 case eVoteNo:
3902 return_value = false;
3903 break;
3904 }
Jim Ingham0161b492013-02-09 01:29:05 +00003905
Jim Inghamcb95f342012-09-05 21:13:56 +00003906 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003907 {
3908 if (log)
3909 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3910 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003911 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003912 }
3913
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003914 }
3915 else
3916 {
3917 return_value = true;
3918 SynchronouslyNotifyStateChanged (state);
3919 }
3920 }
3921 }
Jim Ingham0161b492013-02-09 01:29:05 +00003922 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003923 }
Jim Ingham0161b492013-02-09 01:29:05 +00003924
Jim Ingham1460e4b2014-01-10 23:46:59 +00003925 // Forcing the next event delivery is a one shot deal. So reset it here.
3926 m_force_next_event_delivery = false;
3927
Jim Ingham0161b492013-02-09 01:29:05 +00003928 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3929 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3930 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3931 // because the PublicState reflects the last event pulled off the queue, and there may be several
3932 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3933 // yet. m_last_broadcast_state gets updated here.
3934
3935 if (return_value)
3936 m_last_broadcast_state = state;
3937
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003938 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003939 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3940 event_ptr,
3941 StateAsCString(state),
3942 StateAsCString(m_last_broadcast_state),
3943 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003944 return return_value;
3945}
3946
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947
3948bool
Jim Ingham372787f2012-04-07 00:00:41 +00003949Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003950{
Greg Clayton5160ce52013-03-27 23:08:40 +00003951 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003952
Greg Clayton8b82f082011-04-12 05:54:46 +00003953 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003954 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003955 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3956
Jim Ingham372787f2012-04-07 00:00:41 +00003957 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003958 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003959
3960 // Create a thread that watches our internal state and controls which
3961 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003962 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003963 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003964 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003965 else
Daniel Malead01b2952012-11-29 21:49:15 +00003966 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003967
3968 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003969 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003970 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3971 if (success)
3972 {
3973 ResumePrivateStateThread();
3974 return true;
3975 }
3976 else
3977 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978}
3979
3980void
3981Process::PausePrivateStateThread ()
3982{
3983 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3984}
3985
3986void
3987Process::ResumePrivateStateThread ()
3988{
3989 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3990}
3991
3992void
3993Process::StopPrivateStateThread ()
3994{
Greg Clayton8b82f082011-04-12 05:54:46 +00003995 if (PrivateStateThreadIsValid ())
3996 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003997 else
3998 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003999 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004000 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004001 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004002 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004003}
4004
4005void
4006Process::ControlPrivateStateThread (uint32_t signal)
4007{
Greg Clayton5160ce52013-03-27 23:08:40 +00004008 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004009
4010 assert (signal == eBroadcastInternalStateControlStop ||
4011 signal == eBroadcastInternalStateControlPause ||
4012 signal == eBroadcastInternalStateControlResume);
4013
4014 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004015 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004017 // Signal the private state thread. First we should copy this is case the
4018 // thread starts exiting since the private state thread will NULL this out
4019 // when it exits
4020 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00004021 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004022 {
4023 TimeValue timeout_time;
4024 bool timed_out;
4025
4026 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4027
4028 timeout_time = TimeValue::Now();
4029 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004030 if (log)
4031 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004032 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4033 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4034
4035 if (signal == eBroadcastInternalStateControlStop)
4036 {
4037 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004038 {
4039 Error error;
4040 Host::ThreadCancel (private_state_thread, &error);
4041 if (log)
4042 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4043 }
4044 else
4045 {
4046 if (log)
4047 log->Printf ("The control event killed the private state thread without having to cancel.");
4048 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004049
4050 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004051 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00004052 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053 }
4054 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004055 else
4056 {
4057 if (log)
4058 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4059 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004060}
4061
4062void
Jim Inghamcfc09352012-07-27 23:57:19 +00004063Process::SendAsyncInterrupt ()
4064{
4065 if (PrivateStateThreadIsValid())
4066 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4067 else
4068 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4069}
4070
4071void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004072Process::HandlePrivateEvent (EventSP &event_sp)
4073{
Greg Clayton5160ce52013-03-27 23:08:40 +00004074 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004075 m_resume_requested = false;
4076
Jim Inghamaacc3182012-06-06 00:29:30 +00004077 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004078
Greg Clayton414f5d32011-01-25 02:58:48 +00004079 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004080
4081 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004082 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004083 {
Jim Ingham754ab982011-01-29 04:05:41 +00004084 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004085 if (log)
4086 log->Printf ("Ran next event action, result was %d.", action_result);
4087
Jim Inghambb3a2832011-01-29 01:49:25 +00004088 switch (action_result)
4089 {
4090 case NextEventAction::eEventActionSuccess:
4091 SetNextEventAction(NULL);
4092 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004093
Jim Inghambb3a2832011-01-29 01:49:25 +00004094 case NextEventAction::eEventActionRetry:
4095 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004096
Jim Inghambb3a2832011-01-29 01:49:25 +00004097 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004098 // Handle Exiting Here. If we already got an exited event,
4099 // we should just propagate it. Otherwise, swallow this event,
4100 // and set our state to exit so the next event will kill us.
4101 if (new_state != eStateExited)
4102 {
4103 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004104 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004105 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004106 SetNextEventAction(NULL);
4107 return;
4108 }
4109 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004110 break;
4111 }
4112 }
4113
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004114 // See if we should broadcast this state to external clients?
4115 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004116
4117 if (should_broadcast)
4118 {
4119 if (log)
4120 {
Daniel Malead01b2952012-11-29 21:49:15 +00004121 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004122 __FUNCTION__,
4123 GetID(),
4124 StateAsCString(new_state),
4125 StateAsCString (GetState ()),
4126 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004127 }
Jim Ingham9575d842011-03-11 03:53:59 +00004128 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004129 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004130 {
4131 // Only push the input handler if we aren't fowarding events,
4132 // as this means the curses GUI is in use...
4133 if (!GetTarget().GetDebugger().IsForwardingEvents())
4134 PushProcessIOHandler ();
4135 }
Jim Inghamb78d73f2013-05-15 01:21:48 +00004136 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Greg Clayton44d93782014-01-27 23:43:24 +00004137 PopProcessIOHandler ();
Jim Ingham9575d842011-03-11 03:53:59 +00004138
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004139 BroadcastEvent (event_sp);
4140 }
4141 else
4142 {
4143 if (log)
4144 {
Daniel Malead01b2952012-11-29 21:49:15 +00004145 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004146 __FUNCTION__,
4147 GetID(),
4148 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004149 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004150 }
4151 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004152 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004153}
4154
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004155thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156Process::PrivateStateThread (void *arg)
4157{
4158 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004159 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004160 return result;
4161}
4162
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004163thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004164Process::RunPrivateStateThread ()
4165{
Jim Ingham076b3042012-04-10 01:21:57 +00004166 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004167 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004168
Greg Clayton5160ce52013-03-27 23:08:40 +00004169 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004170 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004171 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004172
4173 bool exit_now = false;
4174 while (!exit_now)
4175 {
4176 EventSP event_sp;
4177 WaitForEventsPrivate (NULL, event_sp, control_only);
4178 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4179 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004180 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004181 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 +00004182
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183 switch (event_sp->GetType())
4184 {
4185 case eBroadcastInternalStateControlStop:
4186 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187 break; // doing any internal state managment below
4188
4189 case eBroadcastInternalStateControlPause:
4190 control_only = true;
4191 break;
4192
4193 case eBroadcastInternalStateControlResume:
4194 control_only = false;
4195 break;
4196 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004197
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004198 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004199 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004200 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004201 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4202 {
4203 if (m_public_state.GetValue() == eStateAttaching)
4204 {
4205 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004206 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 +00004207 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4208 }
4209 else
4210 {
4211 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004212 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004213 Halt();
4214 }
4215 continue;
4216 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004217
4218 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4219
4220 if (internal_state != eStateInvalid)
4221 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004222 if (m_clear_thread_plans_on_stop &&
4223 StateIsStoppedState(internal_state, true))
4224 {
4225 m_clear_thread_plans_on_stop = false;
4226 m_thread_list.DiscardThreadPlans();
4227 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004228 HandlePrivateEvent (event_sp);
4229 }
4230
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004231 if (internal_state == eStateInvalid ||
4232 internal_state == eStateExited ||
4233 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004234 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004235 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004236 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 +00004237
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004238 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004239 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004240 }
4241
Caroline Tice20ad3c42010-10-29 21:48:37 +00004242 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004243 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004244 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004245
Ed Maste64fad602013-07-29 20:58:06 +00004246 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004247 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4248 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004249 return NULL;
4250}
4251
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004252//------------------------------------------------------------------
4253// Process Event Data
4254//------------------------------------------------------------------
4255
4256Process::ProcessEventData::ProcessEventData () :
4257 EventData (),
4258 m_process_sp (),
4259 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004260 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004261 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004262 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004263{
4264}
4265
4266Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4267 EventData (),
4268 m_process_sp (process_sp),
4269 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004270 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004271 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004272 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004273{
4274}
4275
4276Process::ProcessEventData::~ProcessEventData()
4277{
4278}
4279
4280const ConstString &
4281Process::ProcessEventData::GetFlavorString ()
4282{
4283 static ConstString g_flavor ("Process::ProcessEventData");
4284 return g_flavor;
4285}
4286
4287const ConstString &
4288Process::ProcessEventData::GetFlavor () const
4289{
4290 return ProcessEventData::GetFlavorString ();
4291}
4292
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004293void
4294Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4295{
4296 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004297 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4298 // the public event queue, then other times when we're pretending that this is where we stopped at the
4299 // end of expression evaluation. m_update_state is used to distinguish these
4300 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004301 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004302 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004303 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004304
Jim Ingham221d51c2013-05-08 00:35:16 +00004305 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004306
4307 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4308 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004309 {
4310 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004311 uint32_t num_threads = curr_thread_list.GetSize();
4312 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004313
Jim Ingham4b536182011-08-09 02:12:22 +00004314 // The actions might change one of the thread's stop_info's opinions about whether we should
4315 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004316
4317 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4318 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4319 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4320 // 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
4321 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004322 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004323 for (idx = 0; idx < num_threads; ++idx)
4324 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4325
Jim Inghamc7078c22012-12-13 22:24:15 +00004326 // Use this to track whether we should continue from here. We will only continue the target running if
4327 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4328 // then it doesn't matter what the other threads say...
4329
4330 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004331
Jim Ingham0ad7e052013-04-25 02:04:59 +00004332 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4333 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4334 // thing to do is, and it's better to let the user decide than continue behind their backs.
4335
4336 bool does_anybody_have_an_opinion = false;
4337
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004338 for (idx = 0; idx < num_threads; ++idx)
4339 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004340 curr_thread_list = m_process_sp->GetThreadList();
4341 if (curr_thread_list.GetSize() != num_threads)
4342 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004343 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004344 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004345 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 +00004346 break;
4347 }
4348
4349 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4350
4351 if (thread_sp->GetIndexID() != thread_index_array[idx])
4352 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004353 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004354 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004355 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004356 idx,
4357 thread_index_array[idx],
4358 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004359 break;
4360 }
4361
Jim Inghamb15bfc72010-10-20 00:39:53 +00004362 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004363 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004364 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004365 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004366 bool this_thread_wants_to_stop;
4367 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004368 {
Jim Ingham0161b492013-02-09 01:29:05 +00004369 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4370 }
4371 else
4372 {
4373 stop_info_sp->PerformAction(event_ptr);
4374 // The stop action might restart the target. If it does, then we want to mark that in the
4375 // event so that whoever is receiving it will know to wait for the running event and reflect
4376 // that state appropriately.
4377 // We also need to stop processing actions, since they aren't expecting the target to be running.
4378
4379 // FIXME: we might have run.
4380 if (stop_info_sp->HasTargetRunSinceMe())
4381 {
4382 SetRestarted (true);
4383 break;
4384 }
4385
4386 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004387 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004388
Jim Inghamc7078c22012-12-13 22:24:15 +00004389 if (still_should_stop == false)
4390 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391 }
4392 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004393
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004394
Jim Inghama8ca6e22013-05-03 23:04:37 +00004395 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004396 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004397 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004398 {
4399 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004400 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004401 // Use the public resume method here, since this is just
4402 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004403 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004404 }
4405 else
4406 {
4407 // If we didn't restart, run the Stop Hooks here:
4408 // They might also restart the target, so watch for that.
4409 m_process_sp->GetTarget().RunStopHooks();
4410 if (m_process_sp->GetPrivateState() == eStateRunning)
4411 SetRestarted(true);
4412 }
Jim Ingham9575d842011-03-11 03:53:59 +00004413 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004414 }
4415}
4416
4417void
4418Process::ProcessEventData::Dump (Stream *s) const
4419{
4420 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004421 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004422
Greg Clayton8b82f082011-04-12 05:54:46 +00004423 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004424}
4425
4426const Process::ProcessEventData *
4427Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4428{
4429 if (event_ptr)
4430 {
4431 const EventData *event_data = event_ptr->GetData();
4432 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4433 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4434 }
4435 return NULL;
4436}
4437
4438ProcessSP
4439Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4440{
4441 ProcessSP process_sp;
4442 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4443 if (data)
4444 process_sp = data->GetProcessSP();
4445 return process_sp;
4446}
4447
4448StateType
4449Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4450{
4451 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4452 if (data == NULL)
4453 return eStateInvalid;
4454 else
4455 return data->GetState();
4456}
4457
4458bool
4459Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4460{
4461 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4462 if (data == NULL)
4463 return false;
4464 else
4465 return data->GetRestarted();
4466}
4467
4468void
4469Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4470{
4471 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4472 if (data != NULL)
4473 data->SetRestarted(new_value);
4474}
4475
Jim Ingham0161b492013-02-09 01:29:05 +00004476size_t
4477Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4478{
4479 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4480 if (data != NULL)
4481 return data->GetNumRestartedReasons();
4482 else
4483 return 0;
4484}
4485
4486const char *
4487Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4488{
4489 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4490 if (data != NULL)
4491 return data->GetRestartedReasonAtIndex(idx);
4492 else
4493 return NULL;
4494}
4495
4496void
4497Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4498{
4499 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4500 if (data != NULL)
4501 data->AddRestartedReason(reason);
4502}
4503
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004504bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004505Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4506{
4507 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4508 if (data == NULL)
4509 return false;
4510 else
4511 return data->GetInterrupted ();
4512}
4513
4514void
4515Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4516{
4517 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4518 if (data != NULL)
4519 data->SetInterrupted(new_value);
4520}
4521
4522bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004523Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4524{
4525 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4526 if (data)
4527 {
4528 data->SetUpdateStateOnRemoval();
4529 return true;
4530 }
4531 return false;
4532}
4533
Greg Claytond9e416c2012-02-18 05:35:26 +00004534lldb::TargetSP
4535Process::CalculateTarget ()
4536{
4537 return m_target.shared_from_this();
4538}
4539
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004540void
Greg Clayton0603aa92010-10-04 01:05:56 +00004541Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004542{
Greg Claytonc14ee322011-09-22 04:58:26 +00004543 exe_ctx.SetTargetPtr (&m_target);
4544 exe_ctx.SetProcessPtr (this);
4545 exe_ctx.SetThreadPtr(NULL);
4546 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004547}
4548
Greg Claytone996fd32011-03-08 22:40:15 +00004549//uint32_t
4550//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4551//{
4552// return 0;
4553//}
4554//
4555//ArchSpec
4556//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4557//{
4558// return Host::GetArchSpecForExistingProcess (pid);
4559//}
4560//
4561//ArchSpec
4562//Process::GetArchSpecForExistingProcess (const char *process_name)
4563//{
4564// return Host::GetArchSpecForExistingProcess (process_name);
4565//}
4566//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004567void
4568Process::AppendSTDOUT (const char * s, size_t len)
4569{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004570 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004571 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004572 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004573}
4574
4575void
Greg Clayton93e86192011-11-13 04:45:22 +00004576Process::AppendSTDERR (const char * s, size_t len)
4577{
4578 Mutex::Locker locker (m_stdio_communication_mutex);
4579 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004580 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004581}
4582
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004583void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004584Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004585{
4586 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004587 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004588 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4589}
4590
4591size_t
4592Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4593{
4594 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004595 if (m_profile_data.empty())
4596 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004597
4598 std::string &one_profile_data = m_profile_data.front();
4599 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004600 if (bytes_available > 0)
4601 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004602 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004603 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004604 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004605 if (bytes_available > buf_size)
4606 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004607 memcpy(buf, one_profile_data.c_str(), buf_size);
4608 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004609 bytes_available = buf_size;
4610 }
4611 else
4612 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004613 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004614 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004615 }
4616 }
4617 return bytes_available;
4618}
4619
4620
Greg Clayton93e86192011-11-13 04:45:22 +00004621//------------------------------------------------------------------
4622// Process STDIO
4623//------------------------------------------------------------------
4624
4625size_t
4626Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4627{
4628 Mutex::Locker locker(m_stdio_communication_mutex);
4629 size_t bytes_available = m_stdout_data.size();
4630 if (bytes_available > 0)
4631 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004632 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004633 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004634 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004635 if (bytes_available > buf_size)
4636 {
4637 memcpy(buf, m_stdout_data.c_str(), buf_size);
4638 m_stdout_data.erase(0, buf_size);
4639 bytes_available = buf_size;
4640 }
4641 else
4642 {
4643 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4644 m_stdout_data.clear();
4645 }
4646 }
4647 return bytes_available;
4648}
4649
4650
4651size_t
4652Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4653{
4654 Mutex::Locker locker(m_stdio_communication_mutex);
4655 size_t bytes_available = m_stderr_data.size();
4656 if (bytes_available > 0)
4657 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004658 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004659 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004660 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004661 if (bytes_available > buf_size)
4662 {
4663 memcpy(buf, m_stderr_data.c_str(), buf_size);
4664 m_stderr_data.erase(0, buf_size);
4665 bytes_available = buf_size;
4666 }
4667 else
4668 {
4669 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4670 m_stderr_data.clear();
4671 }
4672 }
4673 return bytes_available;
4674}
4675
4676void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004677Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4678{
4679 Process *process = (Process *) baton;
4680 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4681}
4682
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004683void
Greg Clayton44d93782014-01-27 23:43:24 +00004684Process::ResetProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004685{
4686 m_process_input_reader.reset();
4687}
4688
Greg Clayton44d93782014-01-27 23:43:24 +00004689
4690class IOHandlerProcessSTDIO :
4691 public IOHandler
4692{
4693public:
4694 IOHandlerProcessSTDIO (Process *process,
4695 int write_fd) :
4696 IOHandler(process->GetTarget().GetDebugger()),
4697 m_process (process),
4698 m_read_file (),
4699 m_write_file (write_fd, false),
4700 m_pipe_read(),
4701 m_pipe_write()
4702 {
4703 m_read_file.SetDescriptor(GetInputFD(), false);
4704 }
4705
4706 virtual
4707 ~IOHandlerProcessSTDIO ()
4708 {
4709
4710 }
4711
4712 bool
4713 OpenPipes ()
4714 {
4715 if (m_pipe_read.IsValid() && m_pipe_write.IsValid())
4716 return true;
4717
4718 int fds[2];
Deepak Panickal914b8d92014-01-31 18:48:46 +00004719#ifdef _MSC_VER
4720 // pipe is not supported on windows so default to a fail condition
4721 int err = 1;
4722#else
Greg Clayton44d93782014-01-27 23:43:24 +00004723 int err = pipe(fds);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004724#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004725 if (err == 0)
4726 {
4727 m_pipe_read.SetDescriptor(fds[0], true);
4728 m_pipe_write.SetDescriptor(fds[1], true);
4729 return true;
4730 }
4731 return false;
4732 }
4733
4734 void
4735 ClosePipes()
4736 {
4737 m_pipe_read.Close();
4738 m_pipe_write.Close();
4739 }
4740
4741 // Each IOHandler gets to run until it is done. It should read data
4742 // from the "in" and place output into "out" and "err and return
4743 // when done.
4744 virtual void
4745 Run ()
4746 {
4747 if (m_read_file.IsValid() && m_write_file.IsValid())
4748 {
4749 SetIsDone(false);
4750 if (OpenPipes())
4751 {
4752 const int read_fd = m_read_file.GetDescriptor();
4753 const int pipe_read_fd = m_pipe_read.GetDescriptor();
4754 TerminalState terminal_state;
4755 terminal_state.Save (read_fd, false);
4756 Terminal terminal(read_fd);
4757 terminal.SetCanonical(false);
4758 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004759// FD_ZERO, FD_SET are not supported on windows
4760#ifndef _MSC_VER
Greg Clayton44d93782014-01-27 23:43:24 +00004761 while (!GetIsDone())
4762 {
4763 fd_set read_fdset;
4764 FD_ZERO (&read_fdset);
4765 FD_SET (read_fd, &read_fdset);
4766 FD_SET (pipe_read_fd, &read_fdset);
4767 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4768 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4769 if (num_set_fds < 0)
4770 {
4771 const int select_errno = errno;
4772
4773 if (select_errno != EINTR)
4774 SetIsDone(true);
4775 }
4776 else if (num_set_fds > 0)
4777 {
4778 char ch = 0;
4779 size_t n;
4780 if (FD_ISSET (read_fd, &read_fdset))
4781 {
4782 n = 1;
4783 if (m_read_file.Read(&ch, n).Success() && n == 1)
4784 {
4785 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4786 SetIsDone(true);
4787 }
4788 else
4789 SetIsDone(true);
4790 }
4791 if (FD_ISSET (pipe_read_fd, &read_fdset))
4792 {
4793 // Consume the interrupt byte
4794 n = 1;
4795 m_pipe_read.Read (&ch, n);
4796 SetIsDone(true);
4797 }
4798 }
4799 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004800#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004801 terminal_state.Restore();
4802
4803 }
4804 else
4805 SetIsDone(true);
4806 }
4807 else
4808 SetIsDone(true);
4809 }
4810
4811 // Hide any characters that have been displayed so far so async
4812 // output can be displayed. Refresh() will be called after the
4813 // output has been displayed.
4814 virtual void
4815 Hide ()
4816 {
4817
4818 }
4819 // Called when the async output has been received in order to update
4820 // the input reader (refresh the prompt and redisplay any current
4821 // line(s) that are being edited
4822 virtual void
4823 Refresh ()
4824 {
4825
4826 }
4827 virtual void
4828 Interrupt ()
4829 {
4830 size_t n = 1;
4831 char ch = 'q';
4832 m_pipe_write.Write (&ch, n);
4833 }
4834
4835 virtual void
4836 GotEOF()
4837 {
4838
4839 }
4840
4841protected:
4842 Process *m_process;
4843 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4844 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
4845 File m_pipe_read;
4846 File m_pipe_write;
4847
4848};
4849
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004850void
Greg Clayton44d93782014-01-27 23:43:24 +00004851Process::WatchForSTDIN (IOHandler &io_handler)
4852{
4853}
4854
4855void
4856Process::CancelWatchForSTDIN (bool exited)
4857{
4858 if (m_process_input_reader)
4859 {
4860 if (exited)
4861 m_process_input_reader->SetIsDone(true);
4862 m_process_input_reader->Interrupt();
4863 }
4864}
4865
4866void
4867Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004868{
4869 // First set up the Read Thread for reading/handling process I/O
4870
Greg Clayton44d93782014-01-27 23:43:24 +00004871 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004872
4873 if (conn_ap.get())
4874 {
4875 m_stdio_communication.SetConnection (conn_ap.release());
4876 if (m_stdio_communication.IsConnected())
4877 {
4878 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4879 m_stdio_communication.StartReadThread();
4880
4881 // Now read thread is set up, set up input reader.
4882
4883 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004884 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004885 }
4886 }
4887}
4888
4889void
Greg Clayton44d93782014-01-27 23:43:24 +00004890Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004891{
Greg Clayton44d93782014-01-27 23:43:24 +00004892 IOHandlerSP io_handler_sp (m_process_input_reader);
4893 if (io_handler_sp)
4894 {
4895 io_handler_sp->SetIsDone(false);
4896 m_target.GetDebugger().PushIOHandler (io_handler_sp);
4897 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004898}
4899
4900void
Greg Clayton44d93782014-01-27 23:43:24 +00004901Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004902{
Greg Clayton44d93782014-01-27 23:43:24 +00004903 IOHandlerSP io_handler_sp (m_process_input_reader);
4904 if (io_handler_sp)
4905 {
4906 io_handler_sp->Interrupt();
4907 m_target.GetDebugger().PopIOHandler (io_handler_sp);
4908 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004909}
4910
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004911// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004912void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004913Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004914{
Greg Clayton6920b522012-08-22 18:39:03 +00004915 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004916}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004917
Greg Clayton99d0faf2010-11-18 23:32:35 +00004918void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004919Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004920{
Greg Clayton6920b522012-08-22 18:39:03 +00004921 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004922}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004923
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004924ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004925Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004926 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004927 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004928 Stream &errors)
4929{
4930 ExecutionResults return_value = eExecutionSetupError;
4931
Jim Ingham77787032011-01-20 02:03:18 +00004932 if (thread_plan_sp.get() == NULL)
4933 {
4934 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004935 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004936 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004937
4938 if (!thread_plan_sp->ValidatePlan(NULL))
4939 {
4940 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4941 return eExecutionSetupError;
4942 }
4943
Greg Claytonc14ee322011-09-22 04:58:26 +00004944 if (exe_ctx.GetProcessPtr() != this)
4945 {
4946 errors.Printf("RunThreadPlan called on wrong process.");
4947 return eExecutionSetupError;
4948 }
4949
4950 Thread *thread = exe_ctx.GetThreadPtr();
4951 if (thread == NULL)
4952 {
4953 errors.Printf("RunThreadPlan called with invalid thread.");
4954 return eExecutionSetupError;
4955 }
Jim Ingham77787032011-01-20 02:03:18 +00004956
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004957 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4958 // For that to be true the plan can't be private - since private plans suppress themselves in the
4959 // GetCompletedPlan call.
4960
4961 bool orig_plan_private = thread_plan_sp->GetPrivate();
4962 thread_plan_sp->SetPrivate(false);
4963
Jim Ingham444586b2011-01-24 06:34:17 +00004964 if (m_private_state.GetValue() != eStateStopped)
4965 {
4966 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004967 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004968 }
4969
Jim Ingham66243842011-08-13 00:56:10 +00004970 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004971 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004972 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004973 if (!selected_frame_sp)
4974 {
4975 thread->SetSelectedFrame(0);
4976 selected_frame_sp = thread->GetSelectedFrame();
4977 if (!selected_frame_sp)
4978 {
4979 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4980 return eExecutionSetupError;
4981 }
4982 }
4983
4984 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004985
4986 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4987 // so we should arrange to reset them as well.
4988
Greg Claytonc14ee322011-09-22 04:58:26 +00004989 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004990
Jim Ingham66243842011-08-13 00:56:10 +00004991 uint32_t selected_tid;
4992 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004993 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004994 {
4995 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004996 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004997 }
4998 else
4999 {
5000 selected_tid = LLDB_INVALID_THREAD_ID;
5001 }
5002
Jim Ingham372787f2012-04-07 00:00:41 +00005003 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00005004 lldb::StateType old_state;
5005 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005006
Greg Clayton5160ce52013-03-27 23:08:40 +00005007 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00005008 if (Host::GetCurrentThread() == m_private_state_thread)
5009 {
Jim Ingham076b3042012-04-10 01:21:57 +00005010 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5011 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005012 // 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 +00005013 // we are fielding public events here.
5014 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005015 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 +00005016
5017
Jim Ingham372787f2012-04-07 00:00:41 +00005018 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005019
5020 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5021 // returning control here.
5022 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5023 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5024 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5025 // do just what we want.
5026 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5027 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5028 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5029 old_state = m_public_state.GetValue();
5030 m_public_state.SetValueNoLock(eStateStopped);
5031
5032 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005033 StartPrivateStateThread(true);
5034 }
5035
5036 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00005037
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005038 if (options.GetDebug())
5039 {
5040 // In this case, we aren't actually going to run, we just want to stop right away.
5041 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5042 // FIXME: To make this prettier we should invent some stop reason for this, but that
5043 // is only cosmetic, and this functionality is only of use to lldb developers who can
5044 // live with not pretty...
5045 thread->Flush();
5046 return eExecutionStoppedForDebug;
5047 }
5048
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005049 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00005050
Sean Callanana46ec452012-07-11 21:31:24 +00005051 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00005052
Jim Ingham77787032011-01-20 02:03:18 +00005053 {
Sean Callanana46ec452012-07-11 21:31:24 +00005054 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5055 // restored on exit to the function.
5056 //
5057 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5058 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00005059
Sean Callanana46ec452012-07-11 21:31:24 +00005060 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00005061
Jim Inghamf48169b2010-11-30 02:22:11 +00005062 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005063 {
5064 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005065 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005066 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005067 thread->GetIndexID(),
5068 thread->GetID(),
5069 s.GetData());
5070 }
5071
5072 bool got_event;
5073 lldb::EventSP event_sp;
5074 lldb::StateType stop_state = lldb::eStateInvalid;
5075
5076 TimeValue* timeout_ptr = NULL;
5077 TimeValue real_timeout;
5078
Jim Ingham0161b492013-02-09 01:29:05 +00005079 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 +00005080 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005081 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005082 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00005083
Jim Ingham0161b492013-02-09 01:29:05 +00005084 // This is just for accounting:
5085 uint32_t num_resumes = 0;
5086
5087 TimeValue one_thread_timeout = TimeValue::Now();
5088 TimeValue final_timeout = one_thread_timeout;
5089
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005090 uint32_t timeout_usec = options.GetTimeoutUsec();
5091 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005092 {
5093 // If we are running all threads then we take half the time to run all threads, bounded by
5094 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005095 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00005096 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
5097 else
5098 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00005099 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00005100 if (computed_timeout > default_one_thread_timeout_usec)
5101 computed_timeout = default_one_thread_timeout_usec;
5102 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
5103 }
5104 final_timeout.OffsetWithMicroSeconds (timeout_usec);
5105 }
5106 else
5107 {
5108 if (timeout_usec != 0)
5109 final_timeout.OffsetWithMicroSeconds(timeout_usec);
5110 }
5111
Jim Ingham1460e4b2014-01-10 23:46:59 +00005112 // This isn't going to work if there are unfetched events on the queue.
5113 // Are there cases where we might want to run the remaining events here, and then try to
5114 // call the function? That's probably being too tricky for our own good.
5115
5116 Event *other_events = listener.PeekAtNextEvent();
5117 if (other_events != NULL)
5118 {
5119 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
5120 return eExecutionSetupError;
5121 }
5122
5123 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5124 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5125 // event coalescing to cause us to lose OUR running event...
5126 ForceNextEventDelivery();
5127
Jim Ingham8559a352012-11-26 23:52:18 +00005128 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5129 // So don't call return anywhere within it.
5130
Sean Callanana46ec452012-07-11 21:31:24 +00005131 while (1)
5132 {
5133 // We usually want to resume the process if we get to the top of the loop.
5134 // The only exception is if we get two running events with no intervening
5135 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005136 if (log)
5137 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5138 do_resume,
5139 handle_running_event,
5140 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00005141
Jim Ingham184e9812013-01-15 02:47:48 +00005142 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005143 {
5144 // Do the initial resume and wait for the running event before going further.
5145
Jim Ingham184e9812013-01-15 02:47:48 +00005146 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005147 {
Jim Ingham0161b492013-02-09 01:29:05 +00005148 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005149 Error resume_error = PrivateResume ();
5150 if (!resume_error.Success())
5151 {
Jim Ingham0161b492013-02-09 01:29:05 +00005152 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5153 num_resumes,
5154 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00005155 return_value = eExecutionSetupError;
5156 break;
5157 }
Sean Callanana46ec452012-07-11 21:31:24 +00005158 }
Sean Callanana46ec452012-07-11 21:31:24 +00005159
Jim Ingham0161b492013-02-09 01:29:05 +00005160 TimeValue resume_timeout = TimeValue::Now();
5161 resume_timeout.OffsetWithMicroSeconds(500000);
5162
5163 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005164 if (!got_event)
5165 {
5166 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005167 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5168 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005169
Jim Ingham0161b492013-02-09 01:29:05 +00005170 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005171 return_value = eExecutionSetupError;
5172 break;
5173 }
5174
5175 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005176
Sean Callanana46ec452012-07-11 21:31:24 +00005177 if (stop_state != eStateRunning)
5178 {
Jim Ingham0161b492013-02-09 01:29:05 +00005179 bool restarted = false;
5180
5181 if (stop_state == eStateStopped)
5182 {
5183 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5184 if (log)
5185 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5186 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5187 num_resumes,
5188 StateAsCString(stop_state),
5189 restarted,
5190 do_resume,
5191 handle_running_event);
5192 }
5193
5194 if (restarted)
5195 {
5196 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5197 // event here. But if I do, the best thing is to Halt and then get out of here.
5198 Halt();
5199 }
5200
Jim Ingham35e1bda2012-10-16 21:41:58 +00005201 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5202 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00005203 return_value = eExecutionSetupError;
5204 break;
5205 }
5206
5207 if (log)
5208 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5209 // We need to call the function synchronously, so spin waiting for it to return.
5210 // If we get interrupted while executing, we're going to lose our context, and
5211 // won't be able to gather the result at this point.
5212 // We set the timeout AFTER the resume, since the resume takes some time and we
5213 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005214 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005215 else
5216 {
Sean Callanana46ec452012-07-11 21:31:24 +00005217 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005218 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005219 }
Jim Ingham0161b492013-02-09 01:29:05 +00005220
5221 if (before_first_timeout)
5222 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005223 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005224 timeout_ptr = &one_thread_timeout;
5225 else
5226 {
5227 if (timeout_usec == 0)
5228 timeout_ptr = NULL;
5229 else
5230 timeout_ptr = &final_timeout;
5231 }
5232 }
5233 else
5234 {
5235 if (timeout_usec == 0)
5236 timeout_ptr = NULL;
5237 else
5238 timeout_ptr = &final_timeout;
5239 }
5240
5241 do_resume = true;
5242 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005243
Sean Callanana46ec452012-07-11 21:31:24 +00005244 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005245 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005246
Jim Ingham0f16e732011-02-08 05:20:59 +00005247 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005248 {
Sean Callanana46ec452012-07-11 21:31:24 +00005249 if (timeout_ptr)
5250 {
Matt Kopec676a4872013-02-21 23:55:31 +00005251 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005252 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5253 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005254 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005255 else
Sean Callanana46ec452012-07-11 21:31:24 +00005256 {
5257 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5258 }
5259 }
5260
5261 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5262
5263 if (got_event)
5264 {
5265 if (event_sp.get())
5266 {
5267 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005268 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005269 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005270 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005271 return_value = eExecutionInterrupted;
5272 errors.Printf ("Execution halted by user interrupt.");
5273 if (log)
5274 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005275 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005276 }
5277 else
5278 {
5279 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5280 if (log)
5281 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5282
5283 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005284 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005285 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005286 {
Jim Ingham0161b492013-02-09 01:29:05 +00005287 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005288 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5289 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005290 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005291 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005292 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005293 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5294 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005295 }
5296 else
5297 {
Jim Ingham0161b492013-02-09 01:29:05 +00005298 // If we were restarted, we just need to go back up to fetch another event.
5299 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005300 {
5301 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005302 {
5303 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5304 }
5305 keep_going = true;
5306 do_resume = false;
5307 handle_running_event = true;
5308
Jim Inghamcfc09352012-07-27 23:57:19 +00005309 }
5310 else
5311 {
Jim Ingham0161b492013-02-09 01:29:05 +00005312
5313 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5314 StopReason stop_reason = eStopReasonInvalid;
5315 if (stop_info_sp)
5316 stop_reason = stop_info_sp->GetStopReason();
5317
5318
5319 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5320 // it is OUR plan that is complete?
5321 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005322 {
5323 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005324 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5325 // Now mark this plan as private so it doesn't get reported as the stop reason
5326 // after this point.
5327 if (thread_plan_sp)
5328 thread_plan_sp->SetPrivate (orig_plan_private);
5329 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005330 }
5331 else
5332 {
Jim Ingham0161b492013-02-09 01:29:05 +00005333 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005334 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005335 {
5336 if (log)
5337 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005338 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005339 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005340 {
5341 event_to_broadcast_sp = event_sp;
5342 }
Jim Ingham0161b492013-02-09 01:29:05 +00005343 }
Jim Ingham184e9812013-01-15 02:47:48 +00005344 else
Jim Ingham0161b492013-02-09 01:29:05 +00005345 {
5346 if (log)
5347 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005348 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005349 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005350 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005351 }
Jim Ingham184e9812013-01-15 02:47:48 +00005352 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005353 }
Sean Callanana46ec452012-07-11 21:31:24 +00005354 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005355 }
5356 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005357
Jim Inghamcfc09352012-07-27 23:57:19 +00005358 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005359 // This shouldn't really happen, but sometimes we do get two running events without an
5360 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005361 do_resume = false;
5362 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005363 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005364 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005365
Jim Inghamcfc09352012-07-27 23:57:19 +00005366 default:
5367 if (log)
5368 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5369
5370 if (stop_state == eStateExited)
5371 event_to_broadcast_sp = event_sp;
5372
Sean Callananbf154da2012-08-08 17:35:10 +00005373 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005374 return_value = eExecutionInterrupted;
5375 break;
5376 }
Sean Callanana46ec452012-07-11 21:31:24 +00005377 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005378
Sean Callanana46ec452012-07-11 21:31:24 +00005379 if (keep_going)
5380 continue;
5381 else
5382 break;
5383 }
5384 else
5385 {
5386 if (log)
5387 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5388 return_value = eExecutionInterrupted;
5389 break;
5390 }
5391 }
5392 else
5393 {
5394 // If we didn't get an event that means we've timed out...
5395 // We will interrupt the process here. Depending on what we were asked to do we will
5396 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005397
5398 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005399 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005400 {
Jim Ingham0161b492013-02-09 01:29:05 +00005401 uint64_t remaining_time = final_timeout - TimeValue::Now();
5402 if (before_first_timeout)
5403 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005404 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005405 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005406 else
5407 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005408 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005409 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005410 }
5411 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005412 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005413 "abandoning execution.",
5414 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005415 }
5416
Jim Ingham0161b492013-02-09 01:29:05 +00005417 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5418 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5419 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5420 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5421 // stopped event. That's what this while loop does.
5422
5423 bool back_to_top = true;
5424 uint32_t try_halt_again = 0;
5425 bool do_halt = true;
5426 const uint32_t num_retries = 5;
5427 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005428 {
Jim Ingham0161b492013-02-09 01:29:05 +00005429 Error halt_error;
5430 if (do_halt)
5431 {
5432 if (log)
5433 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5434 halt_error = Halt();
5435 }
5436 if (halt_error.Success())
5437 {
5438 if (log)
5439 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5440
5441 real_timeout = TimeValue::Now();
5442 real_timeout.OffsetWithMicroSeconds(500000);
5443
5444 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005445
Jim Ingham0161b492013-02-09 01:29:05 +00005446 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005447 {
Jim Ingham0161b492013-02-09 01:29:05 +00005448 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5449 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005450 {
Jim Ingham0161b492013-02-09 01:29:05 +00005451 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5452 if (stop_state == lldb::eStateStopped
5453 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5454 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005455 }
5456
Jim Ingham0161b492013-02-09 01:29:05 +00005457 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005458 {
Jim Ingham0161b492013-02-09 01:29:05 +00005459 // Between the time we initiated the Halt and the time we delivered it, the process could have
5460 // already finished its job. Check that here:
5461
5462 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5463 {
5464 if (log)
5465 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5466 "Exiting wait loop.");
5467 return_value = eExecutionCompleted;
5468 back_to_top = false;
5469 break;
5470 }
5471
5472 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5473 {
5474 if (log)
5475 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5476 "Exiting wait loop.");
5477 try_halt_again++;
5478 do_halt = false;
5479 continue;
5480 }
Sean Callanana46ec452012-07-11 21:31:24 +00005481
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005482 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005483 {
5484 if (log)
5485 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5486 return_value = eExecutionInterrupted;
5487 back_to_top = false;
5488 break;
5489 }
5490
5491 if (before_first_timeout)
5492 {
5493 // Set all the other threads to run, and return to the top of the loop, which will continue;
5494 before_first_timeout = false;
5495 thread_plan_sp->SetStopOthers (false);
5496 if (log)
5497 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005498
Jim Ingham0161b492013-02-09 01:29:05 +00005499 back_to_top = true;
5500 break;
5501 }
5502 else
5503 {
5504 // Running all threads failed, so return Interrupted.
5505 if (log)
5506 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5507 return_value = eExecutionInterrupted;
5508 back_to_top = false;
5509 break;
5510 }
Sean Callanana46ec452012-07-11 21:31:24 +00005511 }
5512 }
5513 else
Jim Ingham0161b492013-02-09 01:29:05 +00005514 { if (log)
5515 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5516 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005517 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005518 back_to_top = false;
5519 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005520 }
5521 }
Jim Ingham0161b492013-02-09 01:29:05 +00005522 else
5523 {
5524 try_halt_again++;
5525 continue;
5526 }
Sean Callanana46ec452012-07-11 21:31:24 +00005527 }
Jim Ingham0161b492013-02-09 01:29:05 +00005528
5529 if (!back_to_top || try_halt_again > num_retries)
5530 break;
5531 else
5532 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005533 }
Sean Callanana46ec452012-07-11 21:31:24 +00005534 } // END WAIT LOOP
5535
5536 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5537 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5538 {
5539 StopPrivateStateThread();
5540 Error error;
5541 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005542 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005543 {
5544 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5545 }
5546 m_public_state.SetValueNoLock(old_state);
5547
5548 }
5549
Jim Ingham184e9812013-01-15 02:47:48 +00005550 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5551 // could happen:
5552 // 1) The execution successfully completed
5553 // 2) We hit a breakpoint, and ignore_breakpoints was true
5554 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005555 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5556 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005557
Jim Ingham184e9812013-01-15 02:47:48 +00005558 if (return_value == eExecutionCompleted
5559 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005560 {
5561 thread_plan_sp->RestoreThreadState();
5562 }
Sean Callanana46ec452012-07-11 21:31:24 +00005563
5564 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005565 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005566 {
5567 if (log)
5568 {
5569 StreamString s;
5570 if (event_sp)
5571 event_sp->Dump (&s);
5572 else
5573 {
5574 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5575 }
5576
5577 StreamString ts;
5578
5579 const char *event_explanation = NULL;
5580
5581 do
5582 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005583 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005584 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005585 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005586 break;
5587 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005588 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005589 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005590 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005591 break;
5592 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005593 else
Sean Callanana46ec452012-07-11 21:31:24 +00005594 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005595 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5596
5597 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005598 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005599 event_explanation = "<no event data>";
5600 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005601 }
5602
Jim Inghamcfc09352012-07-27 23:57:19 +00005603 Process *process = event_data->GetProcessSP().get();
5604
5605 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005606 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005607 event_explanation = "<no process>";
5608 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005609 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005610
5611 ThreadList &thread_list = process->GetThreadList();
5612
5613 uint32_t num_threads = thread_list.GetSize();
5614 uint32_t thread_index;
5615
5616 ts.Printf("<%u threads> ", num_threads);
5617
5618 for (thread_index = 0;
5619 thread_index < num_threads;
5620 ++thread_index)
5621 {
5622 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5623
5624 if (!thread)
5625 {
5626 ts.Printf("<?> ");
5627 continue;
5628 }
5629
Daniel Malead01b2952012-11-29 21:49:15 +00005630 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005631 RegisterContext *register_context = thread->GetRegisterContext().get();
5632
5633 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005634 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005635 else
5636 ts.Printf("[ip unknown] ");
5637
5638 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5639 if (stop_info_sp)
5640 {
5641 const char *stop_desc = stop_info_sp->GetDescription();
5642 if (stop_desc)
5643 ts.PutCString (stop_desc);
5644 }
5645 ts.Printf(">");
5646 }
5647
5648 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005649 }
Sean Callanana46ec452012-07-11 21:31:24 +00005650 } while (0);
5651
Jim Inghamcfc09352012-07-27 23:57:19 +00005652 if (event_explanation)
5653 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005654 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005655 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5656 }
5657
Jim Inghame4483cf2013-09-27 01:13:01 +00005658 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005659 {
5660 if (log)
5661 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5662 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5663 thread_plan_sp->SetPrivate (orig_plan_private);
5664 }
5665 else
5666 {
5667 if (log)
5668 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005669 }
5670 }
5671 else if (return_value == eExecutionSetupError)
5672 {
5673 if (log)
5674 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005675
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005676 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005677 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005678 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005679 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005680 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005681 }
5682 else
5683 {
Sean Callanana46ec452012-07-11 21:31:24 +00005684 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005685 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005686 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005687 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5688 return_value = eExecutionCompleted;
5689 }
5690 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5691 {
5692 if (log)
5693 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5694 return_value = eExecutionDiscarded;
5695 }
5696 else
5697 {
5698 if (log)
5699 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005700 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005701 {
5702 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005703 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005704 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5705 thread_plan_sp->SetPrivate (orig_plan_private);
5706 }
5707 }
5708 }
5709
5710 // Thread we ran the function in may have gone away because we ran the target
5711 // Check that it's still there, and if it is put it back in the context. Also restore the
5712 // frame in the context if it is still present.
5713 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5714 if (thread)
5715 {
5716 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5717 }
5718
5719 // Also restore the current process'es selected frame & thread, since this function calling may
5720 // be done behind the user's back.
5721
5722 if (selected_tid != LLDB_INVALID_THREAD_ID)
5723 {
5724 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5725 {
5726 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005727 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005728 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005729 if (old_frame_sp)
5730 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005731 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005732 }
5733 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005734
Sean Callanana46ec452012-07-11 21:31:24 +00005735 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005736
Sean Callanana46ec452012-07-11 21:31:24 +00005737 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005738 {
Sean Callanana46ec452012-07-11 21:31:24 +00005739 if (log)
5740 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5741 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005742 }
5743
5744 return return_value;
5745}
5746
5747const char *
5748Process::ExecutionResultAsCString (ExecutionResults result)
5749{
5750 const char *result_name;
5751
5752 switch (result)
5753 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005754 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005755 result_name = "eExecutionCompleted";
5756 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005757 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005758 result_name = "eExecutionDiscarded";
5759 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005760 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005761 result_name = "eExecutionInterrupted";
5762 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005763 case eExecutionHitBreakpoint:
5764 result_name = "eExecutionHitBreakpoint";
5765 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005766 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005767 result_name = "eExecutionSetupError";
5768 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005769 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005770 result_name = "eExecutionTimedOut";
5771 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005772 case eExecutionStoppedForDebug:
5773 result_name = "eExecutionStoppedForDebug";
5774 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005775 }
5776 return result_name;
5777}
5778
Greg Clayton7260f622011-04-18 08:33:37 +00005779void
5780Process::GetStatus (Stream &strm)
5781{
5782 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005783 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005784 {
5785 if (state == eStateExited)
5786 {
5787 int exit_status = GetExitStatus();
5788 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005789 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005790 GetID(),
5791 exit_status,
5792 exit_status,
5793 exit_description ? exit_description : "");
5794 }
5795 else
5796 {
5797 if (state == eStateConnected)
5798 strm.Printf ("Connected to remote target.\n");
5799 else
Daniel Malead01b2952012-11-29 21:49:15 +00005800 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005801 }
5802 }
5803 else
5804 {
Daniel Malead01b2952012-11-29 21:49:15 +00005805 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005806 }
5807}
5808
5809size_t
5810Process::GetThreadStatus (Stream &strm,
5811 bool only_threads_with_stop_reason,
5812 uint32_t start_frame,
5813 uint32_t num_frames,
5814 uint32_t num_frames_with_source)
5815{
5816 size_t num_thread_infos_dumped = 0;
5817
Jim Ingham41f2b942012-09-10 20:50:15 +00005818 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005819 const size_t num_threads = GetThreadList().GetSize();
5820 for (uint32_t i = 0; i < num_threads; i++)
5821 {
5822 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5823 if (thread)
5824 {
5825 if (only_threads_with_stop_reason)
5826 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005827 StopInfoSP stop_info_sp = thread->GetStopInfo();
5828 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005829 continue;
5830 }
5831 thread->GetStatus (strm,
5832 start_frame,
5833 num_frames,
5834 num_frames_with_source);
5835 ++num_thread_infos_dumped;
5836 }
5837 }
5838 return num_thread_infos_dumped;
5839}
5840
Greg Claytona9f40ad2012-02-22 04:37:26 +00005841void
5842Process::AddInvalidMemoryRegion (const LoadRange &region)
5843{
5844 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5845}
5846
5847bool
5848Process::RemoveInvalidMemoryRange (const LoadRange &region)
5849{
5850 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5851}
5852
Jim Ingham372787f2012-04-07 00:00:41 +00005853void
5854Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5855{
5856 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5857}
5858
5859bool
5860Process::RunPreResumeActions ()
5861{
5862 bool result = true;
5863 while (!m_pre_resume_actions.empty())
5864 {
5865 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5866 m_pre_resume_actions.pop_back();
5867 bool this_result = action.callback (action.baton);
5868 if (result == true) result = this_result;
5869 }
5870 return result;
5871}
5872
5873void
5874Process::ClearPreResumeActions ()
5875{
5876 m_pre_resume_actions.clear();
5877}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005878
Greg Claytonfa559e52012-05-18 02:38:05 +00005879void
5880Process::Flush ()
5881{
5882 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005883 m_extended_thread_list.Flush();
5884 m_extended_thread_stop_id = 0;
5885 m_queue_list.Clear();
5886 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005887}
Greg Clayton90ba8112012-12-05 00:16:59 +00005888
5889void
5890Process::DidExec ()
5891{
5892 Target &target = GetTarget();
5893 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005894 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005895 m_dynamic_checkers_ap.reset();
5896 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005897 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005898 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005899 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005900 m_image_tokens.clear();
5901 m_allocated_memory_cache.Clear();
5902 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005903 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005904 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005905 DoDidExec();
5906 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005907 // Flush the process (threads and all stack frames) after running CompleteAttach()
5908 // in case the dynamic loader loaded things in new locations.
5909 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005910
5911 // After we figure out what was loaded/unloaded in CompleteAttach,
5912 // we need to let the target know so it can do any cleanup it needs to.
5913 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005914}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005915
Jim Ingham1460e4b2014-01-10 23:46:59 +00005916addr_t
5917Process::ResolveIndirectFunction(const Address *address, Error &error)
5918{
5919 if (address == nullptr)
5920 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005921 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005922 return LLDB_INVALID_ADDRESS;
5923 }
5924
5925 addr_t function_addr = LLDB_INVALID_ADDRESS;
5926
5927 addr_t addr = address->GetLoadAddress(&GetTarget());
5928 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5929 if (iter != m_resolved_indirect_addresses.end())
5930 {
5931 function_addr = (*iter).second;
5932 }
5933 else
5934 {
5935 if (!InferiorCall(this, address, function_addr))
5936 {
5937 Symbol *symbol = address->CalculateSymbolContextSymbol();
5938 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5939 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5940 function_addr = LLDB_INVALID_ADDRESS;
5941 }
5942 else
5943 {
5944 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5945 }
5946 }
5947 return function_addr;
5948}
5949