blob: d6cd7bbd3aa9f6dc674976d4f8c5aa037cb17c01 [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"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "lldb/Target/Target.h"
39#include "lldb/Target/TargetList.h"
40#include "lldb/Target/Thread.h"
41#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000042#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Charles Davis510938e2013-08-27 05:04:57 +000044#ifndef LLDB_DISABLE_POSIX
45#include <spawn.h>
46#endif
47
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048using namespace lldb;
49using namespace lldb_private;
50
Greg Clayton67cc0632012-08-22 17:17:09 +000051
52// Comment out line below to disable memory caching, overriding the process setting
53// target.process.disable-memory-cache
54#define ENABLE_MEMORY_CACHING
55
56#ifdef ENABLE_MEMORY_CACHING
57#define DISABLE_MEM_CACHE_DEFAULT false
58#else
59#define DISABLE_MEM_CACHE_DEFAULT true
60#endif
61
62class ProcessOptionValueProperties : public OptionValueProperties
63{
64public:
65 ProcessOptionValueProperties (const ConstString &name) :
66 OptionValueProperties (name)
67 {
68 }
69
70 // This constructor is used when creating ProcessOptionValueProperties when it
71 // is part of a new lldb_private::Process instance. It will copy all current
72 // global property values as needed
73 ProcessOptionValueProperties (ProcessProperties *global_properties) :
74 OptionValueProperties(*global_properties->GetValueProperties())
75 {
76 }
77
78 virtual const Property *
79 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
80 {
81 // When gettings the value for a key from the process options, we will always
82 // try and grab the setting from the current process if there is one. Else we just
83 // use the one from this instance.
84 if (exe_ctx)
85 {
86 Process *process = exe_ctx->GetProcessPtr();
87 if (process)
88 {
89 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
90 if (this != instance_properties)
91 return instance_properties->ProtectedGetPropertyAtIndex (idx);
92 }
93 }
94 return ProtectedGetPropertyAtIndex (idx);
95 }
96};
97
98static PropertyDefinition
99g_properties[] =
100{
101 { "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 +0000102 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
103 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000104 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
105 { "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 +0000106 { "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 +0000107 { "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 +0000108 { "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 +0000109 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
110};
111
112enum {
113 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000114 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000115 ePropertyIgnoreBreakpointsInExpressions,
116 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000117 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000118 ePropertyStopOnSharedLibraryEvents,
119 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000120};
121
122ProcessProperties::ProcessProperties (bool is_global) :
123 Properties ()
124{
125 if (is_global)
126 {
127 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
128 m_collection_sp->Initialize(g_properties);
129 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000130 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000131 true,
132 Thread::GetGlobalProperties()->GetValueProperties());
133 }
134 else
135 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
136}
137
138ProcessProperties::~ProcessProperties()
139{
140}
141
142bool
143ProcessProperties::GetDisableMemoryCache() const
144{
145 const uint32_t idx = ePropertyDisableMemCache;
146 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
147}
148
149Args
150ProcessProperties::GetExtraStartupCommands () const
151{
152 Args args;
153 const uint32_t idx = ePropertyExtraStartCommand;
154 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
155 return args;
156}
157
158void
159ProcessProperties::SetExtraStartupCommands (const Args &args)
160{
161 const uint32_t idx = ePropertyExtraStartCommand;
162 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
163}
164
Greg Claytonc9d645d2012-10-18 22:40:37 +0000165FileSpec
166ProcessProperties::GetPythonOSPluginPath () const
167{
168 const uint32_t idx = ePropertyPythonOSPluginPath;
169 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
170}
171
172void
173ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
174{
175 const uint32_t idx = ePropertyPythonOSPluginPath;
176 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
177}
178
Jim Ingham184e9812013-01-15 02:47:48 +0000179
180bool
181ProcessProperties::GetIgnoreBreakpointsInExpressions () const
182{
183 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
184 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
185}
186
187void
188ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
189{
190 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
191 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
192}
193
194bool
195ProcessProperties::GetUnwindOnErrorInExpressions () const
196{
197 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
198 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
199}
200
201void
202ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
203{
204 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
205 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
206}
207
Jim Ingham29950772013-01-26 02:19:28 +0000208bool
209ProcessProperties::GetStopOnSharedLibraryEvents () const
210{
211 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
212 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
213}
214
215void
216ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
217{
218 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
219 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
220}
221
Jim Inghamacff8952013-05-02 00:27:30 +0000222bool
223ProcessProperties::GetDetachKeepsStopped () const
224{
225 const uint32_t idx = ePropertyDetachKeepsStopped;
226 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
227}
228
229void
230ProcessProperties::SetDetachKeepsStopped (bool stop)
231{
232 const uint32_t idx = ePropertyDetachKeepsStopped;
233 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
234}
235
Greg Clayton32e0a752011-03-30 18:16:51 +0000236void
Greg Clayton8b82f082011-04-12 05:54:46 +0000237ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000238{
239 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000240 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000241 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000242
243 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000244 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000245
246 if (m_executable)
247 {
248 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
249 s.PutCString (" file = ");
250 m_executable.Dump(&s);
251 s.EOL();
252 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000253 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000254 if (argc > 0)
255 {
256 for (uint32_t i=0; i<argc; i++)
257 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000258 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000259 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000260 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000261 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000262 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000263 }
264 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000265
266 const uint32_t envc = m_environment.GetArgumentCount();
267 if (envc > 0)
268 {
269 for (uint32_t i=0; i<envc; i++)
270 {
271 const char *env = m_environment.GetArgumentAtIndex(i);
272 if (i < 10)
273 s.Printf (" env[%u] = %s\n", i, env);
274 else
275 s.Printf ("env[%u] = %s\n", i, env);
276 }
277 }
278
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000279 if (m_arch.IsValid())
280 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
281
Greg Clayton8b82f082011-04-12 05:54:46 +0000282 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000283 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000284 cstr = platform->GetUserName (m_uid);
285 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000286 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000287 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000288 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000289 cstr = platform->GetGroupName (m_gid);
290 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000291 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000293 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000294 cstr = platform->GetUserName (m_euid);
295 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000296 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000298 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 cstr = platform->GetGroupName (m_egid);
300 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000301 }
302}
303
304void
Greg Clayton8b82f082011-04-12 05:54:46 +0000305ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000306{
Greg Clayton8b82f082011-04-12 05:54:46 +0000307 const char *label;
308 if (show_args || verbose)
309 label = "ARGUMENTS";
310 else
311 label = "NAME";
312
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000313 if (verbose)
314 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000315 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000316 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
317 }
318 else
319 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000320 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000321 s.PutCString ("====== ====== ========== ======= ============================\n");
322 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000323}
324
325void
Greg Clayton8b82f082011-04-12 05:54:46 +0000326ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000327{
328 if (m_pid != LLDB_INVALID_PROCESS_ID)
329 {
330 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000331 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000332
Greg Clayton32e0a752011-03-30 18:16:51 +0000333
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000334 if (verbose)
335 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000336 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000337 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
338 s.Printf ("%-10s ", cstr);
339 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000340 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000341
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000343 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
344 s.Printf ("%-10s ", cstr);
345 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000346 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000347
Greg Clayton8b82f082011-04-12 05:54:46 +0000348 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000349 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
350 s.Printf ("%-10s ", cstr);
351 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000352 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000353
Greg Clayton8b82f082011-04-12 05:54:46 +0000354 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000355 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
356 s.Printf ("%-10s ", cstr);
357 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000358 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000359 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
360 }
361 else
362 {
Jason Molendafd54b362011-09-20 21:44:10 +0000363 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000364 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000365 (int)m_arch.GetTriple().getArchName().size(),
366 m_arch.GetTriple().getArchName().data());
367 }
368
Greg Clayton8b82f082011-04-12 05:54:46 +0000369 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000370 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000371 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000372 if (argc > 0)
373 {
374 for (uint32_t i=0; i<argc; i++)
375 {
376 if (i > 0)
377 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000378 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000379 }
380 }
381 }
382 else
383 {
384 s.PutCString (GetName());
385 }
386
387 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000388 }
389}
390
Greg Clayton8b82f082011-04-12 05:54:46 +0000391
392void
Greg Clayton45392552012-10-17 22:57:12 +0000393ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000394{
395 m_arguments.SetArguments (argv);
396
397 // Is the first argument the executable?
398 if (first_arg_is_executable)
399 {
400 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
401 if (first_arg)
402 {
403 // Yes the first argument is an executable, set it as the executable
404 // in the launch options. Don't resolve the file path as the path
405 // could be a remote platform path
406 const bool resolve = false;
407 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000408 }
409 }
410}
411void
Greg Clayton45392552012-10-17 22:57:12 +0000412ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000413{
414 // Copy all arguments
415 m_arguments = args;
416
417 // Is the first argument the executable?
418 if (first_arg_is_executable)
419 {
Greg Clayton982c9762011-11-03 21:22:33 +0000420 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000421 if (first_arg)
422 {
423 // Yes the first argument is an executable, set it as the executable
424 // in the launch options. Don't resolve the file path as the path
425 // could be a remote platform path
426 const bool resolve = false;
427 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000428 }
429 }
430}
431
Greg Clayton1d885962011-11-08 02:43:13 +0000432void
Greg Claytonee95ed52011-11-17 22:14:31 +0000433ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000434{
435 // If notthing was specified, then check the process for any default
436 // settings that were set with "settings set"
437 if (m_file_actions.empty())
438 {
Greg Clayton1d885962011-11-08 02:43:13 +0000439 if (m_flags.Test(eLaunchFlagDisableSTDIO))
440 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000441 AppendSuppressFileAction (STDIN_FILENO , true, false);
442 AppendSuppressFileAction (STDOUT_FILENO, false, true);
443 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000444 }
445 else
446 {
447 // Check for any values that might have gotten set with any of:
448 // (lldb) settings set target.input-path
449 // (lldb) settings set target.output-path
450 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000451 FileSpec in_path;
452 FileSpec out_path;
453 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000454 if (target)
455 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000456 in_path = target->GetStandardInputPath();
457 out_path = target->GetStandardOutputPath();
458 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000459 }
460
Greg Clayton67cc0632012-08-22 17:17:09 +0000461 if (in_path || out_path || err_path)
462 {
463 char path[PATH_MAX];
464 if (in_path && in_path.GetPath(path, sizeof(path)))
465 AppendOpenFileAction(STDIN_FILENO, path, true, false);
466
467 if (out_path && out_path.GetPath(path, sizeof(path)))
468 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
469
470 if (err_path && err_path.GetPath(path, sizeof(path)))
471 AppendOpenFileAction(STDERR_FILENO, path, false, true);
472 }
473 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000474 {
475 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000476 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000477 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
478 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
479 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
480 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000481 }
482 }
Greg Clayton1d885962011-11-08 02:43:13 +0000483 }
484 }
485}
486
Greg Clayton144f3a92011-11-15 03:53:30 +0000487
488bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000489ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
490 bool localhost,
491 bool will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000492 bool first_arg_is_full_shell_command,
493 int32_t num_resumes)
Greg Clayton144f3a92011-11-15 03:53:30 +0000494{
495 error.Clear();
496
497 if (GetFlags().Test (eLaunchFlagLaunchInShell))
498 {
499 const char *shell_executable = GetShell();
500 if (shell_executable)
501 {
502 char shell_resolved_path[PATH_MAX];
503
504 if (localhost)
505 {
506 FileSpec shell_filespec (shell_executable, true);
507
508 if (!shell_filespec.Exists())
509 {
510 // Resolve the path in case we just got "bash", "sh" or "tcsh"
511 if (!shell_filespec.ResolveExecutableLocation ())
512 {
513 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
514 return false;
515 }
516 }
517 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
518 shell_executable = shell_resolved_path;
519 }
520
Greg Clayton45392552012-10-17 22:57:12 +0000521 const char **argv = GetArguments().GetConstArgumentVector ();
522 if (argv == NULL || argv[0] == NULL)
523 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000524 Args shell_arguments;
525 std::string safe_arg;
526 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000527 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000528 StreamString shell_command;
529 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000530 {
Greg Clayton45392552012-10-17 22:57:12 +0000531 // Add a modified PATH environment variable in case argv[0]
532 // is a relative path
533 const char *argv0 = argv[0];
534 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
535 {
536 // We have a relative path to our executable which may not work if
537 // we just try to run "a.out" (without it being converted to "./a.out")
538 const char *working_dir = GetWorkingDirectory();
Greg Clayton8938f8d2013-02-14 03:54:39 +0000539 // Be sure to put quotes around PATH's value in case any paths have spaces...
540 std::string new_path("PATH=\"");
Greg Clayton45392552012-10-17 22:57:12 +0000541 const size_t empty_path_len = new_path.size();
542
543 if (working_dir && working_dir[0])
544 {
545 new_path += working_dir;
546 }
547 else
548 {
549 char current_working_dir[PATH_MAX];
550 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
551 if (cwd && cwd[0])
552 new_path += cwd;
553 }
554 const char *curr_path = getenv("PATH");
555 if (curr_path)
556 {
557 if (new_path.size() > empty_path_len)
558 new_path += ':';
559 new_path += curr_path;
560 }
Greg Clayton8938f8d2013-02-14 03:54:39 +0000561 new_path += "\" ";
Greg Clayton45392552012-10-17 22:57:12 +0000562 shell_command.PutCString(new_path.c_str());
563 }
564
Greg Claytond1cf11a2012-04-14 01:42:46 +0000565 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000566
Greg Clayton45392552012-10-17 22:57:12 +0000567 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000568 if (GetArchitecture().IsValid())
569 {
570 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000571 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000572 // 1 - stop in shell
573 // 2 - stop in /usr/bin/arch
574 // 3 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000575 SetResumeCount(num_resumes + 1);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000576 }
577 else
578 {
Greg Clayton45392552012-10-17 22:57:12 +0000579 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000580 // 1 - stop in shell
581 // 2 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000582 SetResumeCount(num_resumes);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000583 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000584 }
Greg Clayton45392552012-10-17 22:57:12 +0000585
586 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000587 {
Greg Clayton45392552012-10-17 22:57:12 +0000588 // There should only be one argument that is the shell command itself to be used as is
589 if (argv[0] && !argv[1])
590 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000591 else
Greg Clayton45392552012-10-17 22:57:12 +0000592 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000593 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000594 else
595 {
Greg Clayton45392552012-10-17 22:57:12 +0000596 for (size_t i=0; argv[i] != NULL; ++i)
597 {
598 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
599 shell_command.Printf(" %s", arg);
600 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000601 }
Greg Clayton45392552012-10-17 22:57:12 +0000602 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000603 m_executable.SetFile(shell_executable, false);
604 m_arguments = shell_arguments;
605 return true;
606 }
607 else
608 {
609 error.SetErrorString ("invalid shell path");
610 }
611 }
612 else
613 {
614 error.SetErrorString ("not launching in shell");
615 }
616 return false;
617}
618
619
Greg Clayton32e0a752011-03-30 18:16:51 +0000620bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000621ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
622{
623 if ((read || write) && fd >= 0 && path && path[0])
624 {
625 m_action = eFileActionOpen;
626 m_fd = fd;
627 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000628 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000629 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000630 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000631 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000632 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000633 m_path.assign (path);
634 return true;
635 }
636 else
637 {
638 Clear();
639 }
640 return false;
641}
642
643bool
644ProcessLaunchInfo::FileAction::Close (int fd)
645{
646 Clear();
647 if (fd >= 0)
648 {
649 m_action = eFileActionClose;
650 m_fd = fd;
651 }
652 return m_fd >= 0;
653}
654
655
656bool
657ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
658{
659 Clear();
660 if (fd >= 0 && dup_fd >= 0)
661 {
662 m_action = eFileActionDuplicate;
663 m_fd = fd;
664 m_arg = dup_fd;
665 }
666 return m_fd >= 0;
667}
668
669
670
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000671#ifndef LLDB_DISABLE_POSIX
Greg Clayton8b82f082011-04-12 05:54:46 +0000672bool
Charles Davis510938e2013-08-27 05:04:57 +0000673ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions,
Greg Clayton8b82f082011-04-12 05:54:46 +0000674 const FileAction *info,
675 Log *log,
676 Error& error)
677{
678 if (info == NULL)
679 return false;
680
Charles Davis510938e2013-08-27 05:04:57 +0000681 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
682
Greg Clayton8b82f082011-04-12 05:54:46 +0000683 switch (info->m_action)
684 {
685 case eFileActionNone:
686 error.Clear();
687 break;
688
689 case eFileActionClose:
690 if (info->m_fd == -1)
691 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
692 else
693 {
694 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
695 eErrorTypePOSIX);
696 if (log && (error.Fail() || log))
697 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
698 file_actions, info->m_fd);
699 }
700 break;
701
702 case eFileActionDuplicate:
703 if (info->m_fd == -1)
704 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
705 else if (info->m_arg == -1)
706 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
707 else
708 {
709 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
710 eErrorTypePOSIX);
711 if (log && (error.Fail() || log))
712 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
713 file_actions, info->m_fd, info->m_arg);
714 }
715 break;
716
717 case eFileActionOpen:
718 if (info->m_fd == -1)
719 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
720 else
721 {
722 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000723
Greg Clayton8b82f082011-04-12 05:54:46 +0000724 mode_t mode = 0;
725
Greg Clayton144f3a92011-11-15 03:53:30 +0000726 if (oflag & O_CREAT)
727 mode = 0640;
728
Greg Clayton8b82f082011-04-12 05:54:46 +0000729 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
730 info->m_fd,
731 info->m_path.c_str(),
732 oflag,
733 mode),
734 eErrorTypePOSIX);
735 if (error.Fail() || log)
736 error.PutToLog(log,
737 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
738 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
739 }
740 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000741 }
742 return error.Success();
743}
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000744#endif
Greg Clayton8b82f082011-04-12 05:54:46 +0000745
746Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000747ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000748{
749 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000750 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000751
752 switch (short_option)
753 {
754 case 's': // Stop at program entry point
755 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
756 break;
757
Greg Clayton8b82f082011-04-12 05:54:46 +0000758 case 'i': // STDIN for read only
759 {
760 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000761 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000762 launch_info.AppendFileAction (action);
763 }
764 break;
765
766 case 'o': // Open STDOUT for write only
767 {
768 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000769 if (action.Open (STDOUT_FILENO, option_arg, false, true))
770 launch_info.AppendFileAction (action);
771 }
772 break;
773
774 case 'e': // STDERR for write only
775 {
776 ProcessLaunchInfo::FileAction action;
777 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000778 launch_info.AppendFileAction (action);
779 }
780 break;
781
Greg Clayton9845a8d2012-03-06 04:01:04 +0000782
Greg Clayton8b82f082011-04-12 05:54:46 +0000783 case 'p': // Process plug-in name
784 launch_info.SetProcessPluginName (option_arg);
785 break;
786
787 case 'n': // Disable STDIO
788 {
789 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000790 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000791 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000792 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000793 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000794 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000795 launch_info.AppendFileAction (action);
796 }
797 break;
798
799 case 'w':
800 launch_info.SetWorkingDirectory (option_arg);
801 break;
802
803 case 't': // Open process in new terminal window
804 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
805 break;
806
807 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000808 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
809 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000810 break;
811
812 case 'A':
813 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
814 break;
815
Greg Clayton982c9762011-11-03 21:22:33 +0000816 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000817 if (option_arg && option_arg[0])
818 launch_info.SetShell (option_arg);
819 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000820 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000821 break;
822
Greg Clayton8b82f082011-04-12 05:54:46 +0000823 case 'v':
824 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
825 break;
826
827 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000828 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000829 break;
830
831 }
832 return error;
833}
834
835OptionDefinition
836ProcessLaunchCommandOptions::g_option_table[] =
837{
Virgile Belloe2607b52013-09-05 16:42:23 +0000838{ 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."},
839{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
840{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
841{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
842{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
843{ 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."},
844{ 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 +0000845
Virgile Belloe2607b52013-09-05 16:42:23 +0000846{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
847{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
848{ 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 +0000849
Virgile Belloe2607b52013-09-05 16:42:23 +0000850{ 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 +0000851
Virgile Belloe2607b52013-09-05 16:42:23 +0000852{ 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 +0000853
854{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
855};
856
857
858
859bool
860ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000861{
862 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
863 return true;
864 const char *match_name = m_match_info.GetName();
865 if (!match_name)
866 return true;
867
868 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
869}
870
871bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000872ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000873{
874 if (!NameMatches (proc_info.GetName()))
875 return false;
876
877 if (m_match_info.ProcessIDIsValid() &&
878 m_match_info.GetProcessID() != proc_info.GetProcessID())
879 return false;
880
881 if (m_match_info.ParentProcessIDIsValid() &&
882 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
883 return false;
884
Greg Clayton8b82f082011-04-12 05:54:46 +0000885 if (m_match_info.UserIDIsValid () &&
886 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000887 return false;
888
Greg Clayton8b82f082011-04-12 05:54:46 +0000889 if (m_match_info.GroupIDIsValid () &&
890 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000891 return false;
892
893 if (m_match_info.EffectiveUserIDIsValid () &&
894 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
895 return false;
896
897 if (m_match_info.EffectiveGroupIDIsValid () &&
898 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
899 return false;
900
901 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000902 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000903 return false;
904 return true;
905}
906
907bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000908ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000909{
910 if (m_name_match_type != eNameMatchIgnore)
911 return false;
912
913 if (m_match_info.ProcessIDIsValid())
914 return false;
915
916 if (m_match_info.ParentProcessIDIsValid())
917 return false;
918
Greg Clayton8b82f082011-04-12 05:54:46 +0000919 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000920 return false;
921
Greg Clayton8b82f082011-04-12 05:54:46 +0000922 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000923 return false;
924
925 if (m_match_info.EffectiveUserIDIsValid ())
926 return false;
927
928 if (m_match_info.EffectiveGroupIDIsValid ())
929 return false;
930
931 if (m_match_info.GetArchitecture().IsValid())
932 return false;
933
934 if (m_match_all_users)
935 return false;
936
937 return true;
938
939}
940
941void
Greg Clayton8b82f082011-04-12 05:54:46 +0000942ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000943{
944 m_match_info.Clear();
945 m_name_match_type = eNameMatchIgnore;
946 m_match_all_users = false;
947}
Greg Clayton58be07b2011-01-07 06:08:19 +0000948
Greg Claytonc3776bf2012-02-09 06:16:32 +0000949ProcessSP
950Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000951{
Greg Clayton949e8222013-01-16 17:29:04 +0000952 static uint32_t g_process_unique_id = 0;
953
Greg Claytonc3776bf2012-02-09 06:16:32 +0000954 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955 ProcessCreateInstance create_callback = NULL;
956 if (plugin_name)
957 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000958 ConstString const_plugin_name(plugin_name);
959 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000960 if (create_callback)
961 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000962 process_sp = create_callback(target, listener, crash_file_path);
963 if (process_sp)
964 {
Greg Clayton949e8222013-01-16 17:29:04 +0000965 if (process_sp->CanDebug(target, true))
966 {
967 process_sp->m_process_unique_id = ++g_process_unique_id;
968 }
969 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000970 process_sp.reset();
971 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000972 }
973 }
974 else
975 {
Greg Claytonc982c762010-07-09 20:39:50 +0000976 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000978 process_sp = create_callback(target, listener, crash_file_path);
979 if (process_sp)
980 {
Greg Clayton949e8222013-01-16 17:29:04 +0000981 if (process_sp->CanDebug(target, false))
982 {
983 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000984 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000985 }
986 else
987 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000988 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989 }
990 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000991 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000992}
993
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000994ConstString &
995Process::GetStaticBroadcasterClass ()
996{
997 static ConstString class_name ("lldb.process");
998 return class_name;
999}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000
1001//----------------------------------------------------------------------
1002// Process constructor
1003//----------------------------------------------------------------------
1004Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +00001005 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001007 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001008 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 m_public_state (eStateUnloaded),
1010 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001011 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1012 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013 m_private_state_listener ("lldb.process.internal_state_listener"),
1014 m_private_state_control_wait(),
1015 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001016 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001017 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001018 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001019 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 m_exit_status (-1),
1021 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001022 m_thread_mutex (Mutex::eMutexTypeRecursive),
1023 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001024 m_thread_list (this),
1025 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001026 m_image_tokens (),
1027 m_listener (listener),
1028 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001029 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001030 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001031 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001032 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001033 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001034 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001035 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001036 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001037 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1038 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001039 m_memory_cache (*this),
1040 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001041 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001042 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001043 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001044 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001045 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001046 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001047 m_clear_thread_plans_on_stop (false),
Jim Ingham0161b492013-02-09 01:29:05 +00001048 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001049 m_destroy_in_process (false),
1050 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001052 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001053
Greg Clayton5160ce52013-03-27 23:08:40 +00001054 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055 if (log)
1056 log->Printf ("%p Process::Process()", this);
1057
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001058 SetEventName (eBroadcastBitStateChanged, "state-changed");
1059 SetEventName (eBroadcastBitInterrupt, "interrupt");
1060 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1061 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001062 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001063
Greg Clayton35a4cc52012-10-29 20:52:08 +00001064 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1065 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1066 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1067
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068 listener.StartListeningForEvents (this,
1069 eBroadcastBitStateChanged |
1070 eBroadcastBitInterrupt |
1071 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001072 eBroadcastBitSTDERR |
1073 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074
1075 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001076 eBroadcastBitStateChanged |
1077 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078
1079 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1080 eBroadcastInternalStateControlStop |
1081 eBroadcastInternalStateControlPause |
1082 eBroadcastInternalStateControlResume);
1083}
1084
1085//----------------------------------------------------------------------
1086// Destructor
1087//----------------------------------------------------------------------
1088Process::~Process()
1089{
Greg Clayton5160ce52013-03-27 23:08:40 +00001090 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091 if (log)
1092 log->Printf ("%p Process::~Process()", this);
1093 StopPrivateStateThread();
1094}
1095
Greg Clayton67cc0632012-08-22 17:17:09 +00001096const ProcessPropertiesSP &
1097Process::GetGlobalProperties()
1098{
1099 static ProcessPropertiesSP g_settings_sp;
1100 if (!g_settings_sp)
1101 g_settings_sp.reset (new ProcessProperties (true));
1102 return g_settings_sp;
1103}
1104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105void
1106Process::Finalize()
1107{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001108 switch (GetPrivateState())
1109 {
1110 case eStateConnected:
1111 case eStateAttaching:
1112 case eStateLaunching:
1113 case eStateStopped:
1114 case eStateRunning:
1115 case eStateStepping:
1116 case eStateCrashed:
1117 case eStateSuspended:
1118 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001119 {
1120 // FIXME: This will have to be a process setting:
1121 bool keep_stopped = false;
1122 Detach(keep_stopped);
1123 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001124 else
1125 Destroy();
1126 break;
1127
1128 case eStateInvalid:
1129 case eStateUnloaded:
1130 case eStateDetached:
1131 case eStateExited:
1132 break;
1133 }
1134
Greg Clayton1ed54f52011-10-01 00:45:15 +00001135 // Clear our broadcaster before we proceed with destroying
1136 Broadcaster::Clear();
1137
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138 // Do any cleanup needed prior to being destructed... Subclasses
1139 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001140
1141 // We need to destroy the loader before the derived Process class gets destroyed
1142 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001143 m_dynamic_checkers_ap.reset();
1144 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001145 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001146 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001147 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001148 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001149 std::vector<Notifications> empty_notifications;
1150 m_notifications.swap(empty_notifications);
1151 m_image_tokens.clear();
1152 m_memory_cache.Clear();
1153 m_allocated_memory_cache.Clear();
1154 m_language_runtimes.clear();
1155 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001156//#ifdef LLDB_CONFIGURATION_DEBUG
1157// StreamFile s(stdout, false);
1158// EventSP event_sp;
1159// while (m_private_state_listener.GetNextEvent(event_sp))
1160// {
1161// event_sp->Dump (&s);
1162// s.EOL();
1163// }
1164//#endif
1165 // We have to be very careful here as the m_private_state_listener might
1166 // contain events that have ProcessSP values in them which can keep this
1167 // process around forever. These events need to be cleared out.
1168 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001169 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1170 m_public_run_lock.SetStopped();
1171 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1172 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001173 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174}
1175
1176void
1177Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1178{
1179 m_notifications.push_back(callbacks);
1180 if (callbacks.initialize != NULL)
1181 callbacks.initialize (callbacks.baton, this);
1182}
1183
1184bool
1185Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1186{
1187 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1188 for (pos = m_notifications.begin(); pos != end; ++pos)
1189 {
1190 if (pos->baton == callbacks.baton &&
1191 pos->initialize == callbacks.initialize &&
1192 pos->process_state_changed == callbacks.process_state_changed)
1193 {
1194 m_notifications.erase(pos);
1195 return true;
1196 }
1197 }
1198 return false;
1199}
1200
1201void
1202Process::SynchronouslyNotifyStateChanged (StateType state)
1203{
1204 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1205 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1206 {
1207 if (notification_pos->process_state_changed)
1208 notification_pos->process_state_changed (notification_pos->baton, this, state);
1209 }
1210}
1211
1212// FIXME: We need to do some work on events before the general Listener sees them.
1213// For instance if we are continuing from a breakpoint, we need to ensure that we do
1214// the little "insert real insn, step & stop" trick. But we can't do that when the
1215// event is delivered by the broadcaster - since that is done on the thread that is
1216// waiting for new events, so if we needed more than one event for our handling, we would
1217// stall. So instead we do it when we fetch the event off of the queue.
1218//
1219
1220StateType
1221Process::GetNextEvent (EventSP &event_sp)
1222{
1223 StateType state = eStateInvalid;
1224
1225 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1226 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1227
1228 return state;
1229}
1230
1231
1232StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001233Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001234{
Jim Ingham4b536182011-08-09 02:12:22 +00001235 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1236 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1237 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001238 if (event_sp_ptr)
1239 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001240 StateType state = GetState();
1241 // If we are exited or detached, we won't ever get back to any
1242 // other valid state...
1243 if (state == eStateDetached || state == eStateExited)
1244 return state;
1245
1246 while (state != eStateInvalid)
1247 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001248 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001249 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001250 if (event_sp_ptr && event_sp)
1251 *event_sp_ptr = event_sp;
1252
Jim Ingham4b536182011-08-09 02:12:22 +00001253 switch (state)
1254 {
1255 case eStateCrashed:
1256 case eStateDetached:
1257 case eStateExited:
1258 case eStateUnloaded:
1259 return state;
1260 case eStateStopped:
1261 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1262 continue;
1263 else
1264 return state;
1265 default:
1266 continue;
1267 }
1268 }
1269 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270}
1271
1272
1273StateType
1274Process::WaitForState
1275(
1276 const TimeValue *timeout,
1277 const StateType *match_states, const uint32_t num_match_states
1278)
1279{
1280 EventSP event_sp;
1281 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001282 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283 while (state != eStateInvalid)
1284 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001285 // If we are exited or detached, we won't ever get back to any
1286 // other valid state...
1287 if (state == eStateDetached || state == eStateExited)
1288 return state;
1289
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001290 state = WaitForStateChangedEvents (timeout, event_sp);
1291
1292 for (i=0; i<num_match_states; ++i)
1293 {
1294 if (match_states[i] == state)
1295 return state;
1296 }
1297 }
1298 return state;
1299}
1300
Jim Ingham30f9b212010-10-11 23:53:14 +00001301bool
1302Process::HijackProcessEvents (Listener *listener)
1303{
1304 if (listener != NULL)
1305 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001306 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001307 }
1308 else
1309 return false;
1310}
1311
1312void
1313Process::RestoreProcessEvents ()
1314{
1315 RestoreBroadcaster();
1316}
1317
Jim Ingham0f16e732011-02-08 05:20:59 +00001318bool
1319Process::HijackPrivateProcessEvents (Listener *listener)
1320{
1321 if (listener != NULL)
1322 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001323 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001324 }
1325 else
1326 return false;
1327}
1328
1329void
1330Process::RestorePrivateProcessEvents ()
1331{
1332 m_private_state_broadcaster.RestoreBroadcaster();
1333}
1334
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335StateType
1336Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1337{
Greg Clayton5160ce52013-03-27 23:08:40 +00001338 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001339
1340 if (log)
1341 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1342
1343 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001344 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1345 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001346 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001347 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001348 {
1349 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1350 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1351 else if (log)
1352 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1353 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354
1355 if (log)
1356 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1357 __FUNCTION__,
1358 timeout,
1359 StateAsCString(state));
1360 return state;
1361}
1362
1363Event *
1364Process::PeekAtStateChangedEvents ()
1365{
Greg Clayton5160ce52013-03-27 23:08:40 +00001366 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367
1368 if (log)
1369 log->Printf ("Process::%s...", __FUNCTION__);
1370
1371 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001372 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1373 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 if (log)
1375 {
1376 if (event_ptr)
1377 {
1378 log->Printf ("Process::%s (event_ptr) => %s",
1379 __FUNCTION__,
1380 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1381 }
1382 else
1383 {
1384 log->Printf ("Process::%s no events found",
1385 __FUNCTION__);
1386 }
1387 }
1388 return event_ptr;
1389}
1390
1391StateType
1392Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1393{
Greg Clayton5160ce52013-03-27 23:08:40 +00001394 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395
1396 if (log)
1397 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1398
1399 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001400 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1401 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001402 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001403 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001404 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1405 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001406
1407 // This is a bit of a hack, but when we wait here we could very well return
1408 // to the command-line, and that could disable the log, which would render the
1409 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001411 {
1412 if (state == eStateInvalid)
1413 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1414 else
1415 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1416 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001417 return state;
1418}
1419
1420bool
1421Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1422{
Greg Clayton5160ce52013-03-27 23:08:40 +00001423 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424
1425 if (log)
1426 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1427
1428 if (control_only)
1429 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1430 else
1431 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1432}
1433
1434bool
1435Process::IsRunning () const
1436{
1437 return StateIsRunningState (m_public_state.GetValue());
1438}
1439
1440int
1441Process::GetExitStatus ()
1442{
1443 if (m_public_state.GetValue() == eStateExited)
1444 return m_exit_status;
1445 return -1;
1446}
1447
Greg Clayton85851dd2010-12-04 00:10:17 +00001448
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001449const char *
1450Process::GetExitDescription ()
1451{
1452 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1453 return m_exit_string.c_str();
1454 return NULL;
1455}
1456
Greg Clayton6779606a2011-01-22 23:43:18 +00001457bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458Process::SetExitStatus (int status, const char *cstr)
1459{
Greg Clayton5160ce52013-03-27 23:08:40 +00001460 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001461 if (log)
1462 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1463 status, status,
1464 cstr ? "\"" : "",
1465 cstr ? cstr : "NULL",
1466 cstr ? "\"" : "");
1467
Greg Clayton6779606a2011-01-22 23:43:18 +00001468 // We were already in the exited state
1469 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001470 {
Greg Clayton385d6032011-01-26 23:47:29 +00001471 if (log)
1472 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001473 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001474 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001475
1476 m_exit_status = status;
1477 if (cstr)
1478 m_exit_string = cstr;
1479 else
1480 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481
Greg Clayton6779606a2011-01-22 23:43:18 +00001482 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001483
Greg Clayton6779606a2011-01-22 23:43:18 +00001484 SetPrivateState (eStateExited);
1485 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486}
1487
1488// This static callback can be used to watch for local child processes on
1489// the current host. The the child process exits, the process will be
1490// found in the global target list (we want to be completely sure that the
1491// lldb_private::Process doesn't go away before we can deliver the signal.
1492bool
Greg Claytone4e45922011-11-16 05:37:56 +00001493Process::SetProcessExitStatus (void *callback_baton,
1494 lldb::pid_t pid,
1495 bool exited,
1496 int signo, // Zero for no signal
1497 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498)
1499{
Greg Clayton5160ce52013-03-27 23:08:40 +00001500 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001501 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001502 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001503 callback_baton,
1504 pid,
1505 exited,
1506 signo,
1507 exit_status);
1508
1509 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510 {
Greg Clayton66111032010-06-23 01:19:29 +00001511 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512 if (target_sp)
1513 {
1514 ProcessSP process_sp (target_sp->GetProcessSP());
1515 if (process_sp)
1516 {
1517 const char *signal_cstr = NULL;
1518 if (signo)
1519 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1520
1521 process_sp->SetExitStatus (exit_status, signal_cstr);
1522 }
1523 }
1524 return true;
1525 }
1526 return false;
1527}
1528
1529
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001530void
1531Process::UpdateThreadListIfNeeded ()
1532{
1533 const uint32_t stop_id = GetStopID();
1534 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1535 {
Greg Clayton2637f822011-11-17 01:23:07 +00001536 const StateType state = GetPrivateState();
1537 if (StateIsStoppedState (state, true))
1538 {
1539 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001540 // m_thread_list does have its own mutex, but we need to
1541 // hold onto the mutex between the call to UpdateThreadList(...)
1542 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001543 ThreadList &old_thread_list = m_thread_list;
1544 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001545 ThreadList new_thread_list(this);
1546 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001547 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001548 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001549 {
Jim Ingham09437922013-03-01 20:04:25 +00001550 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1551 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1552 // shutting us down, causing a deadlock.
1553 if (!m_destroy_in_process)
1554 {
1555 OperatingSystem *os = GetOperatingSystem ();
1556 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001557 {
1558 // Clear any old backing threads where memory threads might have been
1559 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001560 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001561 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001562 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001563
1564 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001565 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1566 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1567 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 +00001568 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001569 else
1570 {
1571 // No OS plug-in, the new thread list is the same as the real thread list
1572 new_thread_list = real_thread_list;
1573 }
Jim Ingham09437922013-03-01 20:04:25 +00001574 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001575
1576 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001577 m_thread_list.Update (new_thread_list);
1578 m_thread_list.SetStopID (stop_id);
Greg Clayton9fc13552012-04-10 00:18:59 +00001579 }
Greg Clayton2637f822011-11-17 01:23:07 +00001580 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001581 }
1582}
1583
Greg Claytona4d87472013-01-18 23:41:08 +00001584ThreadSP
1585Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1586{
1587 OperatingSystem *os = GetOperatingSystem ();
1588 if (os)
1589 return os->CreateThread(tid, context);
1590 return ThreadSP();
1591}
1592
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001593uint32_t
1594Process::GetNextThreadIndexID (uint64_t thread_id)
1595{
1596 return AssignIndexIDToThread(thread_id);
1597}
1598
1599bool
1600Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1601{
1602 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1603 if (iterator == m_thread_id_to_index_id_map.end())
1604 {
1605 return false;
1606 }
1607 else
1608 {
1609 return true;
1610 }
1611}
1612
1613uint32_t
1614Process::AssignIndexIDToThread(uint64_t thread_id)
1615{
1616 uint32_t result = 0;
1617 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1618 if (iterator == m_thread_id_to_index_id_map.end())
1619 {
1620 result = ++m_thread_index_id;
1621 m_thread_id_to_index_id_map[thread_id] = result;
1622 }
1623 else
1624 {
1625 result = iterator->second;
1626 }
1627
1628 return result;
1629}
1630
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001631StateType
1632Process::GetState()
1633{
1634 // If any other threads access this we will need a mutex for it
1635 return m_public_state.GetValue ();
1636}
1637
1638void
Jim Ingham221d51c2013-05-08 00:35:16 +00001639Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001640{
Greg Clayton5160ce52013-03-27 23:08:40 +00001641 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001642 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001643 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001644 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001645 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001646
1647 // On the transition from Run to Stopped, we unlock the writer end of the
1648 // run lock. The lock gets locked in Resume, which is the public API
1649 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001650 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1651 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001652 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001653 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001654 if (log)
1655 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001656 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001657 }
1658 else
1659 {
1660 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1661 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001662 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001663 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001664 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001665 {
1666 if (log)
1667 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001668 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001669 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001670 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001671 }
1672 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673}
1674
Jim Ingham3b8285d2012-04-19 01:40:33 +00001675Error
1676Process::Resume ()
1677{
Greg Clayton5160ce52013-03-27 23:08:40 +00001678 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001679 if (log)
1680 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001681 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001682 {
1683 Error error("Resume request failed - process still running.");
1684 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001685 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001686 return error;
1687 }
1688 return PrivateResume();
1689}
1690
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001691StateType
1692Process::GetPrivateState ()
1693{
1694 return m_private_state.GetValue();
1695}
1696
1697void
1698Process::SetPrivateState (StateType new_state)
1699{
Greg Clayton5160ce52013-03-27 23:08:40 +00001700 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001701 bool state_changed = false;
1702
1703 if (log)
1704 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1705
Andrew Kaylor29d65742013-05-10 17:19:04 +00001706 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001707 Mutex::Locker locker(m_private_state.GetMutex());
1708
1709 const StateType old_state = m_private_state.GetValueNoLock ();
1710 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001711
Greg Claytonaa49c832013-05-03 22:25:56 +00001712 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1713 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1714 if (old_state_is_stopped != new_state_is_stopped)
1715 {
1716 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001717 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001718 else
Ed Maste64fad602013-07-29 20:58:06 +00001719 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001720 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001722 if (state_changed)
1723 {
1724 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001725 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001726 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001727 // Note, this currently assumes that all threads in the list
1728 // stop when the process stops. In the future we will want to
1729 // support a debugging model where some threads continue to run
1730 // while others are stopped. When that happens we will either need
1731 // a way for the thread list to identify which threads are stopping
1732 // or create a special thread list containing only threads which
1733 // actually stopped.
1734 //
1735 // The process plugin is responsible for managing the actual
1736 // behavior of the threads and should have stopped any threads
1737 // that are going to stop before we get here.
1738 m_thread_list.DidStop();
1739
Jim Ingham4b536182011-08-09 02:12:22 +00001740 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001741 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001743 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001744 }
1745 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001746 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1747 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1748 else
1749 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750 }
1751 else
1752 {
1753 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001754 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755 }
1756}
1757
Jim Ingham0faa43f2011-11-08 03:00:11 +00001758void
1759Process::SetRunningUserExpression (bool on)
1760{
1761 m_mod_id.SetRunningUserExpression (on);
1762}
1763
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001764addr_t
1765Process::GetImageInfoAddress()
1766{
1767 return LLDB_INVALID_ADDRESS;
1768}
1769
Greg Clayton8f343b02010-11-04 01:54:29 +00001770//----------------------------------------------------------------------
1771// LoadImage
1772//
1773// This function provides a default implementation that works for most
1774// unix variants. Any Process subclasses that need to do shared library
1775// loading differently should override LoadImage and UnloadImage and
1776// do what is needed.
1777//----------------------------------------------------------------------
1778uint32_t
1779Process::LoadImage (const FileSpec &image_spec, Error &error)
1780{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001781 char path[PATH_MAX];
1782 image_spec.GetPath(path, sizeof(path));
1783
Greg Clayton8f343b02010-11-04 01:54:29 +00001784 DynamicLoader *loader = GetDynamicLoader();
1785 if (loader)
1786 {
1787 error = loader->CanLoadImage();
1788 if (error.Fail())
1789 return LLDB_INVALID_IMAGE_TOKEN;
1790 }
1791
1792 if (error.Success())
1793 {
1794 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001795
1796 if (thread_sp)
1797 {
1798 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1799
1800 if (frame_sp)
1801 {
1802 ExecutionContext exe_ctx;
1803 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham184e9812013-01-15 02:47:48 +00001804 const bool unwind_on_error = true;
1805 const bool ignore_breakpoints = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001806 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001807 expr.Printf("dlopen (\"%s\", 2)", path);
1808 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001809 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001810 ClangUserExpression::Evaluate (exe_ctx,
1811 eExecutionPolicyAlways,
1812 lldb::eLanguageTypeUnknown,
1813 ClangUserExpression::eResultTypeAny,
1814 unwind_on_error,
Jim Ingham184e9812013-01-15 02:47:48 +00001815 ignore_breakpoints,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001816 expr.GetData(),
1817 prefix,
1818 result_valobj_sp,
1819 true,
1820 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001821 error = result_valobj_sp->GetError();
1822 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001823 {
1824 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001825 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001826 {
1827 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1828 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1829 {
1830 uint32_t image_token = m_image_tokens.size();
1831 m_image_tokens.push_back (image_ptr);
1832 return image_token;
1833 }
1834 }
1835 }
1836 }
1837 }
1838 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001839 if (!error.AsCString())
1840 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001841 return LLDB_INVALID_IMAGE_TOKEN;
1842}
1843
1844//----------------------------------------------------------------------
1845// UnloadImage
1846//
1847// This function provides a default implementation that works for most
1848// unix variants. Any Process subclasses that need to do shared library
1849// loading differently should override LoadImage and UnloadImage and
1850// do what is needed.
1851//----------------------------------------------------------------------
1852Error
1853Process::UnloadImage (uint32_t image_token)
1854{
1855 Error error;
1856 if (image_token < m_image_tokens.size())
1857 {
1858 const addr_t image_addr = m_image_tokens[image_token];
1859 if (image_addr == LLDB_INVALID_ADDRESS)
1860 {
1861 error.SetErrorString("image already unloaded");
1862 }
1863 else
1864 {
1865 DynamicLoader *loader = GetDynamicLoader();
1866 if (loader)
1867 error = loader->CanLoadImage();
1868
1869 if (error.Success())
1870 {
1871 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001872
1873 if (thread_sp)
1874 {
1875 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1876
1877 if (frame_sp)
1878 {
1879 ExecutionContext exe_ctx;
1880 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham184e9812013-01-15 02:47:48 +00001881 const bool unwind_on_error = true;
1882 const bool ignore_breakpoints = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001883 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001884 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001885 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001886 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001887 ClangUserExpression::Evaluate (exe_ctx,
1888 eExecutionPolicyAlways,
1889 lldb::eLanguageTypeUnknown,
1890 ClangUserExpression::eResultTypeAny,
1891 unwind_on_error,
Jim Ingham184e9812013-01-15 02:47:48 +00001892 ignore_breakpoints,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001893 expr.GetData(),
1894 prefix,
1895 result_valobj_sp,
1896 true,
1897 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001898 if (result_valobj_sp->GetError().Success())
1899 {
1900 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001901 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001902 {
1903 if (scalar.UInt(1))
1904 {
1905 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1906 }
1907 else
1908 {
1909 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1910 }
1911 }
1912 }
1913 else
1914 {
1915 error = result_valobj_sp->GetError();
1916 }
1917 }
1918 }
1919 }
1920 }
1921 }
1922 else
1923 {
1924 error.SetErrorString("invalid image token");
1925 }
1926 return error;
1927}
1928
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001929const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001930Process::GetABI()
1931{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001932 if (!m_abi_sp)
1933 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1934 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001935}
1936
Jim Ingham22777012010-09-23 02:01:19 +00001937LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001938Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001939{
1940 LanguageRuntimeCollection::iterator pos;
1941 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001942 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001943 {
Jim Inghamab175242012-03-10 00:22:19 +00001944 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001945
Jim Inghamab175242012-03-10 00:22:19 +00001946 m_language_runtimes[language] = runtime_sp;
1947 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001948 }
1949 else
1950 return (*pos).second.get();
1951}
1952
1953CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001954Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001955{
Jim Inghamab175242012-03-10 00:22:19 +00001956 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001957 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1958 return static_cast<CPPLanguageRuntime *> (runtime);
1959 return NULL;
1960}
1961
1962ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001963Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001964{
Jim Inghamab175242012-03-10 00:22:19 +00001965 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001966 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1967 return static_cast<ObjCLanguageRuntime *> (runtime);
1968 return NULL;
1969}
1970
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001971bool
1972Process::IsPossibleDynamicValue (ValueObject& in_value)
1973{
1974 if (in_value.IsDynamic())
1975 return false;
1976 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1977
1978 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1979 {
1980 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1981 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1982 }
1983
1984 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1985 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1986 return true;
1987
1988 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1989 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1990}
1991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001992BreakpointSiteList &
1993Process::GetBreakpointSiteList()
1994{
1995 return m_breakpoint_site_list;
1996}
1997
1998const BreakpointSiteList &
1999Process::GetBreakpointSiteList() const
2000{
2001 return m_breakpoint_site_list;
2002}
2003
2004
2005void
2006Process::DisableAllBreakpointSites ()
2007{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002008 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2009// bp_site->SetEnabled(true);
2010 DisableBreakpointSite(bp_site);
2011 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012}
2013
2014Error
2015Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2016{
2017 Error error (DisableBreakpointSiteByID (break_id));
2018
2019 if (error.Success())
2020 m_breakpoint_site_list.Remove(break_id);
2021
2022 return error;
2023}
2024
2025Error
2026Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2027{
2028 Error error;
2029 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2030 if (bp_site_sp)
2031 {
2032 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002033 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002034 }
2035 else
2036 {
Daniel Malead01b2952012-11-29 21:49:15 +00002037 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038 }
2039
2040 return error;
2041}
2042
2043Error
2044Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2045{
2046 Error error;
2047 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2048 if (bp_site_sp)
2049 {
2050 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002051 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002052 }
2053 else
2054 {
Daniel Malead01b2952012-11-29 21:49:15 +00002055 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002056 }
2057 return error;
2058}
2059
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002060lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002061Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002062{
Greg Clayton92bb12c2011-05-19 18:17:41 +00002063 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064 if (load_addr != LLDB_INVALID_ADDRESS)
2065 {
2066 BreakpointSiteSP bp_site_sp;
2067
2068 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2069 // create a new breakpoint site and add it.
2070
2071 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2072
2073 if (bp_site_sp)
2074 {
2075 bp_site_sp->AddOwner (owner);
2076 owner->SetBreakpointSite (bp_site_sp);
2077 return bp_site_sp->GetID();
2078 }
2079 else
2080 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002081 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002082 if (bp_site_sp)
2083 {
Jim Ingham299c0c12013-02-15 02:06:30 +00002084 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002085 {
2086 owner->SetBreakpointSite (bp_site_sp);
2087 return m_breakpoint_site_list.Add (bp_site_sp);
2088 }
2089 }
2090 }
2091 }
2092 // We failed to enable the breakpoint
2093 return LLDB_INVALID_BREAK_ID;
2094
2095}
2096
2097void
2098Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2099{
2100 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2101 if (num_owners == 0)
2102 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002103 // Don't try to disable the site if we don't have a live process anymore.
2104 if (IsAlive())
2105 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2107 }
2108}
2109
2110
2111size_t
2112Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2113{
2114 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002115 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116
Jim Ingham20c77192011-06-29 19:42:28 +00002117 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002119 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2120 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002122 addr_t intersect_addr;
2123 size_t intersect_size;
2124 size_t opcode_offset;
2125 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002126 {
2127 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2128 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002129 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002130 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002131 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002132 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002133 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002134 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135 }
2136 return bytes_removed;
2137}
2138
2139
Greg Claytonded470d2011-03-19 01:12:21 +00002140
2141size_t
2142Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2143{
2144 PlatformSP platform_sp (m_target.GetPlatform());
2145 if (platform_sp)
2146 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2147 return 0;
2148}
2149
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002150Error
2151Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2152{
2153 Error error;
2154 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002155 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156 const addr_t bp_addr = bp_site->GetLoadAddress();
2157 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002158 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002159 if (bp_site->IsEnabled())
2160 {
2161 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002162 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 +00002163 return error;
2164 }
2165
2166 if (bp_addr == LLDB_INVALID_ADDRESS)
2167 {
2168 error.SetErrorString("BreakpointSite contains an invalid load address.");
2169 return error;
2170 }
2171 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2172 // trap for the breakpoint site
2173 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2174
2175 if (bp_opcode_size == 0)
2176 {
Daniel Malead01b2952012-11-29 21:49:15 +00002177 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178 }
2179 else
2180 {
2181 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2182
2183 if (bp_opcode_bytes == NULL)
2184 {
2185 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2186 return error;
2187 }
2188
2189 // Save the original opcode by reading it
2190 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2191 {
2192 // Write a software breakpoint in place of the original opcode
2193 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2194 {
2195 uint8_t verify_bp_opcode_bytes[64];
2196 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2197 {
2198 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2199 {
2200 bp_site->SetEnabled(true);
2201 bp_site->SetType (BreakpointSite::eSoftware);
2202 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002203 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204 bp_site->GetID(),
2205 (uint64_t)bp_addr);
2206 }
2207 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002208 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209 }
2210 else
2211 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2212 }
2213 else
2214 error.SetErrorString("Unable to write breakpoint trap to memory.");
2215 }
2216 else
2217 error.SetErrorString("Unable to read memory at breakpoint address.");
2218 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002219 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002220 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002221 bp_site->GetID(),
2222 (uint64_t)bp_addr,
2223 error.AsCString());
2224 return error;
2225}
2226
2227Error
2228Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2229{
2230 Error error;
2231 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002232 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233 addr_t bp_addr = bp_site->GetLoadAddress();
2234 lldb::user_id_t breakID = bp_site->GetID();
2235 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002236 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237
2238 if (bp_site->IsHardware())
2239 {
2240 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2241 }
2242 else if (bp_site->IsEnabled())
2243 {
2244 const size_t break_op_size = bp_site->GetByteSize();
2245 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2246 if (break_op_size > 0)
2247 {
2248 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002249 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002250 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 bool break_op_found = false;
2252
2253 // Read the breakpoint opcode
2254 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2255 {
2256 bool verify = false;
2257 // Make sure we have the a breakpoint opcode exists at this address
2258 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2259 {
2260 break_op_found = true;
2261 // We found a valid breakpoint opcode at this address, now restore
2262 // the saved opcode.
2263 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2264 {
2265 verify = true;
2266 }
2267 else
2268 error.SetErrorString("Memory write failed when restoring original opcode.");
2269 }
2270 else
2271 {
2272 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2273 // Set verify to true and so we can check if the original opcode has already been restored
2274 verify = true;
2275 }
2276
2277 if (verify)
2278 {
Greg Claytonc982c762010-07-09 20:39:50 +00002279 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002280 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 // Verify that our original opcode made it back to the inferior
2282 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2283 {
2284 // compare the memory we just read with the original opcode
2285 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2286 {
2287 // SUCCESS
2288 bp_site->SetEnabled(false);
2289 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002290 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 +00002291 return error;
2292 }
2293 else
2294 {
2295 if (break_op_found)
2296 error.SetErrorString("Failed to restore original opcode.");
2297 }
2298 }
2299 else
2300 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2301 }
2302 }
2303 else
2304 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2305 }
2306 }
2307 else
2308 {
2309 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002310 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 +00002311 return error;
2312 }
2313
2314 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002315 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002316 bp_site->GetID(),
2317 (uint64_t)bp_addr,
2318 error.AsCString());
2319 return error;
2320
2321}
2322
Greg Clayton58be07b2011-01-07 06:08:19 +00002323// Uncomment to verify memory caching works after making changes to caching code
2324//#define VERIFY_MEMORY_READS
2325
Sean Callanan64c0cf22012-06-07 22:26:42 +00002326size_t
2327Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2328{
2329 if (!GetDisableMemoryCache())
2330 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002331#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002332 // Memory caching is enabled, with debug verification
2333
2334 if (buf && size)
2335 {
2336 // Uncomment the line below to make sure memory caching is working.
2337 // I ran this through the test suite and got no assertions, so I am
2338 // pretty confident this is working well. If any changes are made to
2339 // memory caching, uncomment the line below and test your changes!
2340
2341 // Verify all memory reads by using the cache first, then redundantly
2342 // reading the same memory from the inferior and comparing to make sure
2343 // everything is exactly the same.
2344 std::string verify_buf (size, '\0');
2345 assert (verify_buf.size() == size);
2346 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2347 Error verify_error;
2348 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2349 assert (cache_bytes_read == verify_bytes_read);
2350 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2351 assert (verify_error.Success() == error.Success());
2352 return cache_bytes_read;
2353 }
2354 return 0;
2355#else // !defined(VERIFY_MEMORY_READS)
2356 // Memory caching is enabled, without debug verification
2357
2358 return m_memory_cache.Read (addr, buf, size, error);
2359#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002360 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002361 else
2362 {
2363 // Memory caching is disabled
2364
2365 return ReadMemoryFromInferior (addr, buf, size, error);
2366 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002367}
Greg Clayton58be07b2011-01-07 06:08:19 +00002368
Greg Clayton4c82d422012-05-18 23:20:01 +00002369size_t
2370Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2371{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002372 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002373 out_str.clear();
2374 addr_t curr_addr = addr;
2375 while (1)
2376 {
2377 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2378 if (length == 0)
2379 break;
2380 out_str.append(buf, length);
2381 // If we got "length - 1" bytes, we didn't get the whole C string, we
2382 // need to read some more characters
2383 if (length == sizeof(buf) - 1)
2384 curr_addr += length;
2385 else
2386 break;
2387 }
2388 return out_str.size();
2389}
2390
Greg Clayton58be07b2011-01-07 06:08:19 +00002391
2392size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002393Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2394 size_t type_width)
2395{
2396 size_t total_bytes_read = 0;
2397 if (dst && max_bytes && type_width && max_bytes >= type_width)
2398 {
2399 // Ensure a null terminator independent of the number of bytes that is read.
2400 memset (dst, 0, max_bytes);
2401 size_t bytes_left = max_bytes - type_width;
2402
2403 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2404 assert(sizeof(terminator) >= type_width &&
2405 "Attempting to validate a string with more than 4 bytes per character!");
2406
2407 addr_t curr_addr = addr;
2408 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2409 char *curr_dst = dst;
2410
2411 error.Clear();
2412 while (bytes_left > 0 && error.Success())
2413 {
2414 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2415 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2416 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2417
2418 if (bytes_read == 0)
2419 break;
2420
2421 // Search for a null terminator of correct size and alignment in bytes_read
2422 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2423 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2424 if (::strncmp(&dst[i], terminator, type_width) == 0)
2425 {
2426 error.Clear();
2427 return i;
2428 }
2429
2430 total_bytes_read += bytes_read;
2431 curr_dst += bytes_read;
2432 curr_addr += bytes_read;
2433 bytes_left -= bytes_read;
2434 }
2435 }
2436 else
2437 {
2438 if (max_bytes)
2439 error.SetErrorString("invalid arguments");
2440 }
2441 return total_bytes_read;
2442}
2443
2444// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2445// null terminators.
2446size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002447Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002448{
2449 size_t total_cstr_len = 0;
2450 if (dst && dst_max_len)
2451 {
Greg Claytone91b7952011-12-15 03:14:23 +00002452 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002453 // NULL out everything just to be safe
2454 memset (dst, 0, dst_max_len);
2455 Error error;
2456 addr_t curr_addr = addr;
2457 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2458 size_t bytes_left = dst_max_len - 1;
2459 char *curr_dst = dst;
2460
2461 while (bytes_left > 0)
2462 {
2463 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2464 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2465 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2466
2467 if (bytes_read == 0)
2468 {
Greg Claytone91b7952011-12-15 03:14:23 +00002469 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002470 dst[total_cstr_len] = '\0';
2471 break;
2472 }
2473 const size_t len = strlen(curr_dst);
2474
2475 total_cstr_len += len;
2476
2477 if (len < bytes_to_read)
2478 break;
2479
2480 curr_dst += bytes_read;
2481 curr_addr += bytes_read;
2482 bytes_left -= bytes_read;
2483 }
2484 }
Greg Claytone91b7952011-12-15 03:14:23 +00002485 else
2486 {
2487 if (dst == NULL)
2488 result_error.SetErrorString("invalid arguments");
2489 else
2490 result_error.Clear();
2491 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002492 return total_cstr_len;
2493}
2494
2495size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002496Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2497{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002498 if (buf == NULL || size == 0)
2499 return 0;
2500
2501 size_t bytes_read = 0;
2502 uint8_t *bytes = (uint8_t *)buf;
2503
2504 while (bytes_read < size)
2505 {
2506 const size_t curr_size = size - bytes_read;
2507 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2508 bytes + bytes_read,
2509 curr_size,
2510 error);
2511 bytes_read += curr_bytes_read;
2512 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2513 break;
2514 }
2515
2516 // Replace any software breakpoint opcodes that fall into this range back
2517 // into "buf" before we return
2518 if (bytes_read > 0)
2519 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2520 return bytes_read;
2521}
2522
Greg Clayton58a4c462010-12-16 20:01:20 +00002523uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002524Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002525{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002526 Scalar scalar;
2527 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2528 return scalar.ULongLong(fail_value);
2529 return fail_value;
2530}
2531
2532addr_t
2533Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2534{
2535 Scalar scalar;
2536 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2537 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2538 return LLDB_INVALID_ADDRESS;
2539}
2540
2541
2542bool
2543Process::WritePointerToMemory (lldb::addr_t vm_addr,
2544 lldb::addr_t ptr_value,
2545 Error &error)
2546{
2547 Scalar scalar;
2548 const uint32_t addr_byte_size = GetAddressByteSize();
2549 if (addr_byte_size <= 4)
2550 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002551 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002552 scalar = ptr_value;
2553 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002554}
2555
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002556size_t
2557Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2558{
2559 size_t bytes_written = 0;
2560 const uint8_t *bytes = (const uint8_t *)buf;
2561
2562 while (bytes_written < size)
2563 {
2564 const size_t curr_size = size - bytes_written;
2565 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2566 bytes + bytes_written,
2567 curr_size,
2568 error);
2569 bytes_written += curr_bytes_written;
2570 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2571 break;
2572 }
2573 return bytes_written;
2574}
2575
2576size_t
2577Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2578{
Greg Clayton58be07b2011-01-07 06:08:19 +00002579#if defined (ENABLE_MEMORY_CACHING)
2580 m_memory_cache.Flush (addr, size);
2581#endif
2582
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583 if (buf == NULL || size == 0)
2584 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002585
Jim Ingham4b536182011-08-09 02:12:22 +00002586 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002587
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002588 // We need to write any data that would go where any current software traps
2589 // (enabled software breakpoints) any software traps (breakpoints) that we
2590 // may have placed in our tasks memory.
2591
Greg Claytond8cf1a12013-06-12 00:46:38 +00002592 BreakpointSiteList bp_sites_in_range;
2593
2594 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002596 // No breakpoint sites overlap
2597 if (bp_sites_in_range.IsEmpty())
2598 return WriteMemoryPrivate (addr, buf, size, error);
2599 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002601 const uint8_t *ubuf = (const uint8_t *)buf;
2602 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002603
Greg Claytond8cf1a12013-06-12 00:46:38 +00002604 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2605
2606 if (error.Success())
2607 {
2608 addr_t intersect_addr;
2609 size_t intersect_size;
2610 size_t opcode_offset;
2611 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2612 assert(intersects);
2613 assert(addr <= intersect_addr && intersect_addr < addr + size);
2614 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2615 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2616
2617 // Check for bytes before this breakpoint
2618 const addr_t curr_addr = addr + bytes_written;
2619 if (intersect_addr > curr_addr)
2620 {
2621 // There are some bytes before this breakpoint that we need to
2622 // just write to memory
2623 size_t curr_size = intersect_addr - curr_addr;
2624 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2625 ubuf + bytes_written,
2626 curr_size,
2627 error);
2628 bytes_written += curr_bytes_written;
2629 if (curr_bytes_written != curr_size)
2630 {
2631 // We weren't able to write all of the requested bytes, we
2632 // are done looping and will return the number of bytes that
2633 // we have written so far.
2634 if (error.Success())
2635 error.SetErrorToGenericError();
2636 }
2637 }
2638 // Now write any bytes that would cover up any software breakpoints
2639 // directly into the breakpoint opcode buffer
2640 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2641 bytes_written += intersect_size;
2642 }
2643 });
2644
2645 if (bytes_written < size)
2646 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2647 ubuf + bytes_written,
2648 size - bytes_written,
2649 error);
2650 }
2651 }
2652 else
2653 {
2654 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655 }
2656
2657 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002658 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002659}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002660
2661size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002662Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002663{
2664 if (byte_size == UINT32_MAX)
2665 byte_size = scalar.GetByteSize();
2666 if (byte_size > 0)
2667 {
2668 uint8_t buf[32];
2669 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2670 if (mem_size > 0)
2671 return WriteMemory(addr, buf, mem_size, error);
2672 else
2673 error.SetErrorString ("failed to get scalar as memory data");
2674 }
2675 else
2676 {
2677 error.SetErrorString ("invalid scalar value");
2678 }
2679 return 0;
2680}
2681
2682size_t
2683Process::ReadScalarIntegerFromMemory (addr_t addr,
2684 uint32_t byte_size,
2685 bool is_signed,
2686 Scalar &scalar,
2687 Error &error)
2688{
Greg Clayton7060f892013-05-01 23:41:30 +00002689 uint64_t uval = 0;
2690 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002691 {
Greg Clayton7060f892013-05-01 23:41:30 +00002692 error.SetErrorString ("byte size is zero");
2693 }
2694 else if (byte_size & (byte_size - 1))
2695 {
2696 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2697 }
2698 else if (byte_size <= sizeof(uval))
2699 {
2700 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002701 if (bytes_read == byte_size)
2702 {
2703 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002704 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002705 if (byte_size <= 4)
2706 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002707 else
Greg Clayton7060f892013-05-01 23:41:30 +00002708 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002709 if (is_signed)
2710 scalar.SignExtend(byte_size * 8);
2711 return bytes_read;
2712 }
2713 }
2714 else
2715 {
2716 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2717 }
2718 return 0;
2719}
2720
Greg Claytond495c532011-05-17 03:37:42 +00002721#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722addr_t
2723Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2724{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002725 if (GetPrivateState() != eStateStopped)
2726 return LLDB_INVALID_ADDRESS;
2727
Greg Claytond495c532011-05-17 03:37:42 +00002728#if defined (USE_ALLOCATE_MEMORY_CACHE)
2729 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2730#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002731 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002732 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002733 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002734 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002735 size,
Greg Claytond495c532011-05-17 03:37:42 +00002736 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002737 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002738 m_mod_id.GetStopID(),
2739 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002740 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002741#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742}
2743
Sean Callanan90539452011-09-20 23:01:51 +00002744bool
2745Process::CanJIT ()
2746{
Sean Callanana7b443a2012-02-14 22:50:38 +00002747 if (m_can_jit == eCanJITDontKnow)
2748 {
2749 Error err;
2750
2751 uint64_t allocated_memory = AllocateMemory(8,
2752 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2753 err);
2754
2755 if (err.Success())
2756 m_can_jit = eCanJITYes;
2757 else
2758 m_can_jit = eCanJITNo;
2759
2760 DeallocateMemory (allocated_memory);
2761 }
2762
Sean Callanan90539452011-09-20 23:01:51 +00002763 return m_can_jit == eCanJITYes;
2764}
2765
2766void
2767Process::SetCanJIT (bool can_jit)
2768{
2769 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2770}
2771
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002772Error
2773Process::DeallocateMemory (addr_t ptr)
2774{
Greg Claytond495c532011-05-17 03:37:42 +00002775 Error error;
2776#if defined (USE_ALLOCATE_MEMORY_CACHE)
2777 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2778 {
Daniel Malead01b2952012-11-29 21:49:15 +00002779 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002780 }
2781#else
2782 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002783
Greg Clayton5160ce52013-03-27 23:08:40 +00002784 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002785 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002786 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 +00002787 ptr,
2788 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002789 m_mod_id.GetStopID(),
2790 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002791#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002792 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002793}
2794
Han Ming Ongc811d382012-11-17 00:33:14 +00002795
Greg Claytonc9660542012-02-05 02:38:54 +00002796ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002797Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002798 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002799{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002800 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002801 if (module_sp)
2802 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002803 Error error;
2804 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2805 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002806 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002807 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002808 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002809}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002810
2811Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002812Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813{
2814 Error error;
2815 error.SetErrorString("watchpoints are not supported");
2816 return error;
2817}
2818
2819Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002820Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002821{
2822 Error error;
2823 error.SetErrorString("watchpoints are not supported");
2824 return error;
2825}
2826
2827StateType
2828Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2829{
2830 StateType state;
2831 // Now wait for the process to launch and return control to us, and then
2832 // call DidLaunch:
2833 while (1)
2834 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002835 event_sp.reset();
2836 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2837
Greg Clayton2637f822011-11-17 01:23:07 +00002838 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002840
2841 // If state is invalid, then we timed out
2842 if (state == eStateInvalid)
2843 break;
2844
2845 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002846 HandlePrivateEvent (event_sp);
2847 }
2848 return state;
2849}
2850
2851Error
Greg Clayton982c9762011-11-03 21:22:33 +00002852Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002853{
2854 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002856 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002857 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002858 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002859
Greg Claytonaa149cb2011-08-11 02:48:45 +00002860 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002861 if (exe_module)
2862 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002863 char local_exec_file_path[PATH_MAX];
2864 char platform_exec_file_path[PATH_MAX];
2865 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2866 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002867 if (exe_module->GetFileSpec().Exists())
2868 {
Greg Clayton71337622011-02-24 22:24:29 +00002869 if (PrivateStateThreadIsValid ())
2870 PausePrivateStateThread ();
2871
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002872 error = WillLaunch (exe_module);
2873 if (error.Success())
2874 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002875 const bool restarted = false;
2876 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002877 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878
Ed Maste64fad602013-07-29 20:58:06 +00002879 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002880 {
2881 // Now launch using these arguments.
2882 error = DoLaunch (exe_module, launch_info);
2883 }
2884 else
2885 {
2886 // This shouldn't happen
2887 error.SetErrorString("failed to acquire process run lock");
2888 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889
2890 if (error.Fail())
2891 {
2892 if (GetID() != LLDB_INVALID_PROCESS_ID)
2893 {
2894 SetID (LLDB_INVALID_PROCESS_ID);
2895 const char *error_string = error.AsCString();
2896 if (error_string == NULL)
2897 error_string = "launch failed";
2898 SetExitStatus (-1, error_string);
2899 }
2900 }
2901 else
2902 {
2903 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002904 TimeValue timeout_time;
2905 timeout_time = TimeValue::Now();
2906 timeout_time.OffsetWithSeconds(10);
2907 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908
Greg Clayton1a38ea72011-06-22 01:42:17 +00002909 if (state == eStateInvalid || event_sp.get() == NULL)
2910 {
2911 // We were able to launch the process, but we failed to
2912 // catch the initial stop.
2913 SetExitStatus (0, "failed to catch stop after launch");
2914 Destroy();
2915 }
2916 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002917 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919 DidLaunch ();
2920
Greg Claytonc859e2d2012-02-13 23:10:39 +00002921 DynamicLoader *dyld = GetDynamicLoader ();
2922 if (dyld)
2923 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002924
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002925 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926 // This delays passing the stopped event to listeners till DidLaunch gets
2927 // a chance to complete...
2928 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002929
2930 if (PrivateStateThreadIsValid ())
2931 ResumePrivateStateThread ();
2932 else
2933 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002934 }
2935 else if (state == eStateExited)
2936 {
2937 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2938 // not likely to work, and return an invalid pid.
2939 HandlePrivateEvent (event_sp);
2940 }
2941 }
2942 }
2943 }
2944 else
2945 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002946 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002947 }
2948 }
2949 return error;
2950}
2951
Greg Claytonc3776bf2012-02-09 06:16:32 +00002952
2953Error
2954Process::LoadCore ()
2955{
2956 Error error = DoLoadCore();
2957 if (error.Success())
2958 {
2959 if (PrivateStateThreadIsValid ())
2960 ResumePrivateStateThread ();
2961 else
2962 StartPrivateStateThread ();
2963
Greg Claytonc859e2d2012-02-13 23:10:39 +00002964 DynamicLoader *dyld = GetDynamicLoader ();
2965 if (dyld)
2966 dyld->DidAttach();
2967
2968 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002969 // We successfully loaded a core file, now pretend we stopped so we can
2970 // show all of the threads in the core file and explore the crashed
2971 // state.
2972 SetPrivateState (eStateStopped);
2973
2974 }
2975 return error;
2976}
2977
Greg Claytonc859e2d2012-02-13 23:10:39 +00002978DynamicLoader *
2979Process::GetDynamicLoader ()
2980{
2981 if (m_dyld_ap.get() == NULL)
2982 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2983 return m_dyld_ap.get();
2984}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002985
2986
Jim Inghambb3a2832011-01-29 01:49:25 +00002987Process::NextEventAction::EventActionResult
2988Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989{
Jim Inghambb3a2832011-01-29 01:49:25 +00002990 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2991 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002992 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002993 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002994 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002995 return eEventActionRetry;
2996
2997 case eStateStopped:
2998 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002999 {
3000 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003001 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003002 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003003 // We don't want these events to be reported, so go set the ShouldReportStop here:
3004 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3005
Greg Claytonc9ed4782011-11-12 02:10:56 +00003006 if (m_exec_count > 0)
3007 {
3008 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003009 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003010 return eEventActionRetry;
3011 }
3012 else
3013 {
3014 m_process->CompleteAttach ();
3015 return eEventActionSuccess;
3016 }
3017 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003018 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003019
Greg Clayton513c26c2011-01-29 07:10:55 +00003020 default:
3021 case eStateExited:
3022 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003023 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003024 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003025
3026 m_exit_string.assign ("No valid Process");
3027 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003028}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029
Jim Inghambb3a2832011-01-29 01:49:25 +00003030Process::NextEventAction::EventActionResult
3031Process::AttachCompletionHandler::HandleBeingInterrupted()
3032{
3033 return eEventActionSuccess;
3034}
3035
3036const char *
3037Process::AttachCompletionHandler::GetExitString ()
3038{
3039 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040}
3041
3042Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003043Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003046 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003047 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003048 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003049
Greg Clayton144f3a92011-11-15 03:53:30 +00003050 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003051 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003052 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003053 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003054 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003055
Greg Clayton144f3a92011-11-15 03:53:30 +00003056 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003057 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003058 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3059
3060 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003062 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3063 if (error.Success())
3064 {
Ed Maste64fad602013-07-29 20:58:06 +00003065 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003066 {
3067 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003068 const bool restarted = false;
3069 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003070 // Now attach using these arguments.
3071 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3072 }
3073 else
3074 {
3075 // This shouldn't happen
3076 error.SetErrorString("failed to acquire process run lock");
3077 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003078
Greg Clayton144f3a92011-11-15 03:53:30 +00003079 if (error.Fail())
3080 {
3081 if (GetID() != LLDB_INVALID_PROCESS_ID)
3082 {
3083 SetID (LLDB_INVALID_PROCESS_ID);
3084 if (error.AsCString() == NULL)
3085 error.SetErrorString("attach failed");
3086
3087 SetExitStatus(-1, error.AsCString());
3088 }
3089 }
3090 else
3091 {
3092 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3093 StartPrivateStateThread();
3094 }
3095 return error;
3096 }
Greg Claytone996fd32011-03-08 22:40:15 +00003097 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003098 else
Greg Claytone996fd32011-03-08 22:40:15 +00003099 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003100 ProcessInstanceInfoList process_infos;
3101 PlatformSP platform_sp (m_target.GetPlatform ());
3102
3103 if (platform_sp)
3104 {
3105 ProcessInstanceInfoMatch match_info;
3106 match_info.GetProcessInfo() = attach_info;
3107 match_info.SetNameMatchType (eNameMatchEquals);
3108 platform_sp->FindProcesses (match_info, process_infos);
3109 const uint32_t num_matches = process_infos.GetSize();
3110 if (num_matches == 1)
3111 {
3112 attach_pid = process_infos.GetProcessIDAtIndex(0);
3113 // Fall through and attach using the above process ID
3114 }
3115 else
3116 {
3117 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3118 if (num_matches > 1)
3119 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3120 else
3121 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3122 }
3123 }
3124 else
3125 {
3126 error.SetErrorString ("invalid platform, can't find processes by name");
3127 return error;
3128 }
Greg Claytone996fd32011-03-08 22:40:15 +00003129 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130 }
3131 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003132 {
3133 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003134 }
3135 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003136
3137 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003138 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003139 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003140 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003142
Ed Maste64fad602013-07-29 20:58:06 +00003143 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003144 {
3145 // Now attach using these arguments.
3146 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003147 const bool restarted = false;
3148 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003149 error = DoAttachToProcessWithID (attach_pid, attach_info);
3150 }
3151 else
3152 {
3153 // This shouldn't happen
3154 error.SetErrorString("failed to acquire process run lock");
3155 }
3156
Greg Clayton144f3a92011-11-15 03:53:30 +00003157 if (error.Success())
3158 {
3159
3160 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3161 StartPrivateStateThread();
3162 }
3163 else
Greg Claytone996fd32011-03-08 22:40:15 +00003164 {
3165 if (GetID() != LLDB_INVALID_PROCESS_ID)
3166 {
3167 SetID (LLDB_INVALID_PROCESS_ID);
3168 const char *error_string = error.AsCString();
3169 if (error_string == NULL)
3170 error_string = "attach failed";
3171
3172 SetExitStatus(-1, error_string);
3173 }
3174 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003175 }
3176 }
3177 return error;
3178}
3179
Greg Clayton93d3c8332011-02-16 04:46:07 +00003180void
3181Process::CompleteAttach ()
3182{
3183 // Let the process subclass figure out at much as it can about the process
3184 // before we go looking for a dynamic loader plug-in.
3185 DidAttach();
3186
Jim Ingham4299fdb2011-09-15 01:10:17 +00003187 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3188 // the same as the one we've already set, switch architectures.
3189 PlatformSP platform_sp (m_target.GetPlatform ());
3190 assert (platform_sp.get());
3191 if (platform_sp)
3192 {
Greg Clayton70512312012-05-08 01:45:38 +00003193 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003194 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003195 {
3196 ArchSpec platform_arch;
3197 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3198 if (platform_sp)
3199 {
3200 m_target.SetPlatform (platform_sp);
3201 m_target.SetArchitecture(platform_arch);
3202 }
3203 }
3204 else
3205 {
3206 ProcessInstanceInfo process_info;
3207 platform_sp->GetProcessInfo (GetID(), process_info);
3208 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003209 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003210 m_target.SetArchitecture (process_arch);
3211 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003212 }
3213
3214 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003215 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003216 DynamicLoader *dyld = GetDynamicLoader ();
3217 if (dyld)
3218 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003219
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003220 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003221 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003222 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003223 Mutex::Locker modules_locker(target_modules.GetMutex());
3224 size_t num_modules = target_modules.GetSize();
3225 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003226
Andy Gibbsa297a972013-06-19 19:04:53 +00003227 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003228 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003229 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003230 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003231 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003232 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003233 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003234 break;
3235 }
3236 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003237 if (new_executable_module_sp)
3238 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003239}
3240
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003241Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003242Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003243{
Greg Claytonb766a732011-02-04 01:58:07 +00003244 m_abi_sp.reset();
3245 m_process_input_reader.reset();
3246
3247 // Find the process and its architecture. Make sure it matches the architecture
3248 // of the current Target, and if not adjust it.
3249
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003250 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003251 if (error.Success())
3252 {
Greg Clayton71337622011-02-24 22:24:29 +00003253 if (GetID() != LLDB_INVALID_PROCESS_ID)
3254 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003255 EventSP event_sp;
3256 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3257
3258 if (state == eStateStopped || state == eStateCrashed)
3259 {
3260 // If we attached and actually have a process on the other end, then
3261 // this ended up being the equivalent of an attach.
3262 CompleteAttach ();
3263
3264 // This delays passing the stopped event to listeners till
3265 // CompleteAttach gets a chance to complete...
3266 HandlePrivateEvent (event_sp);
3267
3268 }
Greg Clayton71337622011-02-24 22:24:29 +00003269 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003270
3271 if (PrivateStateThreadIsValid ())
3272 ResumePrivateStateThread ();
3273 else
3274 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003275 }
3276 return error;
3277}
3278
3279
3280Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003281Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003282{
Greg Clayton5160ce52013-03-27 23:08:40 +00003283 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003284 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003285 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003286 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003287 StateAsCString(m_public_state.GetValue()),
3288 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003289
3290 Error error (WillResume());
3291 // Tell the process it is about to resume before the thread list
3292 if (error.Success())
3293 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003294 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295 // can let all of our threads know that they are about to be
3296 // resumed. Threads will each be called with
3297 // Thread::WillResume(StateType) where StateType contains the state
3298 // that they are supposed to have when the process is resumed
3299 // (suspended/running/stepping). Threads should also check
3300 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003301 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302 if (m_thread_list.WillResume())
3303 {
Jim Ingham372787f2012-04-07 00:00:41 +00003304 // Last thing, do the PreResumeActions.
3305 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306 {
Jim Ingham0161b492013-02-09 01:29:05 +00003307 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003308 }
3309 else
3310 {
3311 m_mod_id.BumpResumeID();
3312 error = DoResume();
3313 if (error.Success())
3314 {
3315 DidResume();
3316 m_thread_list.DidResume();
3317 if (log)
3318 log->Printf ("Process thinks the process has resumed.");
3319 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320 }
3321 }
3322 else
3323 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003324 // Somebody wanted to run without running. So generate a continue & a stopped event,
3325 // and let the world handle them.
3326 if (log)
3327 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3328
3329 SetPrivateState(eStateRunning);
3330 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331 }
3332 }
Jim Ingham444586b2011-01-24 06:34:17 +00003333 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003334 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335 return error;
3336}
3337
3338Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003339Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003340{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003341 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3342 // in case it was already set and some thread plan logic calls halt on its
3343 // own.
3344 m_clear_thread_plans_on_stop |= clear_thread_plans;
3345
Jim Inghamaacc3182012-06-06 00:29:30 +00003346 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3347 // we could just straightaway get another event. It just narrows the window...
3348 m_currently_handling_event.WaitForValueEqualTo(false);
3349
3350
Jim Inghambb3a2832011-01-29 01:49:25 +00003351 // Pause our private state thread so we can ensure no one else eats
3352 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003353 Listener halt_listener ("lldb.process.halt_listener");
3354 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003355
Jim Inghambb3a2832011-01-29 01:49:25 +00003356 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003357 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003358
Greg Clayton513c26c2011-01-29 07:10:55 +00003359 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003360 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003361
Greg Clayton513c26c2011-01-29 07:10:55 +00003362 bool caused_stop = false;
3363
3364 // Ask the process subclass to actually halt our process
3365 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003366 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003367 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003368 if (m_public_state.GetValue() == eStateAttaching)
3369 {
3370 SetExitStatus(SIGKILL, "Cancelled async attach.");
3371 Destroy ();
3372 }
3373 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003374 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003375 // If "caused_stop" is true, then DoHalt stopped the process. If
3376 // "caused_stop" is false, the process was already stopped.
3377 // If the DoHalt caused the process to stop, then we want to catch
3378 // this event and set the interrupted bool to true before we pass
3379 // this along so clients know that the process was interrupted by
3380 // a halt command.
3381 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003382 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003383 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003384 TimeValue timeout_time;
3385 timeout_time = TimeValue::Now();
3386 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003387 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3388 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003389
Jim Ingham0f16e732011-02-08 05:20:59 +00003390 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003391 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003392 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003393 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003394 }
3395 else
3396 {
Greg Clayton2637f822011-11-17 01:23:07 +00003397 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003398 {
3399 // We caused the process to interrupt itself, so mark this
3400 // as such in the stop event so clients can tell an interrupted
3401 // process from a natural stop
3402 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3403 }
3404 else
3405 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003406 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003407 if (log)
3408 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3409 error.SetErrorString ("Did not get stopped event after halt.");
3410 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003411 }
3412 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003413 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003414 }
3415 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003416 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003417 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003418 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003419
3420 // Post any event we might have consumed. If all goes well, we will have
3421 // stopped the process, intercepted the event and set the interrupted
3422 // bool in the event. Post it to the private event queue and that will end up
3423 // correctly setting the state.
3424 if (event_sp)
3425 m_private_state_broadcaster.BroadcastEvent(event_sp);
3426
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427 return error;
3428}
3429
3430Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003431Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3432{
3433 Error error;
3434 if (m_public_state.GetValue() == eStateRunning)
3435 {
3436 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3437 if (log)
3438 log->Printf("Process::Destroy() About to halt.");
3439 error = Halt();
3440 if (error.Success())
3441 {
3442 // Consume the halt event.
3443 TimeValue timeout (TimeValue::Now());
3444 timeout.OffsetWithSeconds(1);
3445 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3446
3447 // If the process exited while we were waiting for it to stop, put the exited event into
3448 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3449 // they don't have a process anymore...
3450
3451 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3452 {
3453 if (log)
3454 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3455 return error;
3456 }
3457 else
3458 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3459
3460 if (state != eStateStopped)
3461 {
3462 if (log)
3463 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3464 // If we really couldn't stop the process then we should just error out here, but if the
3465 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3466 StateType private_state = m_private_state.GetValue();
3467 if (private_state != eStateStopped)
3468 {
3469 return error;
3470 }
3471 }
3472 }
3473 else
3474 {
3475 if (log)
3476 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3477 }
3478 }
3479 return error;
3480}
3481
3482Error
Jim Inghamacff8952013-05-02 00:27:30 +00003483Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003485 EventSP exit_event_sp;
3486 Error error;
3487 m_destroy_in_process = true;
3488
3489 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490
3491 if (error.Success())
3492 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003493 if (DetachRequiresHalt())
3494 {
3495 error = HaltForDestroyOrDetach (exit_event_sp);
3496 if (!error.Success())
3497 {
3498 m_destroy_in_process = false;
3499 return error;
3500 }
3501 else if (exit_event_sp)
3502 {
3503 // We shouldn't need to do anything else here. There's no process left to detach from...
3504 StopPrivateStateThread();
3505 m_destroy_in_process = false;
3506 return error;
3507 }
3508 }
3509
Jim Inghamacff8952013-05-02 00:27:30 +00003510 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 if (error.Success())
3512 {
3513 DidDetach();
3514 StopPrivateStateThread();
3515 }
Jim Inghamacff8952013-05-02 00:27:30 +00003516 else
3517 {
3518 return error;
3519 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003520 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003521 m_destroy_in_process = false;
3522
3523 // If we exited when we were waiting for a process to stop, then
3524 // forward the event here so we don't lose the event
3525 if (exit_event_sp)
3526 {
3527 // Directly broadcast our exited event because we shut down our
3528 // private state thread above
3529 BroadcastEvent(exit_event_sp);
3530 }
3531
3532 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3533 // the last events through the event system, in which case we might strand the write lock. Unlock
3534 // it here so when we do to tear down the process we don't get an error destroying the lock.
3535
Ed Maste64fad602013-07-29 20:58:06 +00003536 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003537 return error;
3538}
3539
3540Error
3541Process::Destroy ()
3542{
Jim Ingham09437922013-03-01 20:04:25 +00003543
3544 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3545 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3546 // failed and the process stays around for some reason it won't be in a confused state.
3547
3548 m_destroy_in_process = true;
3549
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003550 Error error (WillDestroy());
3551 if (error.Success())
3552 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003553 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003554 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003555 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003556 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003557 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003558
Jim Inghamaacc3182012-06-06 00:29:30 +00003559 if (m_public_state.GetValue() != eStateRunning)
3560 {
3561 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3562 // kill it, we don't want it hitting a breakpoint...
3563 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3564 // we're not going to have much luck doing this now.
3565 m_thread_list.DiscardThreadPlans();
3566 DisableAllBreakpointSites();
3567 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003568
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003569 error = DoDestroy();
3570 if (error.Success())
3571 {
3572 DidDestroy();
3573 StopPrivateStateThread();
3574 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003575 m_stdio_communication.StopReadThread();
3576 m_stdio_communication.Disconnect();
3577 if (m_process_input_reader && m_process_input_reader->IsActive())
3578 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3579 if (m_process_input_reader)
3580 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003581
3582 // If we exited when we were waiting for a process to stop, then
3583 // forward the event here so we don't lose the event
3584 if (exit_event_sp)
3585 {
3586 // Directly broadcast our exited event because we shut down our
3587 // private state thread above
3588 BroadcastEvent(exit_event_sp);
3589 }
3590
Jim Inghamb1e2e842012-04-12 18:49:31 +00003591 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3592 // the last events through the event system, in which case we might strand the write lock. Unlock
3593 // 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 +00003594 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003595 }
Jim Ingham09437922013-03-01 20:04:25 +00003596
3597 m_destroy_in_process = false;
3598
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003599 return error;
3600}
3601
3602Error
3603Process::Signal (int signal)
3604{
3605 Error error (WillSignal());
3606 if (error.Success())
3607 {
3608 error = DoSignal(signal);
3609 if (error.Success())
3610 DidSignal();
3611 }
3612 return error;
3613}
3614
Greg Clayton514487e2011-02-15 21:59:32 +00003615lldb::ByteOrder
3616Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617{
Greg Clayton514487e2011-02-15 21:59:32 +00003618 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003619}
3620
3621uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003622Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003623{
Greg Clayton514487e2011-02-15 21:59:32 +00003624 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625}
3626
Greg Clayton514487e2011-02-15 21:59:32 +00003627
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003628bool
3629Process::ShouldBroadcastEvent (Event *event_ptr)
3630{
3631 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3632 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003633 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003634
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003635 switch (state)
3636 {
Greg Claytonb766a732011-02-04 01:58:07 +00003637 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003638 case eStateAttaching:
3639 case eStateLaunching:
3640 case eStateDetached:
3641 case eStateExited:
3642 case eStateUnloaded:
3643 // These events indicate changes in the state of the debugging session, always report them.
3644 return_value = true;
3645 break;
3646 case eStateInvalid:
3647 // We stopped for no apparent reason, don't report it.
3648 return_value = false;
3649 break;
3650 case eStateRunning:
3651 case eStateStepping:
3652 // If we've started the target running, we handle the cases where we
3653 // are already running and where there is a transition from stopped to
3654 // running differently.
3655 // running -> running: Automatically suppress extra running events
3656 // stopped -> running: Report except when there is one or more no votes
3657 // and no yes votes.
3658 SynchronouslyNotifyStateChanged (state);
Jim Ingham0161b492013-02-09 01:29:05 +00003659 switch (m_last_broadcast_state)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003660 {
3661 case eStateRunning:
3662 case eStateStepping:
3663 // We always suppress multiple runnings with no PUBLIC stop in between.
3664 return_value = false;
3665 break;
3666 default:
3667 // TODO: make this work correctly. For now always report
3668 // run if we aren't running so we don't miss any runnning
3669 // events. If I run the lldb/test/thread/a.out file and
3670 // break at main.cpp:58, run and hit the breakpoints on
3671 // multiple threads, then somehow during the stepping over
3672 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003673
3674 // This is a transition from stop to run.
3675 switch (m_thread_list.ShouldReportRun (event_ptr))
3676 {
3677 case eVoteYes:
3678 case eVoteNoOpinion:
3679 return_value = true;
3680 break;
3681 case eVoteNo:
3682 return_value = false;
3683 break;
3684 }
3685 break;
3686 }
3687 break;
3688 case eStateStopped:
3689 case eStateCrashed:
3690 case eStateSuspended:
3691 {
3692 // We've stopped. First see if we're going to restart the target.
3693 // If we are going to stop, then we always broadcast the event.
3694 // 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 +00003695 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003696
Jim Inghamcb4ca112012-05-16 01:32:14 +00003697 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003698 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003700 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003701 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3702 event_ptr,
3703 StateAsCString(state));
3704 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003705 }
3706 else
3707 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003708 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3709 bool should_resume = false;
3710
Jim Ingham0161b492013-02-09 01:29:05 +00003711 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3712 // Asking the thread list is also not likely to go well, since we are running again.
3713 // So in that case just report the event.
3714
Jim Ingham0161b492013-02-09 01:29:05 +00003715 if (!was_restarted)
3716 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003717
3718 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719 {
Jim Ingham0161b492013-02-09 01:29:05 +00003720 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3721 if (log)
3722 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3723 should_resume,
3724 StateAsCString(state),
3725 was_restarted,
3726 stop_vote);
3727
3728 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729 {
3730 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003731 return_value = true;
3732 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003734 case eVoteNo:
3735 return_value = false;
3736 break;
3737 }
Jim Ingham0161b492013-02-09 01:29:05 +00003738
Jim Inghamcb95f342012-09-05 21:13:56 +00003739 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003740 {
3741 if (log)
3742 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3743 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003744 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003745 }
3746
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747 }
3748 else
3749 {
3750 return_value = true;
3751 SynchronouslyNotifyStateChanged (state);
3752 }
3753 }
3754 }
Jim Ingham0161b492013-02-09 01:29:05 +00003755 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003756 }
Jim Ingham0161b492013-02-09 01:29:05 +00003757
3758 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3759 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3760 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3761 // because the PublicState reflects the last event pulled off the queue, and there may be several
3762 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3763 // yet. m_last_broadcast_state gets updated here.
3764
3765 if (return_value)
3766 m_last_broadcast_state = state;
3767
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003768 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003769 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3770 event_ptr,
3771 StateAsCString(state),
3772 StateAsCString(m_last_broadcast_state),
3773 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774 return return_value;
3775}
3776
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777
3778bool
Jim Ingham372787f2012-04-07 00:00:41 +00003779Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780{
Greg Clayton5160ce52013-03-27 23:08:40 +00003781 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782
Greg Clayton8b82f082011-04-12 05:54:46 +00003783 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003784 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003785 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3786
Jim Ingham372787f2012-04-07 00:00:41 +00003787 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003788 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789
3790 // Create a thread that watches our internal state and controls which
3791 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003792 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003793 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003794 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003795 else
Daniel Malead01b2952012-11-29 21:49:15 +00003796 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003797
3798 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003799 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003800 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3801 if (success)
3802 {
3803 ResumePrivateStateThread();
3804 return true;
3805 }
3806 else
3807 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003808}
3809
3810void
3811Process::PausePrivateStateThread ()
3812{
3813 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3814}
3815
3816void
3817Process::ResumePrivateStateThread ()
3818{
3819 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3820}
3821
3822void
3823Process::StopPrivateStateThread ()
3824{
Greg Clayton8b82f082011-04-12 05:54:46 +00003825 if (PrivateStateThreadIsValid ())
3826 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003827 else
3828 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003829 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003830 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003831 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003832 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003833}
3834
3835void
3836Process::ControlPrivateStateThread (uint32_t signal)
3837{
Greg Clayton5160ce52013-03-27 23:08:40 +00003838 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003839
3840 assert (signal == eBroadcastInternalStateControlStop ||
3841 signal == eBroadcastInternalStateControlPause ||
3842 signal == eBroadcastInternalStateControlResume);
3843
3844 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003845 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003846
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003847 // Signal the private state thread. First we should copy this is case the
3848 // thread starts exiting since the private state thread will NULL this out
3849 // when it exits
3850 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003851 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003852 {
3853 TimeValue timeout_time;
3854 bool timed_out;
3855
3856 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3857
3858 timeout_time = TimeValue::Now();
3859 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003860 if (log)
3861 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003862 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3863 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3864
3865 if (signal == eBroadcastInternalStateControlStop)
3866 {
3867 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003868 {
3869 Error error;
3870 Host::ThreadCancel (private_state_thread, &error);
3871 if (log)
3872 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3873 }
3874 else
3875 {
3876 if (log)
3877 log->Printf ("The control event killed the private state thread without having to cancel.");
3878 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879
3880 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003881 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003882 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883 }
3884 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003885 else
3886 {
3887 if (log)
3888 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3889 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890}
3891
3892void
Jim Inghamcfc09352012-07-27 23:57:19 +00003893Process::SendAsyncInterrupt ()
3894{
3895 if (PrivateStateThreadIsValid())
3896 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3897 else
3898 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3899}
3900
3901void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003902Process::HandlePrivateEvent (EventSP &event_sp)
3903{
Greg Clayton5160ce52013-03-27 23:08:40 +00003904 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003905 m_resume_requested = false;
3906
Jim Inghamaacc3182012-06-06 00:29:30 +00003907 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003908
Greg Clayton414f5d32011-01-25 02:58:48 +00003909 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003910
3911 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003912 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003913 {
Jim Ingham754ab982011-01-29 04:05:41 +00003914 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003915 if (log)
3916 log->Printf ("Ran next event action, result was %d.", action_result);
3917
Jim Inghambb3a2832011-01-29 01:49:25 +00003918 switch (action_result)
3919 {
3920 case NextEventAction::eEventActionSuccess:
3921 SetNextEventAction(NULL);
3922 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003923
Jim Inghambb3a2832011-01-29 01:49:25 +00003924 case NextEventAction::eEventActionRetry:
3925 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003926
Jim Inghambb3a2832011-01-29 01:49:25 +00003927 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003928 // Handle Exiting Here. If we already got an exited event,
3929 // we should just propagate it. Otherwise, swallow this event,
3930 // and set our state to exit so the next event will kill us.
3931 if (new_state != eStateExited)
3932 {
3933 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003934 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003935 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003936 SetNextEventAction(NULL);
3937 return;
3938 }
3939 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003940 break;
3941 }
3942 }
3943
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003944 // See if we should broadcast this state to external clients?
3945 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003946
3947 if (should_broadcast)
3948 {
3949 if (log)
3950 {
Daniel Malead01b2952012-11-29 21:49:15 +00003951 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003952 __FUNCTION__,
3953 GetID(),
3954 StateAsCString(new_state),
3955 StateAsCString (GetState ()),
3956 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957 }
Jim Ingham9575d842011-03-11 03:53:59 +00003958 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003959 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003960 PushProcessInputReader ();
Jim Inghamb78d73f2013-05-15 01:21:48 +00003961 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003962 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003963
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964 BroadcastEvent (event_sp);
3965 }
3966 else
3967 {
3968 if (log)
3969 {
Daniel Malead01b2952012-11-29 21:49:15 +00003970 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003971 __FUNCTION__,
3972 GetID(),
3973 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003974 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003975 }
3976 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003977 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978}
3979
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003980thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981Process::PrivateStateThread (void *arg)
3982{
3983 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003984 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003985 return result;
3986}
3987
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003988thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989Process::RunPrivateStateThread ()
3990{
Jim Ingham076b3042012-04-10 01:21:57 +00003991 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003992 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003993
Greg Clayton5160ce52013-03-27 23:08:40 +00003994 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003995 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003996 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003997
3998 bool exit_now = false;
3999 while (!exit_now)
4000 {
4001 EventSP event_sp;
4002 WaitForEventsPrivate (NULL, event_sp, control_only);
4003 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4004 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004005 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004006 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 +00004007
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004008 switch (event_sp->GetType())
4009 {
4010 case eBroadcastInternalStateControlStop:
4011 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004012 break; // doing any internal state managment below
4013
4014 case eBroadcastInternalStateControlPause:
4015 control_only = true;
4016 break;
4017
4018 case eBroadcastInternalStateControlResume:
4019 control_only = false;
4020 break;
4021 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004022
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004023 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004024 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004025 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004026 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4027 {
4028 if (m_public_state.GetValue() == eStateAttaching)
4029 {
4030 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004031 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 +00004032 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4033 }
4034 else
4035 {
4036 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004037 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004038 Halt();
4039 }
4040 continue;
4041 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042
4043 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4044
4045 if (internal_state != eStateInvalid)
4046 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004047 if (m_clear_thread_plans_on_stop &&
4048 StateIsStoppedState(internal_state, true))
4049 {
4050 m_clear_thread_plans_on_stop = false;
4051 m_thread_list.DiscardThreadPlans();
4052 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053 HandlePrivateEvent (event_sp);
4054 }
4055
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004056 if (internal_state == eStateInvalid ||
4057 internal_state == eStateExited ||
4058 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004059 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004060 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004061 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 +00004062
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004063 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004064 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004065 }
4066
Caroline Tice20ad3c42010-10-29 21:48:37 +00004067 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004068 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004069 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004070
Ed Maste64fad602013-07-29 20:58:06 +00004071 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004072 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4073 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074 return NULL;
4075}
4076
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004077//------------------------------------------------------------------
4078// Process Event Data
4079//------------------------------------------------------------------
4080
4081Process::ProcessEventData::ProcessEventData () :
4082 EventData (),
4083 m_process_sp (),
4084 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004085 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004086 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004087 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004088{
4089}
4090
4091Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4092 EventData (),
4093 m_process_sp (process_sp),
4094 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004095 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004096 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004097 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098{
4099}
4100
4101Process::ProcessEventData::~ProcessEventData()
4102{
4103}
4104
4105const ConstString &
4106Process::ProcessEventData::GetFlavorString ()
4107{
4108 static ConstString g_flavor ("Process::ProcessEventData");
4109 return g_flavor;
4110}
4111
4112const ConstString &
4113Process::ProcessEventData::GetFlavor () const
4114{
4115 return ProcessEventData::GetFlavorString ();
4116}
4117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004118void
4119Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4120{
4121 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004122 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4123 // the public event queue, then other times when we're pretending that this is where we stopped at the
4124 // end of expression evaluation. m_update_state is used to distinguish these
4125 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004126 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004127 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004129
Jim Ingham221d51c2013-05-08 00:35:16 +00004130 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131
4132 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4133 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004134 {
4135 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004136 uint32_t num_threads = curr_thread_list.GetSize();
4137 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004138
Jim Ingham4b536182011-08-09 02:12:22 +00004139 // The actions might change one of the thread's stop_info's opinions about whether we should
4140 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004141
4142 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4143 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4144 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4145 // 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
4146 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004147 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004148 for (idx = 0; idx < num_threads; ++idx)
4149 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4150
Jim Inghamc7078c22012-12-13 22:24:15 +00004151 // Use this to track whether we should continue from here. We will only continue the target running if
4152 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4153 // then it doesn't matter what the other threads say...
4154
4155 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004156
Jim Ingham0ad7e052013-04-25 02:04:59 +00004157 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4158 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4159 // thing to do is, and it's better to let the user decide than continue behind their backs.
4160
4161 bool does_anybody_have_an_opinion = false;
4162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004163 for (idx = 0; idx < num_threads; ++idx)
4164 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004165 curr_thread_list = m_process_sp->GetThreadList();
4166 if (curr_thread_list.GetSize() != num_threads)
4167 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004168 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004169 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004170 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 +00004171 break;
4172 }
4173
4174 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4175
4176 if (thread_sp->GetIndexID() != thread_index_array[idx])
4177 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004178 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004179 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004180 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004181 idx,
4182 thread_index_array[idx],
4183 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004184 break;
4185 }
4186
Jim Inghamb15bfc72010-10-20 00:39:53 +00004187 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004188 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004189 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004190 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004191 bool this_thread_wants_to_stop;
4192 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004193 {
Jim Ingham0161b492013-02-09 01:29:05 +00004194 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4195 }
4196 else
4197 {
4198 stop_info_sp->PerformAction(event_ptr);
4199 // The stop action might restart the target. If it does, then we want to mark that in the
4200 // event so that whoever is receiving it will know to wait for the running event and reflect
4201 // that state appropriately.
4202 // We also need to stop processing actions, since they aren't expecting the target to be running.
4203
4204 // FIXME: we might have run.
4205 if (stop_info_sp->HasTargetRunSinceMe())
4206 {
4207 SetRestarted (true);
4208 break;
4209 }
4210
4211 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004212 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004213
Jim Inghamc7078c22012-12-13 22:24:15 +00004214 if (still_should_stop == false)
4215 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004216 }
4217 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004218
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004219
Jim Inghama8ca6e22013-05-03 23:04:37 +00004220 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004221 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004222 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004223 {
4224 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004225 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004226 // Use the public resume method here, since this is just
4227 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004228 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004229 }
4230 else
4231 {
4232 // If we didn't restart, run the Stop Hooks here:
4233 // They might also restart the target, so watch for that.
4234 m_process_sp->GetTarget().RunStopHooks();
4235 if (m_process_sp->GetPrivateState() == eStateRunning)
4236 SetRestarted(true);
4237 }
Jim Ingham9575d842011-03-11 03:53:59 +00004238 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239 }
4240}
4241
4242void
4243Process::ProcessEventData::Dump (Stream *s) const
4244{
4245 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004246 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004247
Greg Clayton8b82f082011-04-12 05:54:46 +00004248 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004249}
4250
4251const Process::ProcessEventData *
4252Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4253{
4254 if (event_ptr)
4255 {
4256 const EventData *event_data = event_ptr->GetData();
4257 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4258 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4259 }
4260 return NULL;
4261}
4262
4263ProcessSP
4264Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4265{
4266 ProcessSP process_sp;
4267 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4268 if (data)
4269 process_sp = data->GetProcessSP();
4270 return process_sp;
4271}
4272
4273StateType
4274Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4275{
4276 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4277 if (data == NULL)
4278 return eStateInvalid;
4279 else
4280 return data->GetState();
4281}
4282
4283bool
4284Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4285{
4286 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4287 if (data == NULL)
4288 return false;
4289 else
4290 return data->GetRestarted();
4291}
4292
4293void
4294Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4295{
4296 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4297 if (data != NULL)
4298 data->SetRestarted(new_value);
4299}
4300
Jim Ingham0161b492013-02-09 01:29:05 +00004301size_t
4302Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4303{
4304 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4305 if (data != NULL)
4306 return data->GetNumRestartedReasons();
4307 else
4308 return 0;
4309}
4310
4311const char *
4312Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4313{
4314 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4315 if (data != NULL)
4316 return data->GetRestartedReasonAtIndex(idx);
4317 else
4318 return NULL;
4319}
4320
4321void
4322Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4323{
4324 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4325 if (data != NULL)
4326 data->AddRestartedReason(reason);
4327}
4328
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004329bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004330Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4331{
4332 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4333 if (data == NULL)
4334 return false;
4335 else
4336 return data->GetInterrupted ();
4337}
4338
4339void
4340Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4341{
4342 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4343 if (data != NULL)
4344 data->SetInterrupted(new_value);
4345}
4346
4347bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4349{
4350 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4351 if (data)
4352 {
4353 data->SetUpdateStateOnRemoval();
4354 return true;
4355 }
4356 return false;
4357}
4358
Greg Claytond9e416c2012-02-18 05:35:26 +00004359lldb::TargetSP
4360Process::CalculateTarget ()
4361{
4362 return m_target.shared_from_this();
4363}
4364
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004365void
Greg Clayton0603aa92010-10-04 01:05:56 +00004366Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004367{
Greg Claytonc14ee322011-09-22 04:58:26 +00004368 exe_ctx.SetTargetPtr (&m_target);
4369 exe_ctx.SetProcessPtr (this);
4370 exe_ctx.SetThreadPtr(NULL);
4371 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004372}
4373
Greg Claytone996fd32011-03-08 22:40:15 +00004374//uint32_t
4375//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4376//{
4377// return 0;
4378//}
4379//
4380//ArchSpec
4381//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4382//{
4383// return Host::GetArchSpecForExistingProcess (pid);
4384//}
4385//
4386//ArchSpec
4387//Process::GetArchSpecForExistingProcess (const char *process_name)
4388//{
4389// return Host::GetArchSpecForExistingProcess (process_name);
4390//}
4391//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004392void
4393Process::AppendSTDOUT (const char * s, size_t len)
4394{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004395 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004396 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004397 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004398}
4399
4400void
Greg Clayton93e86192011-11-13 04:45:22 +00004401Process::AppendSTDERR (const char * s, size_t len)
4402{
4403 Mutex::Locker locker (m_stdio_communication_mutex);
4404 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004405 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004406}
4407
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004408void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004409Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004410{
4411 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004412 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004413 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4414}
4415
4416size_t
4417Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4418{
4419 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004420 if (m_profile_data.empty())
4421 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004422
4423 std::string &one_profile_data = m_profile_data.front();
4424 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004425 if (bytes_available > 0)
4426 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004427 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004428 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004429 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004430 if (bytes_available > buf_size)
4431 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004432 memcpy(buf, one_profile_data.c_str(), buf_size);
4433 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004434 bytes_available = buf_size;
4435 }
4436 else
4437 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004438 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004439 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004440 }
4441 }
4442 return bytes_available;
4443}
4444
4445
Greg Clayton93e86192011-11-13 04:45:22 +00004446//------------------------------------------------------------------
4447// Process STDIO
4448//------------------------------------------------------------------
4449
4450size_t
4451Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4452{
4453 Mutex::Locker locker(m_stdio_communication_mutex);
4454 size_t bytes_available = m_stdout_data.size();
4455 if (bytes_available > 0)
4456 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004457 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004458 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004459 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004460 if (bytes_available > buf_size)
4461 {
4462 memcpy(buf, m_stdout_data.c_str(), buf_size);
4463 m_stdout_data.erase(0, buf_size);
4464 bytes_available = buf_size;
4465 }
4466 else
4467 {
4468 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4469 m_stdout_data.clear();
4470 }
4471 }
4472 return bytes_available;
4473}
4474
4475
4476size_t
4477Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4478{
4479 Mutex::Locker locker(m_stdio_communication_mutex);
4480 size_t bytes_available = m_stderr_data.size();
4481 if (bytes_available > 0)
4482 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004483 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004484 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004485 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004486 if (bytes_available > buf_size)
4487 {
4488 memcpy(buf, m_stderr_data.c_str(), buf_size);
4489 m_stderr_data.erase(0, buf_size);
4490 bytes_available = buf_size;
4491 }
4492 else
4493 {
4494 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4495 m_stderr_data.clear();
4496 }
4497 }
4498 return bytes_available;
4499}
4500
4501void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004502Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4503{
4504 Process *process = (Process *) baton;
4505 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4506}
4507
4508size_t
4509Process::ProcessInputReaderCallback (void *baton,
4510 InputReader &reader,
4511 lldb::InputReaderAction notification,
4512 const char *bytes,
4513 size_t bytes_len)
4514{
4515 Process *process = (Process *) baton;
4516
4517 switch (notification)
4518 {
4519 case eInputReaderActivate:
4520 break;
4521
4522 case eInputReaderDeactivate:
4523 break;
4524
4525 case eInputReaderReactivate:
4526 break;
4527
Caroline Tice969ed3d2011-05-02 20:41:46 +00004528 case eInputReaderAsynchronousOutputWritten:
4529 break;
4530
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004531 case eInputReaderGotToken:
4532 {
4533 Error error;
4534 process->PutSTDIN (bytes, bytes_len, error);
4535 }
4536 break;
4537
Caroline Ticeefed6132010-11-19 20:47:54 +00004538 case eInputReaderInterrupt:
Jim Inghamfc65a502013-06-19 00:56:17 +00004539 process->SendAsyncInterrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +00004540 break;
4541
4542 case eInputReaderEndOfFile:
4543 process->AppendSTDOUT ("^D", 2);
4544 break;
4545
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004546 case eInputReaderDone:
4547 break;
4548
4549 }
4550
4551 return bytes_len;
4552}
4553
4554void
4555Process::ResetProcessInputReader ()
4556{
4557 m_process_input_reader.reset();
4558}
4559
4560void
Greg Claytonee95ed52011-11-17 22:14:31 +00004561Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004562{
4563 // First set up the Read Thread for reading/handling process I/O
4564
Greg Clayton7b0992d2013-04-18 22:45:39 +00004565 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004566
4567 if (conn_ap.get())
4568 {
4569 m_stdio_communication.SetConnection (conn_ap.release());
4570 if (m_stdio_communication.IsConnected())
4571 {
4572 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4573 m_stdio_communication.StartReadThread();
4574
4575 // Now read thread is set up, set up input reader.
4576
4577 if (!m_process_input_reader.get())
4578 {
4579 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4580 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4581 this,
4582 eInputReaderGranularityByte,
4583 NULL,
4584 NULL,
4585 false));
4586
4587 if (err.Fail())
4588 m_process_input_reader.reset();
4589 }
4590 }
4591 }
4592}
4593
4594void
4595Process::PushProcessInputReader ()
4596{
4597 if (m_process_input_reader && !m_process_input_reader->IsActive())
4598 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4599}
4600
4601void
4602Process::PopProcessInputReader ()
4603{
4604 if (m_process_input_reader && m_process_input_reader->IsActive())
4605 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4606}
4607
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004608// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004609void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004610Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004611{
Greg Clayton67cc0632012-08-22 17:17:09 +00004612// static std::vector<OptionEnumValueElement> g_plugins;
4613//
4614// int i=0;
4615// const char *name;
4616// OptionEnumValueElement option_enum;
4617// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4618// {
4619// if (name)
4620// {
4621// option_enum.value = i;
4622// option_enum.string_value = name;
4623// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4624// g_plugins.push_back (option_enum);
4625// }
4626// ++i;
4627// }
4628// option_enum.value = 0;
4629// option_enum.string_value = NULL;
4630// option_enum.usage = NULL;
4631// g_plugins.push_back (option_enum);
4632//
4633// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4634// {
4635// if (::strcmp (name, "plugin") == 0)
4636// {
4637// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4638// break;
4639// }
4640// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004641//
Greg Clayton6920b522012-08-22 18:39:03 +00004642 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004643}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004644
Greg Clayton99d0faf2010-11-18 23:32:35 +00004645void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004646Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004647{
Greg Clayton6920b522012-08-22 18:39:03 +00004648 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004649}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004650
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004651ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004652Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004653 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004654 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004655 bool run_others,
Jim Ingham184e9812013-01-15 02:47:48 +00004656 bool unwind_on_error,
4657 bool ignore_breakpoints,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004658 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004659 Stream &errors)
4660{
4661 ExecutionResults return_value = eExecutionSetupError;
4662
Jim Ingham77787032011-01-20 02:03:18 +00004663 if (thread_plan_sp.get() == NULL)
4664 {
4665 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004666 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004667 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004668
4669 if (!thread_plan_sp->ValidatePlan(NULL))
4670 {
4671 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4672 return eExecutionSetupError;
4673 }
4674
Greg Claytonc14ee322011-09-22 04:58:26 +00004675 if (exe_ctx.GetProcessPtr() != this)
4676 {
4677 errors.Printf("RunThreadPlan called on wrong process.");
4678 return eExecutionSetupError;
4679 }
4680
4681 Thread *thread = exe_ctx.GetThreadPtr();
4682 if (thread == NULL)
4683 {
4684 errors.Printf("RunThreadPlan called with invalid thread.");
4685 return eExecutionSetupError;
4686 }
Jim Ingham77787032011-01-20 02:03:18 +00004687
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004688 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4689 // For that to be true the plan can't be private - since private plans suppress themselves in the
4690 // GetCompletedPlan call.
4691
4692 bool orig_plan_private = thread_plan_sp->GetPrivate();
4693 thread_plan_sp->SetPrivate(false);
4694
Jim Ingham444586b2011-01-24 06:34:17 +00004695 if (m_private_state.GetValue() != eStateStopped)
4696 {
4697 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004698 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004699 }
4700
Jim Ingham66243842011-08-13 00:56:10 +00004701 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004702 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham11b0e052013-02-19 23:22:45 +00004703 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4704 if (!selected_frame_sp)
4705 {
4706 thread->SetSelectedFrame(0);
4707 selected_frame_sp = thread->GetSelectedFrame();
4708 if (!selected_frame_sp)
4709 {
4710 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4711 return eExecutionSetupError;
4712 }
4713 }
4714
4715 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004716
4717 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4718 // so we should arrange to reset them as well.
4719
Greg Claytonc14ee322011-09-22 04:58:26 +00004720 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004721
Jim Ingham66243842011-08-13 00:56:10 +00004722 uint32_t selected_tid;
4723 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004724 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004725 {
4726 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004727 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004728 }
4729 else
4730 {
4731 selected_tid = LLDB_INVALID_THREAD_ID;
4732 }
4733
Jim Ingham372787f2012-04-07 00:00:41 +00004734 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004735 lldb::StateType old_state;
4736 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004737
Greg Clayton5160ce52013-03-27 23:08:40 +00004738 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004739 if (Host::GetCurrentThread() == m_private_state_thread)
4740 {
Jim Ingham076b3042012-04-10 01:21:57 +00004741 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4742 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004743 // 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 +00004744 // we are fielding public events here.
4745 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004746 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 +00004747
4748
Jim Ingham372787f2012-04-07 00:00:41 +00004749 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004750
4751 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4752 // returning control here.
4753 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4754 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4755 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4756 // do just what we want.
4757 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4758 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4759 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4760 old_state = m_public_state.GetValue();
4761 m_public_state.SetValueNoLock(eStateStopped);
4762
4763 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004764 StartPrivateStateThread(true);
4765 }
4766
4767 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004768
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004769 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004770
Sean Callanana46ec452012-07-11 21:31:24 +00004771 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004772
Jim Ingham77787032011-01-20 02:03:18 +00004773 {
Sean Callanana46ec452012-07-11 21:31:24 +00004774 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4775 // restored on exit to the function.
4776 //
4777 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4778 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004779
Sean Callanana46ec452012-07-11 21:31:24 +00004780 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004781
Jim Inghamf48169b2010-11-30 02:22:11 +00004782 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004783 {
4784 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004785 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004786 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004787 thread->GetIndexID(),
4788 thread->GetID(),
4789 s.GetData());
4790 }
4791
4792 bool got_event;
4793 lldb::EventSP event_sp;
4794 lldb::StateType stop_state = lldb::eStateInvalid;
4795
4796 TimeValue* timeout_ptr = NULL;
4797 TimeValue real_timeout;
4798
Jim Ingham0161b492013-02-09 01:29:05 +00004799 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 +00004800 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004801 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004802 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00004803
Jim Ingham0161b492013-02-09 01:29:05 +00004804 // This is just for accounting:
4805 uint32_t num_resumes = 0;
4806
4807 TimeValue one_thread_timeout = TimeValue::Now();
4808 TimeValue final_timeout = one_thread_timeout;
4809
4810 if (run_others)
4811 {
4812 // If we are running all threads then we take half the time to run all threads, bounded by
4813 // .25 sec.
4814 if (timeout_usec == 0)
4815 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4816 else
4817 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00004818 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00004819 if (computed_timeout > default_one_thread_timeout_usec)
4820 computed_timeout = default_one_thread_timeout_usec;
4821 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4822 }
4823 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4824 }
4825 else
4826 {
4827 if (timeout_usec != 0)
4828 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4829 }
4830
Jim Ingham8559a352012-11-26 23:52:18 +00004831 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4832 // So don't call return anywhere within it.
4833
Sean Callanana46ec452012-07-11 21:31:24 +00004834 while (1)
4835 {
4836 // We usually want to resume the process if we get to the top of the loop.
4837 // The only exception is if we get two running events with no intervening
4838 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004839 if (log)
4840 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4841 do_resume,
4842 handle_running_event,
4843 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004844
Jim Ingham184e9812013-01-15 02:47:48 +00004845 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00004846 {
4847 // Do the initial resume and wait for the running event before going further.
4848
Jim Ingham184e9812013-01-15 02:47:48 +00004849 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00004850 {
Jim Ingham0161b492013-02-09 01:29:05 +00004851 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00004852 Error resume_error = PrivateResume ();
4853 if (!resume_error.Success())
4854 {
Jim Ingham0161b492013-02-09 01:29:05 +00004855 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4856 num_resumes,
4857 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00004858 return_value = eExecutionSetupError;
4859 break;
4860 }
Sean Callanana46ec452012-07-11 21:31:24 +00004861 }
Sean Callanana46ec452012-07-11 21:31:24 +00004862
Jim Ingham0161b492013-02-09 01:29:05 +00004863 TimeValue resume_timeout = TimeValue::Now();
4864 resume_timeout.OffsetWithMicroSeconds(500000);
4865
4866 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00004867 if (!got_event)
4868 {
4869 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004870 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4871 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004872
Jim Ingham0161b492013-02-09 01:29:05 +00004873 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004874 return_value = eExecutionSetupError;
4875 break;
4876 }
4877
4878 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00004879
Sean Callanana46ec452012-07-11 21:31:24 +00004880 if (stop_state != eStateRunning)
4881 {
Jim Ingham0161b492013-02-09 01:29:05 +00004882 bool restarted = false;
4883
4884 if (stop_state == eStateStopped)
4885 {
4886 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4887 if (log)
4888 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4889 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4890 num_resumes,
4891 StateAsCString(stop_state),
4892 restarted,
4893 do_resume,
4894 handle_running_event);
4895 }
4896
4897 if (restarted)
4898 {
4899 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4900 // event here. But if I do, the best thing is to Halt and then get out of here.
4901 Halt();
4902 }
4903
Jim Ingham35e1bda2012-10-16 21:41:58 +00004904 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4905 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004906 return_value = eExecutionSetupError;
4907 break;
4908 }
4909
4910 if (log)
4911 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4912 // We need to call the function synchronously, so spin waiting for it to return.
4913 // If we get interrupted while executing, we're going to lose our context, and
4914 // won't be able to gather the result at this point.
4915 // We set the timeout AFTER the resume, since the resume takes some time and we
4916 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00004917 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004918 else
4919 {
Sean Callanana46ec452012-07-11 21:31:24 +00004920 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004921 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004922 }
Jim Ingham0161b492013-02-09 01:29:05 +00004923
4924 if (before_first_timeout)
4925 {
4926 if (run_others)
4927 timeout_ptr = &one_thread_timeout;
4928 else
4929 {
4930 if (timeout_usec == 0)
4931 timeout_ptr = NULL;
4932 else
4933 timeout_ptr = &final_timeout;
4934 }
4935 }
4936 else
4937 {
4938 if (timeout_usec == 0)
4939 timeout_ptr = NULL;
4940 else
4941 timeout_ptr = &final_timeout;
4942 }
4943
4944 do_resume = true;
4945 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004946
Sean Callanana46ec452012-07-11 21:31:24 +00004947 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004948 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004949
Jim Ingham0f16e732011-02-08 05:20:59 +00004950 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004951 {
Sean Callanana46ec452012-07-11 21:31:24 +00004952 if (timeout_ptr)
4953 {
Matt Kopec676a4872013-02-21 23:55:31 +00004954 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00004955 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4956 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00004957 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004958 else
Sean Callanana46ec452012-07-11 21:31:24 +00004959 {
4960 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4961 }
4962 }
4963
4964 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4965
4966 if (got_event)
4967 {
4968 if (event_sp.get())
4969 {
4970 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004971 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004972 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004973 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00004974 return_value = eExecutionInterrupted;
4975 errors.Printf ("Execution halted by user interrupt.");
4976 if (log)
4977 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00004978 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00004979 }
4980 else
4981 {
4982 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4983 if (log)
4984 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4985
4986 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004987 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004988 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004989 {
Jim Ingham0161b492013-02-09 01:29:05 +00004990 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00004991 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4992 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004993 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004994 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004995 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004996 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4997 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004998 }
4999 else
5000 {
Jim Ingham0161b492013-02-09 01:29:05 +00005001 // If we were restarted, we just need to go back up to fetch another event.
5002 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005003 {
5004 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005005 {
5006 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5007 }
5008 keep_going = true;
5009 do_resume = false;
5010 handle_running_event = true;
5011
Jim Inghamcfc09352012-07-27 23:57:19 +00005012 }
5013 else
5014 {
Jim Ingham0161b492013-02-09 01:29:05 +00005015
5016 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5017 StopReason stop_reason = eStopReasonInvalid;
5018 if (stop_info_sp)
5019 stop_reason = stop_info_sp->GetStopReason();
5020
5021
5022 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5023 // it is OUR plan that is complete?
5024 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005025 {
5026 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005027 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5028 // Now mark this plan as private so it doesn't get reported as the stop reason
5029 // after this point.
5030 if (thread_plan_sp)
5031 thread_plan_sp->SetPrivate (orig_plan_private);
5032 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005033 }
5034 else
5035 {
Jim Ingham0161b492013-02-09 01:29:05 +00005036 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005037 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005038 {
5039 if (log)
5040 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005041 return_value = eExecutionHitBreakpoint;
Sean Callanan4b388c92013-07-30 19:54:09 +00005042 if (!ignore_breakpoints)
5043 {
5044 event_to_broadcast_sp = event_sp;
5045 }
Jim Ingham0161b492013-02-09 01:29:05 +00005046 }
Jim Ingham184e9812013-01-15 02:47:48 +00005047 else
Jim Ingham0161b492013-02-09 01:29:05 +00005048 {
5049 if (log)
5050 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanan4b388c92013-07-30 19:54:09 +00005051 if (!unwind_on_error)
5052 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005053 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005054 }
Jim Ingham184e9812013-01-15 02:47:48 +00005055 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005056 }
Sean Callanana46ec452012-07-11 21:31:24 +00005057 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005058 }
5059 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005060
Jim Inghamcfc09352012-07-27 23:57:19 +00005061 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005062 // This shouldn't really happen, but sometimes we do get two running events without an
5063 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005064 do_resume = false;
5065 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005066 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005067 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005068
Jim Inghamcfc09352012-07-27 23:57:19 +00005069 default:
5070 if (log)
5071 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5072
5073 if (stop_state == eStateExited)
5074 event_to_broadcast_sp = event_sp;
5075
Sean Callananbf154da2012-08-08 17:35:10 +00005076 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005077 return_value = eExecutionInterrupted;
5078 break;
5079 }
Sean Callanana46ec452012-07-11 21:31:24 +00005080 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005081
Sean Callanana46ec452012-07-11 21:31:24 +00005082 if (keep_going)
5083 continue;
5084 else
5085 break;
5086 }
5087 else
5088 {
5089 if (log)
5090 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5091 return_value = eExecutionInterrupted;
5092 break;
5093 }
5094 }
5095 else
5096 {
5097 // If we didn't get an event that means we've timed out...
5098 // We will interrupt the process here. Depending on what we were asked to do we will
5099 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005100
5101 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00005102 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00005103 {
Jim Ingham0161b492013-02-09 01:29:05 +00005104 uint64_t remaining_time = final_timeout - TimeValue::Now();
5105 if (before_first_timeout)
5106 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5107 "running till for %" PRId64 " usec with all threads enabled.",
5108 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005109 else
5110 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005111 "and timeout: %d timed out, abandoning execution.",
5112 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005113 }
5114 else
5115 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005116 "abandoning execution.",
5117 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005118 }
5119
Jim Ingham0161b492013-02-09 01:29:05 +00005120 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5121 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5122 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5123 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5124 // stopped event. That's what this while loop does.
5125
5126 bool back_to_top = true;
5127 uint32_t try_halt_again = 0;
5128 bool do_halt = true;
5129 const uint32_t num_retries = 5;
5130 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005131 {
Jim Ingham0161b492013-02-09 01:29:05 +00005132 Error halt_error;
5133 if (do_halt)
5134 {
5135 if (log)
5136 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5137 halt_error = Halt();
5138 }
5139 if (halt_error.Success())
5140 {
5141 if (log)
5142 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5143
5144 real_timeout = TimeValue::Now();
5145 real_timeout.OffsetWithMicroSeconds(500000);
5146
5147 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005148
Jim Ingham0161b492013-02-09 01:29:05 +00005149 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005150 {
Jim Ingham0161b492013-02-09 01:29:05 +00005151 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5152 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005153 {
Jim Ingham0161b492013-02-09 01:29:05 +00005154 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5155 if (stop_state == lldb::eStateStopped
5156 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5157 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005158 }
5159
Jim Ingham0161b492013-02-09 01:29:05 +00005160 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005161 {
Jim Ingham0161b492013-02-09 01:29:05 +00005162 // Between the time we initiated the Halt and the time we delivered it, the process could have
5163 // already finished its job. Check that here:
5164
5165 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5166 {
5167 if (log)
5168 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5169 "Exiting wait loop.");
5170 return_value = eExecutionCompleted;
5171 back_to_top = false;
5172 break;
5173 }
5174
5175 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5176 {
5177 if (log)
5178 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5179 "Exiting wait loop.");
5180 try_halt_again++;
5181 do_halt = false;
5182 continue;
5183 }
Sean Callanana46ec452012-07-11 21:31:24 +00005184
Jim Ingham0161b492013-02-09 01:29:05 +00005185 if (!run_others)
5186 {
5187 if (log)
5188 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5189 return_value = eExecutionInterrupted;
5190 back_to_top = false;
5191 break;
5192 }
5193
5194 if (before_first_timeout)
5195 {
5196 // Set all the other threads to run, and return to the top of the loop, which will continue;
5197 before_first_timeout = false;
5198 thread_plan_sp->SetStopOthers (false);
5199 if (log)
5200 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005201
Jim Ingham0161b492013-02-09 01:29:05 +00005202 back_to_top = true;
5203 break;
5204 }
5205 else
5206 {
5207 // Running all threads failed, so return Interrupted.
5208 if (log)
5209 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5210 return_value = eExecutionInterrupted;
5211 back_to_top = false;
5212 break;
5213 }
Sean Callanana46ec452012-07-11 21:31:24 +00005214 }
5215 }
5216 else
Jim Ingham0161b492013-02-09 01:29:05 +00005217 { if (log)
5218 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5219 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005220 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005221 back_to_top = false;
5222 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005223 }
5224 }
Jim Ingham0161b492013-02-09 01:29:05 +00005225 else
5226 {
5227 try_halt_again++;
5228 continue;
5229 }
Sean Callanana46ec452012-07-11 21:31:24 +00005230 }
Jim Ingham0161b492013-02-09 01:29:05 +00005231
5232 if (!back_to_top || try_halt_again > num_retries)
5233 break;
5234 else
5235 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005236 }
Sean Callanana46ec452012-07-11 21:31:24 +00005237 } // END WAIT LOOP
5238
5239 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5240 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5241 {
5242 StopPrivateStateThread();
5243 Error error;
5244 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005245 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005246 {
5247 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5248 }
5249 m_public_state.SetValueNoLock(old_state);
5250
5251 }
5252
Jim Ingham184e9812013-01-15 02:47:48 +00005253 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5254 // could happen:
5255 // 1) The execution successfully completed
5256 // 2) We hit a breakpoint, and ignore_breakpoints was true
5257 // 3) We got some other error, and discard_on_error was true
5258 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5259 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham8559a352012-11-26 23:52:18 +00005260
Jim Ingham184e9812013-01-15 02:47:48 +00005261 if (return_value == eExecutionCompleted
5262 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005263 {
5264 thread_plan_sp->RestoreThreadState();
5265 }
Sean Callanana46ec452012-07-11 21:31:24 +00005266
5267 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005268 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005269 {
5270 if (log)
5271 {
5272 StreamString s;
5273 if (event_sp)
5274 event_sp->Dump (&s);
5275 else
5276 {
5277 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5278 }
5279
5280 StreamString ts;
5281
5282 const char *event_explanation = NULL;
5283
5284 do
5285 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005286 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005287 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005288 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005289 break;
5290 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005291 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005292 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005293 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005294 break;
5295 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005296 else
Sean Callanana46ec452012-07-11 21:31:24 +00005297 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005298 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5299
5300 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005301 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005302 event_explanation = "<no event data>";
5303 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005304 }
5305
Jim Inghamcfc09352012-07-27 23:57:19 +00005306 Process *process = event_data->GetProcessSP().get();
5307
5308 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005309 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005310 event_explanation = "<no process>";
5311 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005312 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005313
5314 ThreadList &thread_list = process->GetThreadList();
5315
5316 uint32_t num_threads = thread_list.GetSize();
5317 uint32_t thread_index;
5318
5319 ts.Printf("<%u threads> ", num_threads);
5320
5321 for (thread_index = 0;
5322 thread_index < num_threads;
5323 ++thread_index)
5324 {
5325 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5326
5327 if (!thread)
5328 {
5329 ts.Printf("<?> ");
5330 continue;
5331 }
5332
Daniel Malead01b2952012-11-29 21:49:15 +00005333 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005334 RegisterContext *register_context = thread->GetRegisterContext().get();
5335
5336 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005337 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005338 else
5339 ts.Printf("[ip unknown] ");
5340
5341 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5342 if (stop_info_sp)
5343 {
5344 const char *stop_desc = stop_info_sp->GetDescription();
5345 if (stop_desc)
5346 ts.PutCString (stop_desc);
5347 }
5348 ts.Printf(">");
5349 }
5350
5351 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005352 }
Sean Callanana46ec452012-07-11 21:31:24 +00005353 } while (0);
5354
Jim Inghamcfc09352012-07-27 23:57:19 +00005355 if (event_explanation)
5356 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005357 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005358 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5359 }
5360
Jim Ingham184e9812013-01-15 02:47:48 +00005361 if (should_unwind && thread_plan_sp)
Jim Inghamcfc09352012-07-27 23:57:19 +00005362 {
5363 if (log)
5364 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5365 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5366 thread_plan_sp->SetPrivate (orig_plan_private);
5367 }
5368 else
5369 {
5370 if (log)
5371 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005372 }
5373 }
5374 else if (return_value == eExecutionSetupError)
5375 {
5376 if (log)
5377 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005378
Jim Ingham184e9812013-01-15 02:47:48 +00005379 if (unwind_on_error && thread_plan_sp)
Jim Ingham0f16e732011-02-08 05:20:59 +00005380 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005381 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005382 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005383 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005384 }
5385 else
5386 {
Sean Callanana46ec452012-07-11 21:31:24 +00005387 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005388 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005389 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005390 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5391 return_value = eExecutionCompleted;
5392 }
5393 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5394 {
5395 if (log)
5396 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5397 return_value = eExecutionDiscarded;
5398 }
5399 else
5400 {
5401 if (log)
5402 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham184e9812013-01-15 02:47:48 +00005403 if (unwind_on_error && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005404 {
5405 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005406 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005407 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5408 thread_plan_sp->SetPrivate (orig_plan_private);
5409 }
5410 }
5411 }
5412
5413 // Thread we ran the function in may have gone away because we ran the target
5414 // Check that it's still there, and if it is put it back in the context. Also restore the
5415 // frame in the context if it is still present.
5416 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5417 if (thread)
5418 {
5419 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5420 }
5421
5422 // Also restore the current process'es selected frame & thread, since this function calling may
5423 // be done behind the user's back.
5424
5425 if (selected_tid != LLDB_INVALID_THREAD_ID)
5426 {
5427 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5428 {
5429 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005430 Mutex::Locker lock(GetThreadList().GetMutex());
Sean Callanana46ec452012-07-11 21:31:24 +00005431 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5432 if (old_frame_sp)
5433 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005434 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005435 }
5436 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005437
Sean Callanana46ec452012-07-11 21:31:24 +00005438 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005439
Sean Callanana46ec452012-07-11 21:31:24 +00005440 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005441 {
Sean Callanana46ec452012-07-11 21:31:24 +00005442 if (log)
5443 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5444 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005445 }
5446
5447 return return_value;
5448}
5449
5450const char *
5451Process::ExecutionResultAsCString (ExecutionResults result)
5452{
5453 const char *result_name;
5454
5455 switch (result)
5456 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005457 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005458 result_name = "eExecutionCompleted";
5459 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005460 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005461 result_name = "eExecutionDiscarded";
5462 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005463 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005464 result_name = "eExecutionInterrupted";
5465 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005466 case eExecutionHitBreakpoint:
5467 result_name = "eExecutionHitBreakpoint";
5468 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005469 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005470 result_name = "eExecutionSetupError";
5471 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005472 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005473 result_name = "eExecutionTimedOut";
5474 break;
5475 }
5476 return result_name;
5477}
5478
Greg Clayton7260f622011-04-18 08:33:37 +00005479void
5480Process::GetStatus (Stream &strm)
5481{
5482 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005483 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005484 {
5485 if (state == eStateExited)
5486 {
5487 int exit_status = GetExitStatus();
5488 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005489 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005490 GetID(),
5491 exit_status,
5492 exit_status,
5493 exit_description ? exit_description : "");
5494 }
5495 else
5496 {
5497 if (state == eStateConnected)
5498 strm.Printf ("Connected to remote target.\n");
5499 else
Daniel Malead01b2952012-11-29 21:49:15 +00005500 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005501 }
5502 }
5503 else
5504 {
Daniel Malead01b2952012-11-29 21:49:15 +00005505 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005506 }
5507}
5508
5509size_t
5510Process::GetThreadStatus (Stream &strm,
5511 bool only_threads_with_stop_reason,
5512 uint32_t start_frame,
5513 uint32_t num_frames,
5514 uint32_t num_frames_with_source)
5515{
5516 size_t num_thread_infos_dumped = 0;
5517
Jim Ingham41f2b942012-09-10 20:50:15 +00005518 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005519 const size_t num_threads = GetThreadList().GetSize();
5520 for (uint32_t i = 0; i < num_threads; i++)
5521 {
5522 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5523 if (thread)
5524 {
5525 if (only_threads_with_stop_reason)
5526 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005527 StopInfoSP stop_info_sp = thread->GetStopInfo();
5528 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005529 continue;
5530 }
5531 thread->GetStatus (strm,
5532 start_frame,
5533 num_frames,
5534 num_frames_with_source);
5535 ++num_thread_infos_dumped;
5536 }
5537 }
5538 return num_thread_infos_dumped;
5539}
5540
Greg Claytona9f40ad2012-02-22 04:37:26 +00005541void
5542Process::AddInvalidMemoryRegion (const LoadRange &region)
5543{
5544 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5545}
5546
5547bool
5548Process::RemoveInvalidMemoryRange (const LoadRange &region)
5549{
5550 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5551}
5552
Jim Ingham372787f2012-04-07 00:00:41 +00005553void
5554Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5555{
5556 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5557}
5558
5559bool
5560Process::RunPreResumeActions ()
5561{
5562 bool result = true;
5563 while (!m_pre_resume_actions.empty())
5564 {
5565 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5566 m_pre_resume_actions.pop_back();
5567 bool this_result = action.callback (action.baton);
5568 if (result == true) result = this_result;
5569 }
5570 return result;
5571}
5572
5573void
5574Process::ClearPreResumeActions ()
5575{
5576 m_pre_resume_actions.clear();
5577}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005578
Greg Claytonfa559e52012-05-18 02:38:05 +00005579void
5580Process::Flush ()
5581{
5582 m_thread_list.Flush();
5583}
Greg Clayton90ba8112012-12-05 00:16:59 +00005584
5585void
5586Process::DidExec ()
5587{
5588 Target &target = GetTarget();
5589 target.CleanupProcess ();
5590 ModuleList unloaded_modules (target.GetImages());
5591 target.ModulesDidUnload (unloaded_modules);
5592 target.GetSectionLoadList().Clear();
5593 m_dynamic_checkers_ap.reset();
5594 m_abi_sp.reset();
5595 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005596 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005597 m_image_tokens.clear();
5598 m_allocated_memory_cache.Clear();
5599 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005600 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005601 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005602 DoDidExec();
5603 CompleteAttach ();
5604}