blob: 390365847d6582543b86fc9969ef9dc981f6358e [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"
Jason Molendaeef51062013-11-05 03:57:19 +000038#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Target/Target.h"
40#include "lldb/Target/TargetList.h"
41#include "lldb/Target/Thread.h"
42#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000043#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Charles Davis510938e2013-08-27 05:04:57 +000045#ifndef LLDB_DISABLE_POSIX
46#include <spawn.h>
47#endif
48
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049using namespace lldb;
50using namespace lldb_private;
51
Greg Clayton67cc0632012-08-22 17:17:09 +000052
53// Comment out line below to disable memory caching, overriding the process setting
54// target.process.disable-memory-cache
55#define ENABLE_MEMORY_CACHING
56
57#ifdef ENABLE_MEMORY_CACHING
58#define DISABLE_MEM_CACHE_DEFAULT false
59#else
60#define DISABLE_MEM_CACHE_DEFAULT true
61#endif
62
63class ProcessOptionValueProperties : public OptionValueProperties
64{
65public:
66 ProcessOptionValueProperties (const ConstString &name) :
67 OptionValueProperties (name)
68 {
69 }
70
71 // This constructor is used when creating ProcessOptionValueProperties when it
72 // is part of a new lldb_private::Process instance. It will copy all current
73 // global property values as needed
74 ProcessOptionValueProperties (ProcessProperties *global_properties) :
75 OptionValueProperties(*global_properties->GetValueProperties())
76 {
77 }
78
79 virtual const Property *
80 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
81 {
82 // When gettings the value for a key from the process options, we will always
83 // try and grab the setting from the current process if there is one. Else we just
84 // use the one from this instance.
85 if (exe_ctx)
86 {
87 Process *process = exe_ctx->GetProcessPtr();
88 if (process)
89 {
90 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
91 if (this != instance_properties)
92 return instance_properties->ProtectedGetPropertyAtIndex (idx);
93 }
94 }
95 return ProtectedGetPropertyAtIndex (idx);
96 }
97};
98
99static PropertyDefinition
100g_properties[] =
101{
102 { "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 +0000103 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
104 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000105 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
106 { "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 +0000107 { "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 +0000108 { "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 +0000109 { "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 +0000110 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111};
112
113enum {
114 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000115 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000116 ePropertyIgnoreBreakpointsInExpressions,
117 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000118 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000119 ePropertyStopOnSharedLibraryEvents,
120 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000121};
122
123ProcessProperties::ProcessProperties (bool is_global) :
124 Properties ()
125{
126 if (is_global)
127 {
128 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
129 m_collection_sp->Initialize(g_properties);
130 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000131 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000132 true,
133 Thread::GetGlobalProperties()->GetValueProperties());
134 }
135 else
136 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
137}
138
139ProcessProperties::~ProcessProperties()
140{
141}
142
143bool
144ProcessProperties::GetDisableMemoryCache() const
145{
146 const uint32_t idx = ePropertyDisableMemCache;
147 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
148}
149
150Args
151ProcessProperties::GetExtraStartupCommands () const
152{
153 Args args;
154 const uint32_t idx = ePropertyExtraStartCommand;
155 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
156 return args;
157}
158
159void
160ProcessProperties::SetExtraStartupCommands (const Args &args)
161{
162 const uint32_t idx = ePropertyExtraStartCommand;
163 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
164}
165
Greg Claytonc9d645d2012-10-18 22:40:37 +0000166FileSpec
167ProcessProperties::GetPythonOSPluginPath () const
168{
169 const uint32_t idx = ePropertyPythonOSPluginPath;
170 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
171}
172
173void
174ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
175{
176 const uint32_t idx = ePropertyPythonOSPluginPath;
177 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
178}
179
Jim Ingham184e9812013-01-15 02:47:48 +0000180
181bool
182ProcessProperties::GetIgnoreBreakpointsInExpressions () const
183{
184 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
185 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
186}
187
188void
189ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
190{
191 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
192 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
193}
194
195bool
196ProcessProperties::GetUnwindOnErrorInExpressions () const
197{
198 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
199 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
200}
201
202void
203ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
204{
205 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
206 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
207}
208
Jim Ingham29950772013-01-26 02:19:28 +0000209bool
210ProcessProperties::GetStopOnSharedLibraryEvents () const
211{
212 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
213 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
214}
215
216void
217ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
218{
219 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
220 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
221}
222
Jim Inghamacff8952013-05-02 00:27:30 +0000223bool
224ProcessProperties::GetDetachKeepsStopped () const
225{
226 const uint32_t idx = ePropertyDetachKeepsStopped;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
228}
229
230void
231ProcessProperties::SetDetachKeepsStopped (bool stop)
232{
233 const uint32_t idx = ePropertyDetachKeepsStopped;
234 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
235}
236
Greg Clayton32e0a752011-03-30 18:16:51 +0000237void
Greg Clayton8b82f082011-04-12 05:54:46 +0000238ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000239{
240 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000241 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000242 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000243
244 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000245 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000246
247 if (m_executable)
248 {
249 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
250 s.PutCString (" file = ");
251 m_executable.Dump(&s);
252 s.EOL();
253 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000254 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000255 if (argc > 0)
256 {
257 for (uint32_t i=0; i<argc; i++)
258 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000259 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000260 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000261 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000262 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000263 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000264 }
265 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000266
267 const uint32_t envc = m_environment.GetArgumentCount();
268 if (envc > 0)
269 {
270 for (uint32_t i=0; i<envc; i++)
271 {
272 const char *env = m_environment.GetArgumentAtIndex(i);
273 if (i < 10)
274 s.Printf (" env[%u] = %s\n", i, env);
275 else
276 s.Printf ("env[%u] = %s\n", i, env);
277 }
278 }
279
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000280 if (m_arch.IsValid())
281 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
282
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000284 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000285 cstr = platform->GetUserName (m_uid);
286 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000287 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000289 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 cstr = platform->GetGroupName (m_gid);
291 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000292 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000294 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000295 cstr = platform->GetUserName (m_euid);
296 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000297 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000299 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 cstr = platform->GetGroupName (m_egid);
301 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000302 }
303}
304
305void
Greg Clayton8b82f082011-04-12 05:54:46 +0000306ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000307{
Greg Clayton8b82f082011-04-12 05:54:46 +0000308 const char *label;
309 if (show_args || verbose)
310 label = "ARGUMENTS";
311 else
312 label = "NAME";
313
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000314 if (verbose)
315 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000316 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000317 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
318 }
319 else
320 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000322 s.PutCString ("====== ====== ========== ======= ============================\n");
323 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000324}
325
326void
Greg Clayton8b82f082011-04-12 05:54:46 +0000327ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000328{
329 if (m_pid != LLDB_INVALID_PROCESS_ID)
330 {
331 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000332 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000333
Greg Clayton32e0a752011-03-30 18:16:51 +0000334
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000335 if (verbose)
336 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000338 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
339 s.Printf ("%-10s ", cstr);
340 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000341 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000342
Greg Clayton8b82f082011-04-12 05:54:46 +0000343 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000344 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
345 s.Printf ("%-10s ", cstr);
346 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000348
Greg Clayton8b82f082011-04-12 05:54:46 +0000349 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000350 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
351 s.Printf ("%-10s ", cstr);
352 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000353 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000354
Greg Clayton8b82f082011-04-12 05:54:46 +0000355 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000356 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
357 s.Printf ("%-10s ", cstr);
358 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000359 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000360 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
361 }
362 else
363 {
Jason Molendafd54b362011-09-20 21:44:10 +0000364 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000365 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000366 (int)m_arch.GetTriple().getArchName().size(),
367 m_arch.GetTriple().getArchName().data());
368 }
369
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000371 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 if (argc > 0)
374 {
375 for (uint32_t i=0; i<argc; i++)
376 {
377 if (i > 0)
378 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000379 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000380 }
381 }
382 }
383 else
384 {
385 s.PutCString (GetName());
386 }
387
388 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000389 }
390}
391
Greg Clayton8b82f082011-04-12 05:54:46 +0000392
393void
Greg Clayton45392552012-10-17 22:57:12 +0000394ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000395{
396 m_arguments.SetArguments (argv);
397
398 // Is the first argument the executable?
399 if (first_arg_is_executable)
400 {
401 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
402 if (first_arg)
403 {
404 // Yes the first argument is an executable, set it as the executable
405 // in the launch options. Don't resolve the file path as the path
406 // could be a remote platform path
407 const bool resolve = false;
408 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000409 }
410 }
411}
412void
Greg Clayton45392552012-10-17 22:57:12 +0000413ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000414{
415 // Copy all arguments
416 m_arguments = args;
417
418 // Is the first argument the executable?
419 if (first_arg_is_executable)
420 {
Greg Clayton982c9762011-11-03 21:22:33 +0000421 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000422 if (first_arg)
423 {
424 // Yes the first argument is an executable, set it as the executable
425 // in the launch options. Don't resolve the file path as the path
426 // could be a remote platform path
427 const bool resolve = false;
428 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 }
430 }
431}
432
Greg Clayton1d885962011-11-08 02:43:13 +0000433void
Greg Claytonee95ed52011-11-17 22:14:31 +0000434ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000435{
436 // If notthing was specified, then check the process for any default
437 // settings that were set with "settings set"
438 if (m_file_actions.empty())
439 {
Greg Clayton1d885962011-11-08 02:43:13 +0000440 if (m_flags.Test(eLaunchFlagDisableSTDIO))
441 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000442 AppendSuppressFileAction (STDIN_FILENO , true, false);
443 AppendSuppressFileAction (STDOUT_FILENO, false, true);
444 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000445 }
446 else
447 {
448 // Check for any values that might have gotten set with any of:
449 // (lldb) settings set target.input-path
450 // (lldb) settings set target.output-path
451 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000452 FileSpec in_path;
453 FileSpec out_path;
454 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000455 if (target)
456 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000457 in_path = target->GetStandardInputPath();
458 out_path = target->GetStandardOutputPath();
459 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000460 }
461
Greg Clayton67cc0632012-08-22 17:17:09 +0000462 if (in_path || out_path || err_path)
463 {
464 char path[PATH_MAX];
465 if (in_path && in_path.GetPath(path, sizeof(path)))
466 AppendOpenFileAction(STDIN_FILENO, path, true, false);
467
468 if (out_path && out_path.GetPath(path, sizeof(path)))
469 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
470
471 if (err_path && err_path.GetPath(path, sizeof(path)))
472 AppendOpenFileAction(STDERR_FILENO, path, false, true);
473 }
474 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000475 {
476 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000477 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000478 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
479 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
480 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
481 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000482 }
483 }
Greg Clayton1d885962011-11-08 02:43:13 +0000484 }
485 }
486}
487
Greg Clayton144f3a92011-11-15 03:53:30 +0000488
489bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000490ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
491 bool localhost,
492 bool will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000493 bool first_arg_is_full_shell_command,
494 int32_t num_resumes)
Greg Clayton144f3a92011-11-15 03:53:30 +0000495{
496 error.Clear();
497
498 if (GetFlags().Test (eLaunchFlagLaunchInShell))
499 {
500 const char *shell_executable = GetShell();
501 if (shell_executable)
502 {
503 char shell_resolved_path[PATH_MAX];
504
505 if (localhost)
506 {
507 FileSpec shell_filespec (shell_executable, true);
508
509 if (!shell_filespec.Exists())
510 {
511 // Resolve the path in case we just got "bash", "sh" or "tcsh"
512 if (!shell_filespec.ResolveExecutableLocation ())
513 {
514 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
515 return false;
516 }
517 }
518 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
519 shell_executable = shell_resolved_path;
520 }
521
Greg Clayton45392552012-10-17 22:57:12 +0000522 const char **argv = GetArguments().GetConstArgumentVector ();
523 if (argv == NULL || argv[0] == NULL)
524 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000525 Args shell_arguments;
526 std::string safe_arg;
527 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000528 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000529 StreamString shell_command;
530 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000531 {
Greg Clayton45392552012-10-17 22:57:12 +0000532 // Add a modified PATH environment variable in case argv[0]
533 // is a relative path
534 const char *argv0 = argv[0];
535 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
536 {
537 // We have a relative path to our executable which may not work if
538 // we just try to run "a.out" (without it being converted to "./a.out")
539 const char *working_dir = GetWorkingDirectory();
Greg Clayton8938f8d2013-02-14 03:54:39 +0000540 // Be sure to put quotes around PATH's value in case any paths have spaces...
541 std::string new_path("PATH=\"");
Greg Clayton45392552012-10-17 22:57:12 +0000542 const size_t empty_path_len = new_path.size();
543
544 if (working_dir && working_dir[0])
545 {
546 new_path += working_dir;
547 }
548 else
549 {
550 char current_working_dir[PATH_MAX];
551 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
552 if (cwd && cwd[0])
553 new_path += cwd;
554 }
555 const char *curr_path = getenv("PATH");
556 if (curr_path)
557 {
558 if (new_path.size() > empty_path_len)
559 new_path += ':';
560 new_path += curr_path;
561 }
Greg Clayton8938f8d2013-02-14 03:54:39 +0000562 new_path += "\" ";
Greg Clayton45392552012-10-17 22:57:12 +0000563 shell_command.PutCString(new_path.c_str());
564 }
565
Greg Claytond1cf11a2012-04-14 01:42:46 +0000566 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000567
Greg Clayton45392552012-10-17 22:57:12 +0000568 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000569 if (GetArchitecture().IsValid())
570 {
571 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000572 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000573 // 1 - stop in shell
574 // 2 - stop in /usr/bin/arch
575 // 3 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000576 SetResumeCount(num_resumes + 1);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000577 }
578 else
579 {
Greg Clayton45392552012-10-17 22:57:12 +0000580 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000581 // 1 - stop in shell
582 // 2 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000583 SetResumeCount(num_resumes);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000584 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000585 }
Greg Clayton45392552012-10-17 22:57:12 +0000586
587 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000588 {
Greg Clayton45392552012-10-17 22:57:12 +0000589 // There should only be one argument that is the shell command itself to be used as is
590 if (argv[0] && !argv[1])
591 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000592 else
Greg Clayton45392552012-10-17 22:57:12 +0000593 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000594 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000595 else
596 {
Greg Clayton45392552012-10-17 22:57:12 +0000597 for (size_t i=0; argv[i] != NULL; ++i)
598 {
599 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
600 shell_command.Printf(" %s", arg);
601 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000602 }
Greg Clayton45392552012-10-17 22:57:12 +0000603 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000604 m_executable.SetFile(shell_executable, false);
605 m_arguments = shell_arguments;
606 return true;
607 }
608 else
609 {
610 error.SetErrorString ("invalid shell path");
611 }
612 }
613 else
614 {
615 error.SetErrorString ("not launching in shell");
616 }
617 return false;
618}
619
620
Greg Clayton32e0a752011-03-30 18:16:51 +0000621bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000622ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
623{
624 if ((read || write) && fd >= 0 && path && path[0])
625 {
626 m_action = eFileActionOpen;
627 m_fd = fd;
628 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000629 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000630 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000631 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000632 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000633 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000634 m_path.assign (path);
635 return true;
636 }
637 else
638 {
639 Clear();
640 }
641 return false;
642}
643
644bool
645ProcessLaunchInfo::FileAction::Close (int fd)
646{
647 Clear();
648 if (fd >= 0)
649 {
650 m_action = eFileActionClose;
651 m_fd = fd;
652 }
653 return m_fd >= 0;
654}
655
656
657bool
658ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
659{
660 Clear();
661 if (fd >= 0 && dup_fd >= 0)
662 {
663 m_action = eFileActionDuplicate;
664 m_fd = fd;
665 m_arg = dup_fd;
666 }
667 return m_fd >= 0;
668}
669
670
671
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000672#ifndef LLDB_DISABLE_POSIX
Greg Clayton8b82f082011-04-12 05:54:46 +0000673bool
Charles Davis510938e2013-08-27 05:04:57 +0000674ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions,
Greg Clayton8b82f082011-04-12 05:54:46 +0000675 const FileAction *info,
676 Log *log,
677 Error& error)
678{
679 if (info == NULL)
680 return false;
681
Charles Davis510938e2013-08-27 05:04:57 +0000682 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
683
Greg Clayton8b82f082011-04-12 05:54:46 +0000684 switch (info->m_action)
685 {
686 case eFileActionNone:
687 error.Clear();
688 break;
689
690 case eFileActionClose:
691 if (info->m_fd == -1)
692 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
693 else
694 {
695 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
696 eErrorTypePOSIX);
697 if (log && (error.Fail() || log))
698 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
699 file_actions, info->m_fd);
700 }
701 break;
702
703 case eFileActionDuplicate:
704 if (info->m_fd == -1)
705 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
706 else if (info->m_arg == -1)
707 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
708 else
709 {
710 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
711 eErrorTypePOSIX);
712 if (log && (error.Fail() || log))
713 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
714 file_actions, info->m_fd, info->m_arg);
715 }
716 break;
717
718 case eFileActionOpen:
719 if (info->m_fd == -1)
720 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
721 else
722 {
723 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000724
Greg Clayton8b82f082011-04-12 05:54:46 +0000725 mode_t mode = 0;
726
Greg Clayton144f3a92011-11-15 03:53:30 +0000727 if (oflag & O_CREAT)
728 mode = 0640;
729
Greg Clayton8b82f082011-04-12 05:54:46 +0000730 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
731 info->m_fd,
732 info->m_path.c_str(),
733 oflag,
734 mode),
735 eErrorTypePOSIX);
736 if (error.Fail() || log)
737 error.PutToLog(log,
738 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
739 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
740 }
741 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000742 }
743 return error.Success();
744}
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000745#endif
Greg Clayton8b82f082011-04-12 05:54:46 +0000746
747Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000748ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000749{
750 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000751 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000752
753 switch (short_option)
754 {
755 case 's': // Stop at program entry point
756 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
757 break;
758
Greg Clayton8b82f082011-04-12 05:54:46 +0000759 case 'i': // STDIN for read only
760 {
761 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000762 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000763 launch_info.AppendFileAction (action);
764 }
765 break;
766
767 case 'o': // Open STDOUT for write only
768 {
769 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000770 if (action.Open (STDOUT_FILENO, option_arg, false, true))
771 launch_info.AppendFileAction (action);
772 }
773 break;
774
775 case 'e': // STDERR for write only
776 {
777 ProcessLaunchInfo::FileAction action;
778 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000779 launch_info.AppendFileAction (action);
780 }
781 break;
782
Greg Clayton9845a8d2012-03-06 04:01:04 +0000783
Greg Clayton8b82f082011-04-12 05:54:46 +0000784 case 'p': // Process plug-in name
785 launch_info.SetProcessPluginName (option_arg);
786 break;
787
788 case 'n': // Disable STDIO
789 {
790 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000791 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000792 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000793 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000794 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000795 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000796 launch_info.AppendFileAction (action);
797 }
798 break;
799
800 case 'w':
801 launch_info.SetWorkingDirectory (option_arg);
802 break;
803
804 case 't': // Open process in new terminal window
805 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
806 break;
807
808 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000809 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
810 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000811 break;
812
813 case 'A':
814 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
815 break;
816
Greg Clayton982c9762011-11-03 21:22:33 +0000817 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000818 if (option_arg && option_arg[0])
819 launch_info.SetShell (option_arg);
820 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000821 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000822 break;
823
Greg Clayton8b82f082011-04-12 05:54:46 +0000824 case 'v':
825 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
826 break;
827
828 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000829 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000830 break;
831
832 }
833 return error;
834}
835
836OptionDefinition
837ProcessLaunchCommandOptions::g_option_table[] =
838{
Virgile Belloe2607b52013-09-05 16:42:23 +0000839{ 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."},
840{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
841{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
842{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
843{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
844{ 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."},
845{ 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 +0000846
Virgile Belloe2607b52013-09-05 16:42:23 +0000847{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
848{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
849{ 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 +0000850
Virgile Belloe2607b52013-09-05 16:42:23 +0000851{ 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 +0000852
Virgile Belloe2607b52013-09-05 16:42:23 +0000853{ 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 +0000854
855{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
856};
857
858
859
860bool
861ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000862{
863 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
864 return true;
865 const char *match_name = m_match_info.GetName();
866 if (!match_name)
867 return true;
868
869 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
870}
871
872bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000873ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000874{
875 if (!NameMatches (proc_info.GetName()))
876 return false;
877
878 if (m_match_info.ProcessIDIsValid() &&
879 m_match_info.GetProcessID() != proc_info.GetProcessID())
880 return false;
881
882 if (m_match_info.ParentProcessIDIsValid() &&
883 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
884 return false;
885
Greg Clayton8b82f082011-04-12 05:54:46 +0000886 if (m_match_info.UserIDIsValid () &&
887 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000888 return false;
889
Greg Clayton8b82f082011-04-12 05:54:46 +0000890 if (m_match_info.GroupIDIsValid () &&
891 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000892 return false;
893
894 if (m_match_info.EffectiveUserIDIsValid () &&
895 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
896 return false;
897
898 if (m_match_info.EffectiveGroupIDIsValid () &&
899 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
900 return false;
901
902 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000903 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000904 return false;
905 return true;
906}
907
908bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000909ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000910{
911 if (m_name_match_type != eNameMatchIgnore)
912 return false;
913
914 if (m_match_info.ProcessIDIsValid())
915 return false;
916
917 if (m_match_info.ParentProcessIDIsValid())
918 return false;
919
Greg Clayton8b82f082011-04-12 05:54:46 +0000920 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000921 return false;
922
Greg Clayton8b82f082011-04-12 05:54:46 +0000923 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000924 return false;
925
926 if (m_match_info.EffectiveUserIDIsValid ())
927 return false;
928
929 if (m_match_info.EffectiveGroupIDIsValid ())
930 return false;
931
932 if (m_match_info.GetArchitecture().IsValid())
933 return false;
934
935 if (m_match_all_users)
936 return false;
937
938 return true;
939
940}
941
942void
Greg Clayton8b82f082011-04-12 05:54:46 +0000943ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000944{
945 m_match_info.Clear();
946 m_name_match_type = eNameMatchIgnore;
947 m_match_all_users = false;
948}
Greg Clayton58be07b2011-01-07 06:08:19 +0000949
Greg Claytonc3776bf2012-02-09 06:16:32 +0000950ProcessSP
951Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952{
Greg Clayton949e8222013-01-16 17:29:04 +0000953 static uint32_t g_process_unique_id = 0;
954
Greg Claytonc3776bf2012-02-09 06:16:32 +0000955 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956 ProcessCreateInstance create_callback = NULL;
957 if (plugin_name)
958 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000959 ConstString const_plugin_name(plugin_name);
960 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 if (create_callback)
962 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000963 process_sp = create_callback(target, listener, crash_file_path);
964 if (process_sp)
965 {
Greg Clayton949e8222013-01-16 17:29:04 +0000966 if (process_sp->CanDebug(target, true))
967 {
968 process_sp->m_process_unique_id = ++g_process_unique_id;
969 }
970 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000971 process_sp.reset();
972 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973 }
974 }
975 else
976 {
Greg Claytonc982c762010-07-09 20:39:50 +0000977 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000979 process_sp = create_callback(target, listener, crash_file_path);
980 if (process_sp)
981 {
Greg Clayton949e8222013-01-16 17:29:04 +0000982 if (process_sp->CanDebug(target, false))
983 {
984 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000985 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000986 }
987 else
988 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000989 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990 }
991 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000992 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993}
994
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000995ConstString &
996Process::GetStaticBroadcasterClass ()
997{
998 static ConstString class_name ("lldb.process");
999 return class_name;
1000}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
1002//----------------------------------------------------------------------
1003// Process constructor
1004//----------------------------------------------------------------------
1005Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +00001006 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001008 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010 m_public_state (eStateUnloaded),
1011 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001012 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1013 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014 m_private_state_listener ("lldb.process.internal_state_listener"),
1015 m_private_state_control_wait(),
1016 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001017 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001018 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001020 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 m_exit_status (-1),
1022 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001023 m_thread_mutex (Mutex::eMutexTypeRecursive),
1024 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +00001026 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +00001027 m_extended_thread_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001028 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001029 m_image_tokens (),
1030 m_listener (listener),
1031 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001032 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001033 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001034 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001035 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001036 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001037 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001038 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001039 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001040 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1041 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001042 m_memory_cache (*this),
1043 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001044 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001045 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001046 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001047 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001048 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001049 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001050 m_clear_thread_plans_on_stop (false),
Jim Ingham0161b492013-02-09 01:29:05 +00001051 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001052 m_destroy_in_process (false),
1053 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001055 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001056
Greg Clayton5160ce52013-03-27 23:08:40 +00001057 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058 if (log)
1059 log->Printf ("%p Process::Process()", this);
1060
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001061 SetEventName (eBroadcastBitStateChanged, "state-changed");
1062 SetEventName (eBroadcastBitInterrupt, "interrupt");
1063 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1064 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001065 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001066
Greg Clayton35a4cc52012-10-29 20:52:08 +00001067 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1068 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1069 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1070
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 listener.StartListeningForEvents (this,
1072 eBroadcastBitStateChanged |
1073 eBroadcastBitInterrupt |
1074 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001075 eBroadcastBitSTDERR |
1076 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077
1078 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001079 eBroadcastBitStateChanged |
1080 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081
1082 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1083 eBroadcastInternalStateControlStop |
1084 eBroadcastInternalStateControlPause |
1085 eBroadcastInternalStateControlResume);
1086}
1087
1088//----------------------------------------------------------------------
1089// Destructor
1090//----------------------------------------------------------------------
1091Process::~Process()
1092{
Greg Clayton5160ce52013-03-27 23:08:40 +00001093 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 if (log)
1095 log->Printf ("%p Process::~Process()", this);
1096 StopPrivateStateThread();
1097}
1098
Greg Clayton67cc0632012-08-22 17:17:09 +00001099const ProcessPropertiesSP &
1100Process::GetGlobalProperties()
1101{
1102 static ProcessPropertiesSP g_settings_sp;
1103 if (!g_settings_sp)
1104 g_settings_sp.reset (new ProcessProperties (true));
1105 return g_settings_sp;
1106}
1107
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001108void
1109Process::Finalize()
1110{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001111 switch (GetPrivateState())
1112 {
1113 case eStateConnected:
1114 case eStateAttaching:
1115 case eStateLaunching:
1116 case eStateStopped:
1117 case eStateRunning:
1118 case eStateStepping:
1119 case eStateCrashed:
1120 case eStateSuspended:
1121 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001122 {
1123 // FIXME: This will have to be a process setting:
1124 bool keep_stopped = false;
1125 Detach(keep_stopped);
1126 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001127 else
1128 Destroy();
1129 break;
1130
1131 case eStateInvalid:
1132 case eStateUnloaded:
1133 case eStateDetached:
1134 case eStateExited:
1135 break;
1136 }
1137
Greg Clayton1ed54f52011-10-01 00:45:15 +00001138 // Clear our broadcaster before we proceed with destroying
1139 Broadcaster::Clear();
1140
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 // Do any cleanup needed prior to being destructed... Subclasses
1142 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001143
1144 // We need to destroy the loader before the derived Process class gets destroyed
1145 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001146 m_dynamic_checkers_ap.reset();
1147 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001148 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00001149 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001150 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001151 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001152 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +00001153 m_extended_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001154 std::vector<Notifications> empty_notifications;
1155 m_notifications.swap(empty_notifications);
1156 m_image_tokens.clear();
1157 m_memory_cache.Clear();
1158 m_allocated_memory_cache.Clear();
1159 m_language_runtimes.clear();
1160 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001161//#ifdef LLDB_CONFIGURATION_DEBUG
1162// StreamFile s(stdout, false);
1163// EventSP event_sp;
1164// while (m_private_state_listener.GetNextEvent(event_sp))
1165// {
1166// event_sp->Dump (&s);
1167// s.EOL();
1168// }
1169//#endif
1170 // We have to be very careful here as the m_private_state_listener might
1171 // contain events that have ProcessSP values in them which can keep this
1172 // process around forever. These events need to be cleared out.
1173 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001174 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1175 m_public_run_lock.SetStopped();
1176 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1177 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001178 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179}
1180
1181void
1182Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1183{
1184 m_notifications.push_back(callbacks);
1185 if (callbacks.initialize != NULL)
1186 callbacks.initialize (callbacks.baton, this);
1187}
1188
1189bool
1190Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1191{
1192 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1193 for (pos = m_notifications.begin(); pos != end; ++pos)
1194 {
1195 if (pos->baton == callbacks.baton &&
1196 pos->initialize == callbacks.initialize &&
1197 pos->process_state_changed == callbacks.process_state_changed)
1198 {
1199 m_notifications.erase(pos);
1200 return true;
1201 }
1202 }
1203 return false;
1204}
1205
1206void
1207Process::SynchronouslyNotifyStateChanged (StateType state)
1208{
1209 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1210 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1211 {
1212 if (notification_pos->process_state_changed)
1213 notification_pos->process_state_changed (notification_pos->baton, this, state);
1214 }
1215}
1216
1217// FIXME: We need to do some work on events before the general Listener sees them.
1218// For instance if we are continuing from a breakpoint, we need to ensure that we do
1219// the little "insert real insn, step & stop" trick. But we can't do that when the
1220// event is delivered by the broadcaster - since that is done on the thread that is
1221// waiting for new events, so if we needed more than one event for our handling, we would
1222// stall. So instead we do it when we fetch the event off of the queue.
1223//
1224
1225StateType
1226Process::GetNextEvent (EventSP &event_sp)
1227{
1228 StateType state = eStateInvalid;
1229
1230 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1231 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1232
1233 return state;
1234}
1235
1236
1237StateType
Daniel Malea9e9919f2013-10-09 16:56:28 +00001238Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001239{
Jim Ingham4b536182011-08-09 02:12:22 +00001240 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1241 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1242 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001243 if (event_sp_ptr)
1244 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001245 StateType state = GetState();
1246 // If we are exited or detached, we won't ever get back to any
1247 // other valid state...
1248 if (state == eStateDetached || state == eStateExited)
1249 return state;
1250
Daniel Malea9e9919f2013-10-09 16:56:28 +00001251 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1252 if (log)
1253 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1254
1255 if (!wait_always &&
1256 StateIsStoppedState(state, true) &&
1257 StateIsStoppedState(GetPrivateState(), true)) {
1258 if (log)
1259 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1260 __FUNCTION__);
1261 return state;
1262 }
1263
Jim Ingham4b536182011-08-09 02:12:22 +00001264 while (state != eStateInvalid)
1265 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001266 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001267 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001268 if (event_sp_ptr && event_sp)
1269 *event_sp_ptr = event_sp;
1270
Jim Ingham4b536182011-08-09 02:12:22 +00001271 switch (state)
1272 {
1273 case eStateCrashed:
1274 case eStateDetached:
1275 case eStateExited:
1276 case eStateUnloaded:
1277 return state;
1278 case eStateStopped:
1279 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1280 continue;
1281 else
1282 return state;
1283 default:
1284 continue;
1285 }
1286 }
1287 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288}
1289
1290
1291StateType
1292Process::WaitForState
1293(
1294 const TimeValue *timeout,
1295 const StateType *match_states, const uint32_t num_match_states
1296)
1297{
1298 EventSP event_sp;
1299 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001300 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301 while (state != eStateInvalid)
1302 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001303 // If we are exited or detached, we won't ever get back to any
1304 // other valid state...
1305 if (state == eStateDetached || state == eStateExited)
1306 return state;
1307
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308 state = WaitForStateChangedEvents (timeout, event_sp);
1309
1310 for (i=0; i<num_match_states; ++i)
1311 {
1312 if (match_states[i] == state)
1313 return state;
1314 }
1315 }
1316 return state;
1317}
1318
Jim Ingham30f9b212010-10-11 23:53:14 +00001319bool
1320Process::HijackProcessEvents (Listener *listener)
1321{
1322 if (listener != NULL)
1323 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001324 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001325 }
1326 else
1327 return false;
1328}
1329
1330void
1331Process::RestoreProcessEvents ()
1332{
1333 RestoreBroadcaster();
1334}
1335
Jim Ingham0f16e732011-02-08 05:20:59 +00001336bool
1337Process::HijackPrivateProcessEvents (Listener *listener)
1338{
1339 if (listener != NULL)
1340 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001341 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001342 }
1343 else
1344 return false;
1345}
1346
1347void
1348Process::RestorePrivateProcessEvents ()
1349{
1350 m_private_state_broadcaster.RestoreBroadcaster();
1351}
1352
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353StateType
1354Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1355{
Greg Clayton5160ce52013-03-27 23:08:40 +00001356 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357
1358 if (log)
1359 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1360
1361 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001362 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1363 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001364 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001365 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001366 {
1367 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1368 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1369 else if (log)
1370 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1371 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372
1373 if (log)
1374 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1375 __FUNCTION__,
1376 timeout,
1377 StateAsCString(state));
1378 return state;
1379}
1380
1381Event *
1382Process::PeekAtStateChangedEvents ()
1383{
Greg Clayton5160ce52013-03-27 23:08:40 +00001384 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001385
1386 if (log)
1387 log->Printf ("Process::%s...", __FUNCTION__);
1388
1389 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001390 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1391 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392 if (log)
1393 {
1394 if (event_ptr)
1395 {
1396 log->Printf ("Process::%s (event_ptr) => %s",
1397 __FUNCTION__,
1398 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1399 }
1400 else
1401 {
1402 log->Printf ("Process::%s no events found",
1403 __FUNCTION__);
1404 }
1405 }
1406 return event_ptr;
1407}
1408
1409StateType
1410Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1411{
Greg Clayton5160ce52013-03-27 23:08:40 +00001412 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413
1414 if (log)
1415 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1416
1417 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001418 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1419 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001420 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001421 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001422 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1423 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424
1425 // This is a bit of a hack, but when we wait here we could very well return
1426 // to the command-line, and that could disable the log, which would render the
1427 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001428 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001429 {
1430 if (state == eStateInvalid)
1431 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1432 else
1433 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1434 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001435 return state;
1436}
1437
1438bool
1439Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1440{
Greg Clayton5160ce52013-03-27 23:08:40 +00001441 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442
1443 if (log)
1444 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1445
1446 if (control_only)
1447 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1448 else
1449 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1450}
1451
1452bool
1453Process::IsRunning () const
1454{
1455 return StateIsRunningState (m_public_state.GetValue());
1456}
1457
1458int
1459Process::GetExitStatus ()
1460{
1461 if (m_public_state.GetValue() == eStateExited)
1462 return m_exit_status;
1463 return -1;
1464}
1465
Greg Clayton85851dd2010-12-04 00:10:17 +00001466
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467const char *
1468Process::GetExitDescription ()
1469{
1470 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1471 return m_exit_string.c_str();
1472 return NULL;
1473}
1474
Greg Clayton6779606a2011-01-22 23:43:18 +00001475bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476Process::SetExitStatus (int status, const char *cstr)
1477{
Greg Clayton5160ce52013-03-27 23:08:40 +00001478 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001479 if (log)
1480 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1481 status, status,
1482 cstr ? "\"" : "",
1483 cstr ? cstr : "NULL",
1484 cstr ? "\"" : "");
1485
Greg Clayton6779606a2011-01-22 23:43:18 +00001486 // We were already in the exited state
1487 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001488 {
Greg Clayton385d6032011-01-26 23:47:29 +00001489 if (log)
1490 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001491 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001492 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001493
1494 m_exit_status = status;
1495 if (cstr)
1496 m_exit_string = cstr;
1497 else
1498 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499
Greg Clayton6779606a2011-01-22 23:43:18 +00001500 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001501
Greg Clayton6779606a2011-01-22 23:43:18 +00001502 SetPrivateState (eStateExited);
1503 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504}
1505
1506// This static callback can be used to watch for local child processes on
1507// the current host. The the child process exits, the process will be
1508// found in the global target list (we want to be completely sure that the
1509// lldb_private::Process doesn't go away before we can deliver the signal.
1510bool
Greg Claytone4e45922011-11-16 05:37:56 +00001511Process::SetProcessExitStatus (void *callback_baton,
1512 lldb::pid_t pid,
1513 bool exited,
1514 int signo, // Zero for no signal
1515 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001516)
1517{
Greg Clayton5160ce52013-03-27 23:08:40 +00001518 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001519 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001520 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001521 callback_baton,
1522 pid,
1523 exited,
1524 signo,
1525 exit_status);
1526
1527 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001528 {
Greg Clayton66111032010-06-23 01:19:29 +00001529 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 if (target_sp)
1531 {
1532 ProcessSP process_sp (target_sp->GetProcessSP());
1533 if (process_sp)
1534 {
1535 const char *signal_cstr = NULL;
1536 if (signo)
1537 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1538
1539 process_sp->SetExitStatus (exit_status, signal_cstr);
1540 }
1541 }
1542 return true;
1543 }
1544 return false;
1545}
1546
1547
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001548void
1549Process::UpdateThreadListIfNeeded ()
1550{
1551 const uint32_t stop_id = GetStopID();
1552 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1553 {
Greg Clayton2637f822011-11-17 01:23:07 +00001554 const StateType state = GetPrivateState();
1555 if (StateIsStoppedState (state, true))
1556 {
1557 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001558 // m_thread_list does have its own mutex, but we need to
1559 // hold onto the mutex between the call to UpdateThreadList(...)
1560 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001561 ThreadList &old_thread_list = m_thread_list;
1562 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001563 ThreadList new_thread_list(this);
1564 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001565 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001566 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001567 {
Jim Ingham09437922013-03-01 20:04:25 +00001568 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1569 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1570 // shutting us down, causing a deadlock.
1571 if (!m_destroy_in_process)
1572 {
1573 OperatingSystem *os = GetOperatingSystem ();
1574 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001575 {
1576 // Clear any old backing threads where memory threads might have been
1577 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001578 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001579 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001580 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001581
1582 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001583 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1584 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1585 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 +00001586 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001587 else
1588 {
1589 // No OS plug-in, the new thread list is the same as the real thread list
1590 new_thread_list = real_thread_list;
1591 }
Jim Ingham09437922013-03-01 20:04:25 +00001592 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001593
1594 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001595 m_thread_list.Update (new_thread_list);
1596 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001597
Jason Molenda4ff13262013-11-20 00:31:38 +00001598 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1599 {
1600 // Clear any extended threads that we may have accumulated previously
1601 m_extended_thread_list.Clear();
1602 m_extended_thread_stop_id = GetLastNaturalStopID ();
1603 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001604 }
Greg Clayton2637f822011-11-17 01:23:07 +00001605 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001606 }
1607}
1608
Greg Claytona4d87472013-01-18 23:41:08 +00001609ThreadSP
1610Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1611{
1612 OperatingSystem *os = GetOperatingSystem ();
1613 if (os)
1614 return os->CreateThread(tid, context);
1615 return ThreadSP();
1616}
1617
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001618uint32_t
1619Process::GetNextThreadIndexID (uint64_t thread_id)
1620{
1621 return AssignIndexIDToThread(thread_id);
1622}
1623
1624bool
1625Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1626{
1627 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1628 if (iterator == m_thread_id_to_index_id_map.end())
1629 {
1630 return false;
1631 }
1632 else
1633 {
1634 return true;
1635 }
1636}
1637
1638uint32_t
1639Process::AssignIndexIDToThread(uint64_t thread_id)
1640{
1641 uint32_t result = 0;
1642 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1643 if (iterator == m_thread_id_to_index_id_map.end())
1644 {
1645 result = ++m_thread_index_id;
1646 m_thread_id_to_index_id_map[thread_id] = result;
1647 }
1648 else
1649 {
1650 result = iterator->second;
1651 }
1652
1653 return result;
1654}
1655
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001656StateType
1657Process::GetState()
1658{
1659 // If any other threads access this we will need a mutex for it
1660 return m_public_state.GetValue ();
1661}
1662
1663void
Jim Ingham221d51c2013-05-08 00:35:16 +00001664Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665{
Greg Clayton5160ce52013-03-27 23:08:40 +00001666 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001668 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001669 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001670 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001671
1672 // On the transition from Run to Stopped, we unlock the writer end of the
1673 // run lock. The lock gets locked in Resume, which is the public API
1674 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001675 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1676 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001677 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001678 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001679 if (log)
1680 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001681 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001682 }
1683 else
1684 {
1685 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1686 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001687 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001688 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001689 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001690 {
1691 if (log)
1692 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001693 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001694 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001695 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001696 }
1697 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001698}
1699
Jim Ingham3b8285d2012-04-19 01:40:33 +00001700Error
1701Process::Resume ()
1702{
Greg Clayton5160ce52013-03-27 23:08:40 +00001703 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001704 if (log)
1705 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001706 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001707 {
1708 Error error("Resume request failed - process still running.");
1709 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001710 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001711 return error;
1712 }
1713 return PrivateResume();
1714}
1715
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001716StateType
1717Process::GetPrivateState ()
1718{
1719 return m_private_state.GetValue();
1720}
1721
1722void
1723Process::SetPrivateState (StateType new_state)
1724{
Greg Clayton5160ce52013-03-27 23:08:40 +00001725 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001726 bool state_changed = false;
1727
1728 if (log)
1729 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1730
Andrew Kaylor29d65742013-05-10 17:19:04 +00001731 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 Mutex::Locker locker(m_private_state.GetMutex());
1733
1734 const StateType old_state = m_private_state.GetValueNoLock ();
1735 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001736
Greg Claytonaa49c832013-05-03 22:25:56 +00001737 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1738 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1739 if (old_state_is_stopped != new_state_is_stopped)
1740 {
1741 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001742 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001743 else
Ed Maste64fad602013-07-29 20:58:06 +00001744 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001745 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001746
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747 if (state_changed)
1748 {
1749 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001750 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001752 // Note, this currently assumes that all threads in the list
1753 // stop when the process stops. In the future we will want to
1754 // support a debugging model where some threads continue to run
1755 // while others are stopped. When that happens we will either need
1756 // a way for the thread list to identify which threads are stopping
1757 // or create a special thread list containing only threads which
1758 // actually stopped.
1759 //
1760 // The process plugin is responsible for managing the actual
1761 // behavior of the threads and should have stopped any threads
1762 // that are going to stop before we get here.
1763 m_thread_list.DidStop();
1764
Jim Ingham4b536182011-08-09 02:12:22 +00001765 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001766 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001767 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001768 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 }
1770 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001771 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1772 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1773 else
1774 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775 }
1776 else
1777 {
1778 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001779 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780 }
1781}
1782
Jim Ingham0faa43f2011-11-08 03:00:11 +00001783void
1784Process::SetRunningUserExpression (bool on)
1785{
1786 m_mod_id.SetRunningUserExpression (on);
1787}
1788
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789addr_t
1790Process::GetImageInfoAddress()
1791{
1792 return LLDB_INVALID_ADDRESS;
1793}
1794
Greg Clayton8f343b02010-11-04 01:54:29 +00001795//----------------------------------------------------------------------
1796// LoadImage
1797//
1798// This function provides a default implementation that works for most
1799// unix variants. Any Process subclasses that need to do shared library
1800// loading differently should override LoadImage and UnloadImage and
1801// do what is needed.
1802//----------------------------------------------------------------------
1803uint32_t
1804Process::LoadImage (const FileSpec &image_spec, Error &error)
1805{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001806 char path[PATH_MAX];
1807 image_spec.GetPath(path, sizeof(path));
1808
Greg Clayton8f343b02010-11-04 01:54:29 +00001809 DynamicLoader *loader = GetDynamicLoader();
1810 if (loader)
1811 {
1812 error = loader->CanLoadImage();
1813 if (error.Fail())
1814 return LLDB_INVALID_IMAGE_TOKEN;
1815 }
1816
1817 if (error.Success())
1818 {
1819 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001820
1821 if (thread_sp)
1822 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001823 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001824
1825 if (frame_sp)
1826 {
1827 ExecutionContext exe_ctx;
1828 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001829 EvaluateExpressionOptions expr_options;
1830 expr_options.SetUnwindOnError(true);
1831 expr_options.SetIgnoreBreakpoints(true);
1832 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001833 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001834 expr.Printf("dlopen (\"%s\", 2)", path);
1835 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001836 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001837 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001838 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001839 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001840 expr.GetData(),
1841 prefix,
1842 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001843 expr_error);
1844 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001845 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001846 error = result_valobj_sp->GetError();
1847 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001848 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001849 Scalar scalar;
1850 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001851 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001852 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1853 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1854 {
1855 uint32_t image_token = m_image_tokens.size();
1856 m_image_tokens.push_back (image_ptr);
1857 return image_token;
1858 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001859 }
1860 }
1861 }
1862 }
1863 }
1864 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001865 if (!error.AsCString())
1866 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001867 return LLDB_INVALID_IMAGE_TOKEN;
1868}
1869
1870//----------------------------------------------------------------------
1871// UnloadImage
1872//
1873// This function provides a default implementation that works for most
1874// unix variants. Any Process subclasses that need to do shared library
1875// loading differently should override LoadImage and UnloadImage and
1876// do what is needed.
1877//----------------------------------------------------------------------
1878Error
1879Process::UnloadImage (uint32_t image_token)
1880{
1881 Error error;
1882 if (image_token < m_image_tokens.size())
1883 {
1884 const addr_t image_addr = m_image_tokens[image_token];
1885 if (image_addr == LLDB_INVALID_ADDRESS)
1886 {
1887 error.SetErrorString("image already unloaded");
1888 }
1889 else
1890 {
1891 DynamicLoader *loader = GetDynamicLoader();
1892 if (loader)
1893 error = loader->CanLoadImage();
1894
1895 if (error.Success())
1896 {
1897 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001898
1899 if (thread_sp)
1900 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001901 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001902
1903 if (frame_sp)
1904 {
1905 ExecutionContext exe_ctx;
1906 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001907 EvaluateExpressionOptions expr_options;
1908 expr_options.SetUnwindOnError(true);
1909 expr_options.SetIgnoreBreakpoints(true);
1910 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001911 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001912 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001913 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001914 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001915 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001916 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001917 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001918 expr.GetData(),
1919 prefix,
1920 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001921 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001922 if (result_valobj_sp->GetError().Success())
1923 {
1924 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001925 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001926 {
1927 if (scalar.UInt(1))
1928 {
1929 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1930 }
1931 else
1932 {
1933 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1934 }
1935 }
1936 }
1937 else
1938 {
1939 error = result_valobj_sp->GetError();
1940 }
1941 }
1942 }
1943 }
1944 }
1945 }
1946 else
1947 {
1948 error.SetErrorString("invalid image token");
1949 }
1950 return error;
1951}
1952
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001953const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001954Process::GetABI()
1955{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001956 if (!m_abi_sp)
1957 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1958 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959}
1960
Jim Ingham22777012010-09-23 02:01:19 +00001961LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001962Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001963{
1964 LanguageRuntimeCollection::iterator pos;
1965 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001966 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001967 {
Jim Inghamab175242012-03-10 00:22:19 +00001968 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001969
Jim Inghamab175242012-03-10 00:22:19 +00001970 m_language_runtimes[language] = runtime_sp;
1971 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001972 }
1973 else
1974 return (*pos).second.get();
1975}
1976
1977CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001978Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001979{
Jim Inghamab175242012-03-10 00:22:19 +00001980 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001981 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1982 return static_cast<CPPLanguageRuntime *> (runtime);
1983 return NULL;
1984}
1985
1986ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001987Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001988{
Jim Inghamab175242012-03-10 00:22:19 +00001989 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001990 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1991 return static_cast<ObjCLanguageRuntime *> (runtime);
1992 return NULL;
1993}
1994
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001995bool
1996Process::IsPossibleDynamicValue (ValueObject& in_value)
1997{
1998 if (in_value.IsDynamic())
1999 return false;
2000 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2001
2002 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2003 {
2004 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2005 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2006 }
2007
2008 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2009 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2010 return true;
2011
2012 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2013 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2014}
2015
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002016BreakpointSiteList &
2017Process::GetBreakpointSiteList()
2018{
2019 return m_breakpoint_site_list;
2020}
2021
2022const BreakpointSiteList &
2023Process::GetBreakpointSiteList() const
2024{
2025 return m_breakpoint_site_list;
2026}
2027
2028
2029void
2030Process::DisableAllBreakpointSites ()
2031{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002032 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2033// bp_site->SetEnabled(true);
2034 DisableBreakpointSite(bp_site);
2035 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036}
2037
2038Error
2039Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2040{
2041 Error error (DisableBreakpointSiteByID (break_id));
2042
2043 if (error.Success())
2044 m_breakpoint_site_list.Remove(break_id);
2045
2046 return error;
2047}
2048
2049Error
2050Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2051{
2052 Error error;
2053 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2054 if (bp_site_sp)
2055 {
2056 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002057 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002058 }
2059 else
2060 {
Daniel Malead01b2952012-11-29 21:49:15 +00002061 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002062 }
2063
2064 return error;
2065}
2066
2067Error
2068Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2069{
2070 Error error;
2071 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2072 if (bp_site_sp)
2073 {
2074 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002075 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002076 }
2077 else
2078 {
Daniel Malead01b2952012-11-29 21:49:15 +00002079 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080 }
2081 return error;
2082}
2083
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002084lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002085Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002086{
Greg Clayton92bb12c2011-05-19 18:17:41 +00002087 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088 if (load_addr != LLDB_INVALID_ADDRESS)
2089 {
2090 BreakpointSiteSP bp_site_sp;
2091
2092 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2093 // create a new breakpoint site and add it.
2094
2095 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2096
2097 if (bp_site_sp)
2098 {
2099 bp_site_sp->AddOwner (owner);
2100 owner->SetBreakpointSite (bp_site_sp);
2101 return bp_site_sp->GetID();
2102 }
2103 else
2104 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002105 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106 if (bp_site_sp)
2107 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002108 Error error = EnableBreakpointSite (bp_site_sp.get());
2109 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110 {
2111 owner->SetBreakpointSite (bp_site_sp);
2112 return m_breakpoint_site_list.Add (bp_site_sp);
2113 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002114 else
2115 {
2116 // Report error for setting breakpoint...
2117 m_target.GetDebugger().GetErrorFile().Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2118 load_addr,
2119 owner->GetBreakpoint().GetID(),
2120 owner->GetID(),
2121 error.AsCString() ? error.AsCString() : "unkown error");
2122 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123 }
2124 }
2125 }
2126 // We failed to enable the breakpoint
2127 return LLDB_INVALID_BREAK_ID;
2128
2129}
2130
2131void
2132Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2133{
2134 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2135 if (num_owners == 0)
2136 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002137 // Don't try to disable the site if we don't have a live process anymore.
2138 if (IsAlive())
2139 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002140 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2141 }
2142}
2143
2144
2145size_t
2146Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2147{
2148 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002149 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002150
Jim Ingham20c77192011-06-29 19:42:28 +00002151 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002153 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2154 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002156 addr_t intersect_addr;
2157 size_t intersect_size;
2158 size_t opcode_offset;
2159 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002160 {
2161 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2162 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002163 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002164 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002165 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002166 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002168 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169 }
2170 return bytes_removed;
2171}
2172
2173
Greg Claytonded470d2011-03-19 01:12:21 +00002174
2175size_t
2176Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2177{
2178 PlatformSP platform_sp (m_target.GetPlatform());
2179 if (platform_sp)
2180 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2181 return 0;
2182}
2183
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184Error
2185Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2186{
2187 Error error;
2188 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002189 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190 const addr_t bp_addr = bp_site->GetLoadAddress();
2191 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002192 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193 if (bp_site->IsEnabled())
2194 {
2195 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002196 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 +00002197 return error;
2198 }
2199
2200 if (bp_addr == LLDB_INVALID_ADDRESS)
2201 {
2202 error.SetErrorString("BreakpointSite contains an invalid load address.");
2203 return error;
2204 }
2205 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2206 // trap for the breakpoint site
2207 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2208
2209 if (bp_opcode_size == 0)
2210 {
Daniel Malead01b2952012-11-29 21:49:15 +00002211 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212 }
2213 else
2214 {
2215 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2216
2217 if (bp_opcode_bytes == NULL)
2218 {
2219 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2220 return error;
2221 }
2222
2223 // Save the original opcode by reading it
2224 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2225 {
2226 // Write a software breakpoint in place of the original opcode
2227 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2228 {
2229 uint8_t verify_bp_opcode_bytes[64];
2230 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2231 {
2232 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2233 {
2234 bp_site->SetEnabled(true);
2235 bp_site->SetType (BreakpointSite::eSoftware);
2236 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002237 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238 bp_site->GetID(),
2239 (uint64_t)bp_addr);
2240 }
2241 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002242 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002243 }
2244 else
2245 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2246 }
2247 else
2248 error.SetErrorString("Unable to write breakpoint trap to memory.");
2249 }
2250 else
2251 error.SetErrorString("Unable to read memory at breakpoint address.");
2252 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002253 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002254 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002255 bp_site->GetID(),
2256 (uint64_t)bp_addr,
2257 error.AsCString());
2258 return error;
2259}
2260
2261Error
2262Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2263{
2264 Error error;
2265 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002266 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002267 addr_t bp_addr = bp_site->GetLoadAddress();
2268 lldb::user_id_t breakID = bp_site->GetID();
2269 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002270 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271
2272 if (bp_site->IsHardware())
2273 {
2274 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2275 }
2276 else if (bp_site->IsEnabled())
2277 {
2278 const size_t break_op_size = bp_site->GetByteSize();
2279 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2280 if (break_op_size > 0)
2281 {
2282 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002283 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002284 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285 bool break_op_found = false;
2286
2287 // Read the breakpoint opcode
2288 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2289 {
2290 bool verify = false;
2291 // Make sure we have the a breakpoint opcode exists at this address
2292 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2293 {
2294 break_op_found = true;
2295 // We found a valid breakpoint opcode at this address, now restore
2296 // the saved opcode.
2297 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2298 {
2299 verify = true;
2300 }
2301 else
2302 error.SetErrorString("Memory write failed when restoring original opcode.");
2303 }
2304 else
2305 {
2306 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2307 // Set verify to true and so we can check if the original opcode has already been restored
2308 verify = true;
2309 }
2310
2311 if (verify)
2312 {
Greg Claytonc982c762010-07-09 20:39:50 +00002313 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002314 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315 // Verify that our original opcode made it back to the inferior
2316 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2317 {
2318 // compare the memory we just read with the original opcode
2319 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2320 {
2321 // SUCCESS
2322 bp_site->SetEnabled(false);
2323 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002324 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 +00002325 return error;
2326 }
2327 else
2328 {
2329 if (break_op_found)
2330 error.SetErrorString("Failed to restore original opcode.");
2331 }
2332 }
2333 else
2334 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2335 }
2336 }
2337 else
2338 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2339 }
2340 }
2341 else
2342 {
2343 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002344 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 +00002345 return error;
2346 }
2347
2348 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002349 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002350 bp_site->GetID(),
2351 (uint64_t)bp_addr,
2352 error.AsCString());
2353 return error;
2354
2355}
2356
Greg Clayton58be07b2011-01-07 06:08:19 +00002357// Uncomment to verify memory caching works after making changes to caching code
2358//#define VERIFY_MEMORY_READS
2359
Sean Callanan64c0cf22012-06-07 22:26:42 +00002360size_t
2361Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2362{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002363 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002364 if (!GetDisableMemoryCache())
2365 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002366#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002367 // Memory caching is enabled, with debug verification
2368
2369 if (buf && size)
2370 {
2371 // Uncomment the line below to make sure memory caching is working.
2372 // I ran this through the test suite and got no assertions, so I am
2373 // pretty confident this is working well. If any changes are made to
2374 // memory caching, uncomment the line below and test your changes!
2375
2376 // Verify all memory reads by using the cache first, then redundantly
2377 // reading the same memory from the inferior and comparing to make sure
2378 // everything is exactly the same.
2379 std::string verify_buf (size, '\0');
2380 assert (verify_buf.size() == size);
2381 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2382 Error verify_error;
2383 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2384 assert (cache_bytes_read == verify_bytes_read);
2385 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2386 assert (verify_error.Success() == error.Success());
2387 return cache_bytes_read;
2388 }
2389 return 0;
2390#else // !defined(VERIFY_MEMORY_READS)
2391 // Memory caching is enabled, without debug verification
2392
2393 return m_memory_cache.Read (addr, buf, size, error);
2394#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002395 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002396 else
2397 {
2398 // Memory caching is disabled
2399
2400 return ReadMemoryFromInferior (addr, buf, size, error);
2401 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002402}
Greg Clayton58be07b2011-01-07 06:08:19 +00002403
Greg Clayton4c82d422012-05-18 23:20:01 +00002404size_t
2405Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2406{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002407 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002408 out_str.clear();
2409 addr_t curr_addr = addr;
2410 while (1)
2411 {
2412 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2413 if (length == 0)
2414 break;
2415 out_str.append(buf, length);
2416 // If we got "length - 1" bytes, we didn't get the whole C string, we
2417 // need to read some more characters
2418 if (length == sizeof(buf) - 1)
2419 curr_addr += length;
2420 else
2421 break;
2422 }
2423 return out_str.size();
2424}
2425
Greg Clayton58be07b2011-01-07 06:08:19 +00002426
2427size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002428Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2429 size_t type_width)
2430{
2431 size_t total_bytes_read = 0;
2432 if (dst && max_bytes && type_width && max_bytes >= type_width)
2433 {
2434 // Ensure a null terminator independent of the number of bytes that is read.
2435 memset (dst, 0, max_bytes);
2436 size_t bytes_left = max_bytes - type_width;
2437
2438 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2439 assert(sizeof(terminator) >= type_width &&
2440 "Attempting to validate a string with more than 4 bytes per character!");
2441
2442 addr_t curr_addr = addr;
2443 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2444 char *curr_dst = dst;
2445
2446 error.Clear();
2447 while (bytes_left > 0 && error.Success())
2448 {
2449 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2450 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2451 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2452
2453 if (bytes_read == 0)
2454 break;
2455
2456 // Search for a null terminator of correct size and alignment in bytes_read
2457 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2458 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2459 if (::strncmp(&dst[i], terminator, type_width) == 0)
2460 {
2461 error.Clear();
2462 return i;
2463 }
2464
2465 total_bytes_read += bytes_read;
2466 curr_dst += bytes_read;
2467 curr_addr += bytes_read;
2468 bytes_left -= bytes_read;
2469 }
2470 }
2471 else
2472 {
2473 if (max_bytes)
2474 error.SetErrorString("invalid arguments");
2475 }
2476 return total_bytes_read;
2477}
2478
2479// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2480// null terminators.
2481size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002482Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002483{
2484 size_t total_cstr_len = 0;
2485 if (dst && dst_max_len)
2486 {
Greg Claytone91b7952011-12-15 03:14:23 +00002487 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002488 // NULL out everything just to be safe
2489 memset (dst, 0, dst_max_len);
2490 Error error;
2491 addr_t curr_addr = addr;
2492 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2493 size_t bytes_left = dst_max_len - 1;
2494 char *curr_dst = dst;
2495
2496 while (bytes_left > 0)
2497 {
2498 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2499 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2500 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2501
2502 if (bytes_read == 0)
2503 {
Greg Claytone91b7952011-12-15 03:14:23 +00002504 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002505 dst[total_cstr_len] = '\0';
2506 break;
2507 }
2508 const size_t len = strlen(curr_dst);
2509
2510 total_cstr_len += len;
2511
2512 if (len < bytes_to_read)
2513 break;
2514
2515 curr_dst += bytes_read;
2516 curr_addr += bytes_read;
2517 bytes_left -= bytes_read;
2518 }
2519 }
Greg Claytone91b7952011-12-15 03:14:23 +00002520 else
2521 {
2522 if (dst == NULL)
2523 result_error.SetErrorString("invalid arguments");
2524 else
2525 result_error.Clear();
2526 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002527 return total_cstr_len;
2528}
2529
2530size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002531Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2532{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533 if (buf == NULL || size == 0)
2534 return 0;
2535
2536 size_t bytes_read = 0;
2537 uint8_t *bytes = (uint8_t *)buf;
2538
2539 while (bytes_read < size)
2540 {
2541 const size_t curr_size = size - bytes_read;
2542 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2543 bytes + bytes_read,
2544 curr_size,
2545 error);
2546 bytes_read += curr_bytes_read;
2547 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2548 break;
2549 }
2550
2551 // Replace any software breakpoint opcodes that fall into this range back
2552 // into "buf" before we return
2553 if (bytes_read > 0)
2554 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2555 return bytes_read;
2556}
2557
Greg Clayton58a4c462010-12-16 20:01:20 +00002558uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002559Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002560{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002561 Scalar scalar;
2562 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2563 return scalar.ULongLong(fail_value);
2564 return fail_value;
2565}
2566
2567addr_t
2568Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2569{
2570 Scalar scalar;
2571 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2572 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2573 return LLDB_INVALID_ADDRESS;
2574}
2575
2576
2577bool
2578Process::WritePointerToMemory (lldb::addr_t vm_addr,
2579 lldb::addr_t ptr_value,
2580 Error &error)
2581{
2582 Scalar scalar;
2583 const uint32_t addr_byte_size = GetAddressByteSize();
2584 if (addr_byte_size <= 4)
2585 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002586 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002587 scalar = ptr_value;
2588 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002589}
2590
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002591size_t
2592Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2593{
2594 size_t bytes_written = 0;
2595 const uint8_t *bytes = (const uint8_t *)buf;
2596
2597 while (bytes_written < size)
2598 {
2599 const size_t curr_size = size - bytes_written;
2600 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2601 bytes + bytes_written,
2602 curr_size,
2603 error);
2604 bytes_written += curr_bytes_written;
2605 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2606 break;
2607 }
2608 return bytes_written;
2609}
2610
2611size_t
2612Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2613{
Greg Clayton58be07b2011-01-07 06:08:19 +00002614#if defined (ENABLE_MEMORY_CACHING)
2615 m_memory_cache.Flush (addr, size);
2616#endif
2617
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618 if (buf == NULL || size == 0)
2619 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002620
Jim Ingham4b536182011-08-09 02:12:22 +00002621 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002622
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623 // We need to write any data that would go where any current software traps
2624 // (enabled software breakpoints) any software traps (breakpoints) that we
2625 // may have placed in our tasks memory.
2626
Greg Claytond8cf1a12013-06-12 00:46:38 +00002627 BreakpointSiteList bp_sites_in_range;
2628
2629 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002630 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002631 // No breakpoint sites overlap
2632 if (bp_sites_in_range.IsEmpty())
2633 return WriteMemoryPrivate (addr, buf, size, error);
2634 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002635 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002636 const uint8_t *ubuf = (const uint8_t *)buf;
2637 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002638
Greg Claytond8cf1a12013-06-12 00:46:38 +00002639 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2640
2641 if (error.Success())
2642 {
2643 addr_t intersect_addr;
2644 size_t intersect_size;
2645 size_t opcode_offset;
2646 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2647 assert(intersects);
2648 assert(addr <= intersect_addr && intersect_addr < addr + size);
2649 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2650 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2651
2652 // Check for bytes before this breakpoint
2653 const addr_t curr_addr = addr + bytes_written;
2654 if (intersect_addr > curr_addr)
2655 {
2656 // There are some bytes before this breakpoint that we need to
2657 // just write to memory
2658 size_t curr_size = intersect_addr - curr_addr;
2659 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2660 ubuf + bytes_written,
2661 curr_size,
2662 error);
2663 bytes_written += curr_bytes_written;
2664 if (curr_bytes_written != curr_size)
2665 {
2666 // We weren't able to write all of the requested bytes, we
2667 // are done looping and will return the number of bytes that
2668 // we have written so far.
2669 if (error.Success())
2670 error.SetErrorToGenericError();
2671 }
2672 }
2673 // Now write any bytes that would cover up any software breakpoints
2674 // directly into the breakpoint opcode buffer
2675 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2676 bytes_written += intersect_size;
2677 }
2678 });
2679
2680 if (bytes_written < size)
2681 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2682 ubuf + bytes_written,
2683 size - bytes_written,
2684 error);
2685 }
2686 }
2687 else
2688 {
2689 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002690 }
2691
2692 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002693 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002695
2696size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002697Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002698{
2699 if (byte_size == UINT32_MAX)
2700 byte_size = scalar.GetByteSize();
2701 if (byte_size > 0)
2702 {
2703 uint8_t buf[32];
2704 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2705 if (mem_size > 0)
2706 return WriteMemory(addr, buf, mem_size, error);
2707 else
2708 error.SetErrorString ("failed to get scalar as memory data");
2709 }
2710 else
2711 {
2712 error.SetErrorString ("invalid scalar value");
2713 }
2714 return 0;
2715}
2716
2717size_t
2718Process::ReadScalarIntegerFromMemory (addr_t addr,
2719 uint32_t byte_size,
2720 bool is_signed,
2721 Scalar &scalar,
2722 Error &error)
2723{
Greg Clayton7060f892013-05-01 23:41:30 +00002724 uint64_t uval = 0;
2725 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002726 {
Greg Clayton7060f892013-05-01 23:41:30 +00002727 error.SetErrorString ("byte size is zero");
2728 }
2729 else if (byte_size & (byte_size - 1))
2730 {
2731 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2732 }
2733 else if (byte_size <= sizeof(uval))
2734 {
2735 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002736 if (bytes_read == byte_size)
2737 {
2738 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002739 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002740 if (byte_size <= 4)
2741 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002742 else
Greg Clayton7060f892013-05-01 23:41:30 +00002743 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002744 if (is_signed)
2745 scalar.SignExtend(byte_size * 8);
2746 return bytes_read;
2747 }
2748 }
2749 else
2750 {
2751 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2752 }
2753 return 0;
2754}
2755
Greg Claytond495c532011-05-17 03:37:42 +00002756#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757addr_t
2758Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2759{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002760 if (GetPrivateState() != eStateStopped)
2761 return LLDB_INVALID_ADDRESS;
2762
Greg Claytond495c532011-05-17 03:37:42 +00002763#if defined (USE_ALLOCATE_MEMORY_CACHE)
2764 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2765#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002766 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002767 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002768 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002769 log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Deepak Panickald66b50c2013-10-22 12:27:43 +00002770 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002771 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002772 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002773 m_mod_id.GetStopID(),
2774 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002775 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002776#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777}
2778
Sean Callanan90539452011-09-20 23:01:51 +00002779bool
2780Process::CanJIT ()
2781{
Sean Callanana7b443a2012-02-14 22:50:38 +00002782 if (m_can_jit == eCanJITDontKnow)
2783 {
2784 Error err;
2785
2786 uint64_t allocated_memory = AllocateMemory(8,
2787 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2788 err);
2789
2790 if (err.Success())
2791 m_can_jit = eCanJITYes;
2792 else
2793 m_can_jit = eCanJITNo;
2794
2795 DeallocateMemory (allocated_memory);
2796 }
2797
Sean Callanan90539452011-09-20 23:01:51 +00002798 return m_can_jit == eCanJITYes;
2799}
2800
2801void
2802Process::SetCanJIT (bool can_jit)
2803{
2804 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2805}
2806
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807Error
2808Process::DeallocateMemory (addr_t ptr)
2809{
Greg Claytond495c532011-05-17 03:37:42 +00002810 Error error;
2811#if defined (USE_ALLOCATE_MEMORY_CACHE)
2812 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2813 {
Daniel Malead01b2952012-11-29 21:49:15 +00002814 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002815 }
2816#else
2817 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002818
Greg Clayton5160ce52013-03-27 23:08:40 +00002819 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002820 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002821 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 +00002822 ptr,
2823 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002824 m_mod_id.GetStopID(),
2825 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002826#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002827 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828}
2829
Han Ming Ongc811d382012-11-17 00:33:14 +00002830
Greg Claytonc9660542012-02-05 02:38:54 +00002831ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002832Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002833 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002834{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002835 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002836 if (module_sp)
2837 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002838 Error error;
2839 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2840 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002841 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002842 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002843 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002844}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002845
2846Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002847Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848{
2849 Error error;
2850 error.SetErrorString("watchpoints are not supported");
2851 return error;
2852}
2853
2854Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002855Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002856{
2857 Error error;
2858 error.SetErrorString("watchpoints are not supported");
2859 return error;
2860}
2861
2862StateType
2863Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2864{
2865 StateType state;
2866 // Now wait for the process to launch and return control to us, and then
2867 // call DidLaunch:
2868 while (1)
2869 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002870 event_sp.reset();
2871 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2872
Greg Clayton2637f822011-11-17 01:23:07 +00002873 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002874 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002875
2876 // If state is invalid, then we timed out
2877 if (state == eStateInvalid)
2878 break;
2879
2880 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002881 HandlePrivateEvent (event_sp);
2882 }
2883 return state;
2884}
2885
2886Error
Greg Clayton982c9762011-11-03 21:22:33 +00002887Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888{
2889 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002891 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002892 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002893 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002894 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895
Greg Claytonaa149cb2011-08-11 02:48:45 +00002896 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897 if (exe_module)
2898 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002899 char local_exec_file_path[PATH_MAX];
2900 char platform_exec_file_path[PATH_MAX];
2901 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2902 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903 if (exe_module->GetFileSpec().Exists())
2904 {
Greg Clayton71337622011-02-24 22:24:29 +00002905 if (PrivateStateThreadIsValid ())
2906 PausePrivateStateThread ();
2907
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908 error = WillLaunch (exe_module);
2909 if (error.Success())
2910 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002911 const bool restarted = false;
2912 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002913 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002914
Ed Maste64fad602013-07-29 20:58:06 +00002915 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002916 {
2917 // Now launch using these arguments.
2918 error = DoLaunch (exe_module, launch_info);
2919 }
2920 else
2921 {
2922 // This shouldn't happen
2923 error.SetErrorString("failed to acquire process run lock");
2924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925
2926 if (error.Fail())
2927 {
2928 if (GetID() != LLDB_INVALID_PROCESS_ID)
2929 {
2930 SetID (LLDB_INVALID_PROCESS_ID);
2931 const char *error_string = error.AsCString();
2932 if (error_string == NULL)
2933 error_string = "launch failed";
2934 SetExitStatus (-1, error_string);
2935 }
2936 }
2937 else
2938 {
2939 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002940 TimeValue timeout_time;
2941 timeout_time = TimeValue::Now();
2942 timeout_time.OffsetWithSeconds(10);
2943 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944
Greg Clayton1a38ea72011-06-22 01:42:17 +00002945 if (state == eStateInvalid || event_sp.get() == NULL)
2946 {
2947 // We were able to launch the process, but we failed to
2948 // catch the initial stop.
2949 SetExitStatus (0, "failed to catch stop after launch");
2950 Destroy();
2951 }
2952 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002953 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002954
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002955 DidLaunch ();
2956
Greg Claytonc859e2d2012-02-13 23:10:39 +00002957 DynamicLoader *dyld = GetDynamicLoader ();
2958 if (dyld)
2959 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002960
Jason Molendaeef51062013-11-05 03:57:19 +00002961 SystemRuntime *system_runtime = GetSystemRuntime ();
2962 if (system_runtime)
2963 system_runtime->DidLaunch();
2964
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002965 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966 // This delays passing the stopped event to listeners till DidLaunch gets
2967 // a chance to complete...
2968 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002969
2970 if (PrivateStateThreadIsValid ())
2971 ResumePrivateStateThread ();
2972 else
2973 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002974 }
2975 else if (state == eStateExited)
2976 {
2977 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2978 // not likely to work, and return an invalid pid.
2979 HandlePrivateEvent (event_sp);
2980 }
2981 }
2982 }
2983 }
2984 else
2985 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002986 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987 }
2988 }
2989 return error;
2990}
2991
Greg Claytonc3776bf2012-02-09 06:16:32 +00002992
2993Error
2994Process::LoadCore ()
2995{
2996 Error error = DoLoadCore();
2997 if (error.Success())
2998 {
2999 if (PrivateStateThreadIsValid ())
3000 ResumePrivateStateThread ();
3001 else
3002 StartPrivateStateThread ();
3003
Greg Claytonc859e2d2012-02-13 23:10:39 +00003004 DynamicLoader *dyld = GetDynamicLoader ();
3005 if (dyld)
3006 dyld->DidAttach();
3007
Jason Molendaeef51062013-11-05 03:57:19 +00003008 SystemRuntime *system_runtime = GetSystemRuntime ();
3009 if (system_runtime)
3010 system_runtime->DidAttach();
3011
Greg Claytonc859e2d2012-02-13 23:10:39 +00003012 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003013 // We successfully loaded a core file, now pretend we stopped so we can
3014 // show all of the threads in the core file and explore the crashed
3015 // state.
3016 SetPrivateState (eStateStopped);
3017
3018 }
3019 return error;
3020}
3021
Greg Claytonc859e2d2012-02-13 23:10:39 +00003022DynamicLoader *
3023Process::GetDynamicLoader ()
3024{
3025 if (m_dyld_ap.get() == NULL)
3026 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3027 return m_dyld_ap.get();
3028}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003029
Jason Molendaeef51062013-11-05 03:57:19 +00003030SystemRuntime *
3031Process::GetSystemRuntime ()
3032{
3033 if (m_system_runtime_ap.get() == NULL)
3034 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3035 return m_system_runtime_ap.get();
3036}
3037
Greg Claytonc3776bf2012-02-09 06:16:32 +00003038
Jim Inghambb3a2832011-01-29 01:49:25 +00003039Process::NextEventAction::EventActionResult
3040Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003041{
Jim Inghambb3a2832011-01-29 01:49:25 +00003042 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3043 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003044 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003045 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003046 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003047 return eEventActionRetry;
3048
3049 case eStateStopped:
3050 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003051 {
3052 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003053 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003054 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003055 // We don't want these events to be reported, so go set the ShouldReportStop here:
3056 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3057
Greg Claytonc9ed4782011-11-12 02:10:56 +00003058 if (m_exec_count > 0)
3059 {
3060 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003061 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003062 return eEventActionRetry;
3063 }
3064 else
3065 {
3066 m_process->CompleteAttach ();
3067 return eEventActionSuccess;
3068 }
3069 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003070 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003071
Greg Clayton513c26c2011-01-29 07:10:55 +00003072 default:
3073 case eStateExited:
3074 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003075 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003076 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003077
3078 m_exit_string.assign ("No valid Process");
3079 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003080}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081
Jim Inghambb3a2832011-01-29 01:49:25 +00003082Process::NextEventAction::EventActionResult
3083Process::AttachCompletionHandler::HandleBeingInterrupted()
3084{
3085 return eEventActionSuccess;
3086}
3087
3088const char *
3089Process::AttachCompletionHandler::GetExitString ()
3090{
3091 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003092}
3093
3094Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003095Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003098 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003099 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003100 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003101 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003102
Greg Clayton144f3a92011-11-15 03:53:30 +00003103 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003104 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003105 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003106 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003107 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003108
Greg Clayton144f3a92011-11-15 03:53:30 +00003109 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003110 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003111 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3112
3113 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003114 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003115 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3116 if (error.Success())
3117 {
Ed Maste64fad602013-07-29 20:58:06 +00003118 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003119 {
3120 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003121 const bool restarted = false;
3122 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003123 // Now attach using these arguments.
3124 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3125 }
3126 else
3127 {
3128 // This shouldn't happen
3129 error.SetErrorString("failed to acquire process run lock");
3130 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003131
Greg Clayton144f3a92011-11-15 03:53:30 +00003132 if (error.Fail())
3133 {
3134 if (GetID() != LLDB_INVALID_PROCESS_ID)
3135 {
3136 SetID (LLDB_INVALID_PROCESS_ID);
3137 if (error.AsCString() == NULL)
3138 error.SetErrorString("attach failed");
3139
3140 SetExitStatus(-1, error.AsCString());
3141 }
3142 }
3143 else
3144 {
3145 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3146 StartPrivateStateThread();
3147 }
3148 return error;
3149 }
Greg Claytone996fd32011-03-08 22:40:15 +00003150 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003151 else
Greg Claytone996fd32011-03-08 22:40:15 +00003152 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003153 ProcessInstanceInfoList process_infos;
3154 PlatformSP platform_sp (m_target.GetPlatform ());
3155
3156 if (platform_sp)
3157 {
3158 ProcessInstanceInfoMatch match_info;
3159 match_info.GetProcessInfo() = attach_info;
3160 match_info.SetNameMatchType (eNameMatchEquals);
3161 platform_sp->FindProcesses (match_info, process_infos);
3162 const uint32_t num_matches = process_infos.GetSize();
3163 if (num_matches == 1)
3164 {
3165 attach_pid = process_infos.GetProcessIDAtIndex(0);
3166 // Fall through and attach using the above process ID
3167 }
3168 else
3169 {
3170 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3171 if (num_matches > 1)
3172 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3173 else
3174 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3175 }
3176 }
3177 else
3178 {
3179 error.SetErrorString ("invalid platform, can't find processes by name");
3180 return error;
3181 }
Greg Claytone996fd32011-03-08 22:40:15 +00003182 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183 }
3184 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003185 {
3186 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003187 }
3188 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003189
3190 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003191 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003192 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003193 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003194 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003195
Ed Maste64fad602013-07-29 20:58:06 +00003196 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003197 {
3198 // Now attach using these arguments.
3199 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003200 const bool restarted = false;
3201 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003202 error = DoAttachToProcessWithID (attach_pid, attach_info);
3203 }
3204 else
3205 {
3206 // This shouldn't happen
3207 error.SetErrorString("failed to acquire process run lock");
3208 }
3209
Greg Clayton144f3a92011-11-15 03:53:30 +00003210 if (error.Success())
3211 {
3212
3213 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3214 StartPrivateStateThread();
3215 }
3216 else
Greg Claytone996fd32011-03-08 22:40:15 +00003217 {
3218 if (GetID() != LLDB_INVALID_PROCESS_ID)
3219 {
3220 SetID (LLDB_INVALID_PROCESS_ID);
3221 const char *error_string = error.AsCString();
3222 if (error_string == NULL)
3223 error_string = "attach failed";
3224
3225 SetExitStatus(-1, error_string);
3226 }
3227 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 }
3229 }
3230 return error;
3231}
3232
Greg Clayton93d3c8332011-02-16 04:46:07 +00003233void
3234Process::CompleteAttach ()
3235{
3236 // Let the process subclass figure out at much as it can about the process
3237 // before we go looking for a dynamic loader plug-in.
3238 DidAttach();
3239
Jim Ingham4299fdb2011-09-15 01:10:17 +00003240 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3241 // the same as the one we've already set, switch architectures.
3242 PlatformSP platform_sp (m_target.GetPlatform ());
3243 assert (platform_sp.get());
3244 if (platform_sp)
3245 {
Greg Clayton70512312012-05-08 01:45:38 +00003246 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003247 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003248 {
3249 ArchSpec platform_arch;
3250 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3251 if (platform_sp)
3252 {
3253 m_target.SetPlatform (platform_sp);
3254 m_target.SetArchitecture(platform_arch);
3255 }
3256 }
3257 else
3258 {
3259 ProcessInstanceInfo process_info;
3260 platform_sp->GetProcessInfo (GetID(), process_info);
3261 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003262 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003263 m_target.SetArchitecture (process_arch);
3264 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003265 }
3266
3267 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003268 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003269 DynamicLoader *dyld = GetDynamicLoader ();
3270 if (dyld)
3271 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003272
Jason Molendaeef51062013-11-05 03:57:19 +00003273 SystemRuntime *system_runtime = GetSystemRuntime ();
3274 if (system_runtime)
3275 system_runtime->DidAttach();
3276
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003277 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003278 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003279 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003280 Mutex::Locker modules_locker(target_modules.GetMutex());
3281 size_t num_modules = target_modules.GetSize();
3282 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003283
Andy Gibbsa297a972013-06-19 19:04:53 +00003284 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003285 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003286 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003287 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003288 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003289 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003290 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003291 break;
3292 }
3293 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003294 if (new_executable_module_sp)
3295 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003296}
3297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003299Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003300{
Greg Claytonb766a732011-02-04 01:58:07 +00003301 m_abi_sp.reset();
3302 m_process_input_reader.reset();
3303
3304 // Find the process and its architecture. Make sure it matches the architecture
3305 // of the current Target, and if not adjust it.
3306
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003307 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003308 if (error.Success())
3309 {
Greg Clayton71337622011-02-24 22:24:29 +00003310 if (GetID() != LLDB_INVALID_PROCESS_ID)
3311 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003312 EventSP event_sp;
3313 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3314
3315 if (state == eStateStopped || state == eStateCrashed)
3316 {
3317 // If we attached and actually have a process on the other end, then
3318 // this ended up being the equivalent of an attach.
3319 CompleteAttach ();
3320
3321 // This delays passing the stopped event to listeners till
3322 // CompleteAttach gets a chance to complete...
3323 HandlePrivateEvent (event_sp);
3324
3325 }
Greg Clayton71337622011-02-24 22:24:29 +00003326 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003327
3328 if (PrivateStateThreadIsValid ())
3329 ResumePrivateStateThread ();
3330 else
3331 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003332 }
3333 return error;
3334}
3335
3336
3337Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003338Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003339{
Greg Clayton5160ce52013-03-27 23:08:40 +00003340 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003341 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003342 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003343 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003344 StateAsCString(m_public_state.GetValue()),
3345 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003346
3347 Error error (WillResume());
3348 // Tell the process it is about to resume before the thread list
3349 if (error.Success())
3350 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003351 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003352 // can let all of our threads know that they are about to be
3353 // resumed. Threads will each be called with
3354 // Thread::WillResume(StateType) where StateType contains the state
3355 // that they are supposed to have when the process is resumed
3356 // (suspended/running/stepping). Threads should also check
3357 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003358 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003359 if (m_thread_list.WillResume())
3360 {
Jim Ingham372787f2012-04-07 00:00:41 +00003361 // Last thing, do the PreResumeActions.
3362 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363 {
Jim Ingham0161b492013-02-09 01:29:05 +00003364 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003365 }
3366 else
3367 {
3368 m_mod_id.BumpResumeID();
3369 error = DoResume();
3370 if (error.Success())
3371 {
3372 DidResume();
3373 m_thread_list.DidResume();
3374 if (log)
3375 log->Printf ("Process thinks the process has resumed.");
3376 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003377 }
3378 }
3379 else
3380 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003381 // Somebody wanted to run without running. So generate a continue & a stopped event,
3382 // and let the world handle them.
3383 if (log)
3384 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3385
3386 SetPrivateState(eStateRunning);
3387 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003388 }
3389 }
Jim Ingham444586b2011-01-24 06:34:17 +00003390 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003391 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392 return error;
3393}
3394
3395Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003396Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003397{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003398 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3399 // in case it was already set and some thread plan logic calls halt on its
3400 // own.
3401 m_clear_thread_plans_on_stop |= clear_thread_plans;
3402
Jim Inghamaacc3182012-06-06 00:29:30 +00003403 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3404 // we could just straightaway get another event. It just narrows the window...
3405 m_currently_handling_event.WaitForValueEqualTo(false);
3406
3407
Jim Inghambb3a2832011-01-29 01:49:25 +00003408 // Pause our private state thread so we can ensure no one else eats
3409 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003410 Listener halt_listener ("lldb.process.halt_listener");
3411 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003412
Jim Inghambb3a2832011-01-29 01:49:25 +00003413 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003414 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003415
Greg Clayton513c26c2011-01-29 07:10:55 +00003416 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003417 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003418
Greg Clayton513c26c2011-01-29 07:10:55 +00003419 bool caused_stop = false;
3420
3421 // Ask the process subclass to actually halt our process
3422 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003423 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003424 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003425 if (m_public_state.GetValue() == eStateAttaching)
3426 {
3427 SetExitStatus(SIGKILL, "Cancelled async attach.");
3428 Destroy ();
3429 }
3430 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003431 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003432 // If "caused_stop" is true, then DoHalt stopped the process. If
3433 // "caused_stop" is false, the process was already stopped.
3434 // If the DoHalt caused the process to stop, then we want to catch
3435 // this event and set the interrupted bool to true before we pass
3436 // this along so clients know that the process was interrupted by
3437 // a halt command.
3438 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003439 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003440 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003441 TimeValue timeout_time;
3442 timeout_time = TimeValue::Now();
3443 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003444 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3445 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003446
Jim Ingham0f16e732011-02-08 05:20:59 +00003447 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003448 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003449 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003450 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003451 }
3452 else
3453 {
Greg Clayton2637f822011-11-17 01:23:07 +00003454 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003455 {
3456 // We caused the process to interrupt itself, so mark this
3457 // as such in the stop event so clients can tell an interrupted
3458 // process from a natural stop
3459 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3460 }
3461 else
3462 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003463 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003464 if (log)
3465 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3466 error.SetErrorString ("Did not get stopped event after halt.");
3467 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003468 }
3469 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003470 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003471 }
3472 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003473 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003474 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003475 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003476
3477 // Post any event we might have consumed. If all goes well, we will have
3478 // stopped the process, intercepted the event and set the interrupted
3479 // bool in the event. Post it to the private event queue and that will end up
3480 // correctly setting the state.
3481 if (event_sp)
3482 m_private_state_broadcaster.BroadcastEvent(event_sp);
3483
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484 return error;
3485}
3486
3487Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003488Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3489{
3490 Error error;
3491 if (m_public_state.GetValue() == eStateRunning)
3492 {
3493 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3494 if (log)
3495 log->Printf("Process::Destroy() About to halt.");
3496 error = Halt();
3497 if (error.Success())
3498 {
3499 // Consume the halt event.
3500 TimeValue timeout (TimeValue::Now());
3501 timeout.OffsetWithSeconds(1);
3502 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3503
3504 // If the process exited while we were waiting for it to stop, put the exited event into
3505 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3506 // they don't have a process anymore...
3507
3508 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3509 {
3510 if (log)
3511 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3512 return error;
3513 }
3514 else
3515 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3516
3517 if (state != eStateStopped)
3518 {
3519 if (log)
3520 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3521 // If we really couldn't stop the process then we should just error out here, but if the
3522 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3523 StateType private_state = m_private_state.GetValue();
3524 if (private_state != eStateStopped)
3525 {
3526 return error;
3527 }
3528 }
3529 }
3530 else
3531 {
3532 if (log)
3533 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3534 }
3535 }
3536 return error;
3537}
3538
3539Error
Jim Inghamacff8952013-05-02 00:27:30 +00003540Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003542 EventSP exit_event_sp;
3543 Error error;
3544 m_destroy_in_process = true;
3545
3546 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003547
3548 if (error.Success())
3549 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003550 if (DetachRequiresHalt())
3551 {
3552 error = HaltForDestroyOrDetach (exit_event_sp);
3553 if (!error.Success())
3554 {
3555 m_destroy_in_process = false;
3556 return error;
3557 }
3558 else if (exit_event_sp)
3559 {
3560 // We shouldn't need to do anything else here. There's no process left to detach from...
3561 StopPrivateStateThread();
3562 m_destroy_in_process = false;
3563 return error;
3564 }
3565 }
3566
Jim Inghamacff8952013-05-02 00:27:30 +00003567 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003568 if (error.Success())
3569 {
3570 DidDetach();
3571 StopPrivateStateThread();
3572 }
Jim Inghamacff8952013-05-02 00:27:30 +00003573 else
3574 {
3575 return error;
3576 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003578 m_destroy_in_process = false;
3579
3580 // If we exited when we were waiting for a process to stop, then
3581 // forward the event here so we don't lose the event
3582 if (exit_event_sp)
3583 {
3584 // Directly broadcast our exited event because we shut down our
3585 // private state thread above
3586 BroadcastEvent(exit_event_sp);
3587 }
3588
3589 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3590 // the last events through the event system, in which case we might strand the write lock. Unlock
3591 // it here so when we do to tear down the process we don't get an error destroying the lock.
3592
Ed Maste64fad602013-07-29 20:58:06 +00003593 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003594 return error;
3595}
3596
3597Error
3598Process::Destroy ()
3599{
Jim Ingham09437922013-03-01 20:04:25 +00003600
3601 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3602 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3603 // failed and the process stays around for some reason it won't be in a confused state.
3604
3605 m_destroy_in_process = true;
3606
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003607 Error error (WillDestroy());
3608 if (error.Success())
3609 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003610 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003611 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003612 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003613 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003614 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003615
Jim Inghamaacc3182012-06-06 00:29:30 +00003616 if (m_public_state.GetValue() != eStateRunning)
3617 {
3618 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3619 // kill it, we don't want it hitting a breakpoint...
3620 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3621 // we're not going to have much luck doing this now.
3622 m_thread_list.DiscardThreadPlans();
3623 DisableAllBreakpointSites();
3624 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626 error = DoDestroy();
3627 if (error.Success())
3628 {
3629 DidDestroy();
3630 StopPrivateStateThread();
3631 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003632 m_stdio_communication.StopReadThread();
3633 m_stdio_communication.Disconnect();
3634 if (m_process_input_reader && m_process_input_reader->IsActive())
3635 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3636 if (m_process_input_reader)
3637 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003638
3639 // If we exited when we were waiting for a process to stop, then
3640 // forward the event here so we don't lose the event
3641 if (exit_event_sp)
3642 {
3643 // Directly broadcast our exited event because we shut down our
3644 // private state thread above
3645 BroadcastEvent(exit_event_sp);
3646 }
3647
Jim Inghamb1e2e842012-04-12 18:49:31 +00003648 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3649 // the last events through the event system, in which case we might strand the write lock. Unlock
3650 // 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 +00003651 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003652 }
Jim Ingham09437922013-03-01 20:04:25 +00003653
3654 m_destroy_in_process = false;
3655
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003656 return error;
3657}
3658
3659Error
3660Process::Signal (int signal)
3661{
3662 Error error (WillSignal());
3663 if (error.Success())
3664 {
3665 error = DoSignal(signal);
3666 if (error.Success())
3667 DidSignal();
3668 }
3669 return error;
3670}
3671
Greg Clayton514487e2011-02-15 21:59:32 +00003672lldb::ByteOrder
3673Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003674{
Greg Clayton514487e2011-02-15 21:59:32 +00003675 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676}
3677
3678uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003679Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003680{
Greg Clayton514487e2011-02-15 21:59:32 +00003681 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003682}
3683
Greg Clayton514487e2011-02-15 21:59:32 +00003684
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003685bool
3686Process::ShouldBroadcastEvent (Event *event_ptr)
3687{
3688 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3689 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003690 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003691
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003692 switch (state)
3693 {
Greg Claytonb766a732011-02-04 01:58:07 +00003694 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003695 case eStateAttaching:
3696 case eStateLaunching:
3697 case eStateDetached:
3698 case eStateExited:
3699 case eStateUnloaded:
3700 // These events indicate changes in the state of the debugging session, always report them.
3701 return_value = true;
3702 break;
3703 case eStateInvalid:
3704 // We stopped for no apparent reason, don't report it.
3705 return_value = false;
3706 break;
3707 case eStateRunning:
3708 case eStateStepping:
3709 // If we've started the target running, we handle the cases where we
3710 // are already running and where there is a transition from stopped to
3711 // running differently.
3712 // running -> running: Automatically suppress extra running events
3713 // stopped -> running: Report except when there is one or more no votes
3714 // and no yes votes.
3715 SynchronouslyNotifyStateChanged (state);
Jim Ingham0161b492013-02-09 01:29:05 +00003716 switch (m_last_broadcast_state)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717 {
3718 case eStateRunning:
3719 case eStateStepping:
3720 // We always suppress multiple runnings with no PUBLIC stop in between.
3721 return_value = false;
3722 break;
3723 default:
3724 // TODO: make this work correctly. For now always report
3725 // run if we aren't running so we don't miss any runnning
3726 // events. If I run the lldb/test/thread/a.out file and
3727 // break at main.cpp:58, run and hit the breakpoints on
3728 // multiple threads, then somehow during the stepping over
3729 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003730
3731 // This is a transition from stop to run.
3732 switch (m_thread_list.ShouldReportRun (event_ptr))
3733 {
3734 case eVoteYes:
3735 case eVoteNoOpinion:
3736 return_value = true;
3737 break;
3738 case eVoteNo:
3739 return_value = false;
3740 break;
3741 }
3742 break;
3743 }
3744 break;
3745 case eStateStopped:
3746 case eStateCrashed:
3747 case eStateSuspended:
3748 {
3749 // We've stopped. First see if we're going to restart the target.
3750 // If we are going to stop, then we always broadcast the event.
3751 // 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 +00003752 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003753
Jim Inghamcb4ca112012-05-16 01:32:14 +00003754 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003755 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003756 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003757 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003758 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3759 event_ptr,
3760 StateAsCString(state));
3761 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003762 }
3763 else
3764 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003765 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3766 bool should_resume = false;
3767
Jim Ingham0161b492013-02-09 01:29:05 +00003768 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3769 // Asking the thread list is also not likely to go well, since we are running again.
3770 // So in that case just report the event.
3771
Jim Ingham0161b492013-02-09 01:29:05 +00003772 if (!was_restarted)
3773 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003774
3775 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003776 {
Jim Ingham0161b492013-02-09 01:29:05 +00003777 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3778 if (log)
3779 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3780 should_resume,
3781 StateAsCString(state),
3782 was_restarted,
3783 stop_vote);
3784
3785 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786 {
3787 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003788 return_value = true;
3789 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791 case eVoteNo:
3792 return_value = false;
3793 break;
3794 }
Jim Ingham0161b492013-02-09 01:29:05 +00003795
Jim Inghamcb95f342012-09-05 21:13:56 +00003796 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003797 {
3798 if (log)
3799 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3800 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003801 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003802 }
3803
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003804 }
3805 else
3806 {
3807 return_value = true;
3808 SynchronouslyNotifyStateChanged (state);
3809 }
3810 }
3811 }
Jim Ingham0161b492013-02-09 01:29:05 +00003812 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003813 }
Jim Ingham0161b492013-02-09 01:29:05 +00003814
3815 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3816 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3817 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3818 // because the PublicState reflects the last event pulled off the queue, and there may be several
3819 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3820 // yet. m_last_broadcast_state gets updated here.
3821
3822 if (return_value)
3823 m_last_broadcast_state = state;
3824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003826 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3827 event_ptr,
3828 StateAsCString(state),
3829 StateAsCString(m_last_broadcast_state),
3830 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003831 return return_value;
3832}
3833
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003834
3835bool
Jim Ingham372787f2012-04-07 00:00:41 +00003836Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003837{
Greg Clayton5160ce52013-03-27 23:08:40 +00003838 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003839
Greg Clayton8b82f082011-04-12 05:54:46 +00003840 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003841 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003842 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3843
Jim Ingham372787f2012-04-07 00:00:41 +00003844 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003845 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003846
3847 // Create a thread that watches our internal state and controls which
3848 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003849 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003850 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003851 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003852 else
Daniel Malead01b2952012-11-29 21:49:15 +00003853 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003854
3855 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003856 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003857 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3858 if (success)
3859 {
3860 ResumePrivateStateThread();
3861 return true;
3862 }
3863 else
3864 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003865}
3866
3867void
3868Process::PausePrivateStateThread ()
3869{
3870 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3871}
3872
3873void
3874Process::ResumePrivateStateThread ()
3875{
3876 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3877}
3878
3879void
3880Process::StopPrivateStateThread ()
3881{
Greg Clayton8b82f082011-04-12 05:54:46 +00003882 if (PrivateStateThreadIsValid ())
3883 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003884 else
3885 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003886 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003887 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003888 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003889 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890}
3891
3892void
3893Process::ControlPrivateStateThread (uint32_t signal)
3894{
Greg Clayton5160ce52013-03-27 23:08:40 +00003895 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896
3897 assert (signal == eBroadcastInternalStateControlStop ||
3898 signal == eBroadcastInternalStateControlPause ||
3899 signal == eBroadcastInternalStateControlResume);
3900
3901 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003902 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003903
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003904 // Signal the private state thread. First we should copy this is case the
3905 // thread starts exiting since the private state thread will NULL this out
3906 // when it exits
3907 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003908 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003909 {
3910 TimeValue timeout_time;
3911 bool timed_out;
3912
3913 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3914
3915 timeout_time = TimeValue::Now();
3916 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003917 if (log)
3918 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003919 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3920 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3921
3922 if (signal == eBroadcastInternalStateControlStop)
3923 {
3924 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003925 {
3926 Error error;
3927 Host::ThreadCancel (private_state_thread, &error);
3928 if (log)
3929 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3930 }
3931 else
3932 {
3933 if (log)
3934 log->Printf ("The control event killed the private state thread without having to cancel.");
3935 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003936
3937 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003938 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003939 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003940 }
3941 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003942 else
3943 {
3944 if (log)
3945 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3946 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947}
3948
3949void
Jim Inghamcfc09352012-07-27 23:57:19 +00003950Process::SendAsyncInterrupt ()
3951{
3952 if (PrivateStateThreadIsValid())
3953 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3954 else
3955 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3956}
3957
3958void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003959Process::HandlePrivateEvent (EventSP &event_sp)
3960{
Greg Clayton5160ce52013-03-27 23:08:40 +00003961 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003962 m_resume_requested = false;
3963
Jim Inghamaacc3182012-06-06 00:29:30 +00003964 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003965
Greg Clayton414f5d32011-01-25 02:58:48 +00003966 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003967
3968 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003969 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003970 {
Jim Ingham754ab982011-01-29 04:05:41 +00003971 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003972 if (log)
3973 log->Printf ("Ran next event action, result was %d.", action_result);
3974
Jim Inghambb3a2832011-01-29 01:49:25 +00003975 switch (action_result)
3976 {
3977 case NextEventAction::eEventActionSuccess:
3978 SetNextEventAction(NULL);
3979 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003980
Jim Inghambb3a2832011-01-29 01:49:25 +00003981 case NextEventAction::eEventActionRetry:
3982 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003983
Jim Inghambb3a2832011-01-29 01:49:25 +00003984 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003985 // Handle Exiting Here. If we already got an exited event,
3986 // we should just propagate it. Otherwise, swallow this event,
3987 // and set our state to exit so the next event will kill us.
3988 if (new_state != eStateExited)
3989 {
3990 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003991 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003992 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003993 SetNextEventAction(NULL);
3994 return;
3995 }
3996 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003997 break;
3998 }
3999 }
4000
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004001 // See if we should broadcast this state to external clients?
4002 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004003
4004 if (should_broadcast)
4005 {
4006 if (log)
4007 {
Daniel Malead01b2952012-11-29 21:49:15 +00004008 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004009 __FUNCTION__,
4010 GetID(),
4011 StateAsCString(new_state),
4012 StateAsCString (GetState ()),
4013 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004014 }
Jim Ingham9575d842011-03-11 03:53:59 +00004015 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004016 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004017 PushProcessInputReader ();
Jim Inghamb78d73f2013-05-15 01:21:48 +00004018 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004019 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00004020
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004021 BroadcastEvent (event_sp);
4022 }
4023 else
4024 {
4025 if (log)
4026 {
Daniel Malead01b2952012-11-29 21:49:15 +00004027 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004028 __FUNCTION__,
4029 GetID(),
4030 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004031 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004032 }
4033 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004034 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004035}
4036
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004037thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038Process::PrivateStateThread (void *arg)
4039{
4040 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004041 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042 return result;
4043}
4044
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004045thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004046Process::RunPrivateStateThread ()
4047{
Jim Ingham076b3042012-04-10 01:21:57 +00004048 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004049 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050
Greg Clayton5160ce52013-03-27 23:08:40 +00004051 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004052 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004053 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004054
4055 bool exit_now = false;
4056 while (!exit_now)
4057 {
4058 EventSP event_sp;
4059 WaitForEventsPrivate (NULL, event_sp, control_only);
4060 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4061 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004062 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004063 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 +00004064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004065 switch (event_sp->GetType())
4066 {
4067 case eBroadcastInternalStateControlStop:
4068 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004069 break; // doing any internal state managment below
4070
4071 case eBroadcastInternalStateControlPause:
4072 control_only = true;
4073 break;
4074
4075 case eBroadcastInternalStateControlResume:
4076 control_only = false;
4077 break;
4078 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004080 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004081 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004082 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004083 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4084 {
4085 if (m_public_state.GetValue() == eStateAttaching)
4086 {
4087 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004088 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 +00004089 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4090 }
4091 else
4092 {
4093 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004094 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004095 Halt();
4096 }
4097 continue;
4098 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004099
4100 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4101
4102 if (internal_state != eStateInvalid)
4103 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004104 if (m_clear_thread_plans_on_stop &&
4105 StateIsStoppedState(internal_state, true))
4106 {
4107 m_clear_thread_plans_on_stop = false;
4108 m_thread_list.DiscardThreadPlans();
4109 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110 HandlePrivateEvent (event_sp);
4111 }
4112
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004113 if (internal_state == eStateInvalid ||
4114 internal_state == eStateExited ||
4115 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004116 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004117 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004118 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 +00004119
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004120 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004121 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004122 }
4123
Caroline Tice20ad3c42010-10-29 21:48:37 +00004124 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004125 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004126 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004127
Ed Maste64fad602013-07-29 20:58:06 +00004128 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004129 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4130 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131 return NULL;
4132}
4133
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004134//------------------------------------------------------------------
4135// Process Event Data
4136//------------------------------------------------------------------
4137
4138Process::ProcessEventData::ProcessEventData () :
4139 EventData (),
4140 m_process_sp (),
4141 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004142 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004143 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004144 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145{
4146}
4147
4148Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4149 EventData (),
4150 m_process_sp (process_sp),
4151 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004152 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004153 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004154 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004155{
4156}
4157
4158Process::ProcessEventData::~ProcessEventData()
4159{
4160}
4161
4162const ConstString &
4163Process::ProcessEventData::GetFlavorString ()
4164{
4165 static ConstString g_flavor ("Process::ProcessEventData");
4166 return g_flavor;
4167}
4168
4169const ConstString &
4170Process::ProcessEventData::GetFlavor () const
4171{
4172 return ProcessEventData::GetFlavorString ();
4173}
4174
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004175void
4176Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4177{
4178 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004179 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4180 // the public event queue, then other times when we're pretending that this is where we stopped at the
4181 // end of expression evaluation. m_update_state is used to distinguish these
4182 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004183 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004184 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004186
Jim Ingham221d51c2013-05-08 00:35:16 +00004187 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004188
4189 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4190 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004191 {
4192 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004193 uint32_t num_threads = curr_thread_list.GetSize();
4194 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004195
Jim Ingham4b536182011-08-09 02:12:22 +00004196 // The actions might change one of the thread's stop_info's opinions about whether we should
4197 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004198
4199 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4200 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4201 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4202 // 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
4203 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004204 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004205 for (idx = 0; idx < num_threads; ++idx)
4206 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4207
Jim Inghamc7078c22012-12-13 22:24:15 +00004208 // Use this to track whether we should continue from here. We will only continue the target running if
4209 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4210 // then it doesn't matter what the other threads say...
4211
4212 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004213
Jim Ingham0ad7e052013-04-25 02:04:59 +00004214 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4215 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4216 // thing to do is, and it's better to let the user decide than continue behind their backs.
4217
4218 bool does_anybody_have_an_opinion = false;
4219
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004220 for (idx = 0; idx < num_threads; ++idx)
4221 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004222 curr_thread_list = m_process_sp->GetThreadList();
4223 if (curr_thread_list.GetSize() != num_threads)
4224 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004225 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004226 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004227 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 +00004228 break;
4229 }
4230
4231 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4232
4233 if (thread_sp->GetIndexID() != thread_index_array[idx])
4234 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004235 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004236 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004237 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004238 idx,
4239 thread_index_array[idx],
4240 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004241 break;
4242 }
4243
Jim Inghamb15bfc72010-10-20 00:39:53 +00004244 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004245 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004246 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004247 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004248 bool this_thread_wants_to_stop;
4249 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004250 {
Jim Ingham0161b492013-02-09 01:29:05 +00004251 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4252 }
4253 else
4254 {
4255 stop_info_sp->PerformAction(event_ptr);
4256 // The stop action might restart the target. If it does, then we want to mark that in the
4257 // event so that whoever is receiving it will know to wait for the running event and reflect
4258 // that state appropriately.
4259 // We also need to stop processing actions, since they aren't expecting the target to be running.
4260
4261 // FIXME: we might have run.
4262 if (stop_info_sp->HasTargetRunSinceMe())
4263 {
4264 SetRestarted (true);
4265 break;
4266 }
4267
4268 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004269 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004270
Jim Inghamc7078c22012-12-13 22:24:15 +00004271 if (still_should_stop == false)
4272 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004273 }
4274 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004275
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004276
Jim Inghama8ca6e22013-05-03 23:04:37 +00004277 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004278 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004279 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004280 {
4281 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004282 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004283 // Use the public resume method here, since this is just
4284 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004285 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004286 }
4287 else
4288 {
4289 // If we didn't restart, run the Stop Hooks here:
4290 // They might also restart the target, so watch for that.
4291 m_process_sp->GetTarget().RunStopHooks();
4292 if (m_process_sp->GetPrivateState() == eStateRunning)
4293 SetRestarted(true);
4294 }
Jim Ingham9575d842011-03-11 03:53:59 +00004295 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004296 }
4297}
4298
4299void
4300Process::ProcessEventData::Dump (Stream *s) const
4301{
4302 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004303 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004304
Greg Clayton8b82f082011-04-12 05:54:46 +00004305 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004306}
4307
4308const Process::ProcessEventData *
4309Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4310{
4311 if (event_ptr)
4312 {
4313 const EventData *event_data = event_ptr->GetData();
4314 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4315 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4316 }
4317 return NULL;
4318}
4319
4320ProcessSP
4321Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4322{
4323 ProcessSP process_sp;
4324 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4325 if (data)
4326 process_sp = data->GetProcessSP();
4327 return process_sp;
4328}
4329
4330StateType
4331Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4332{
4333 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4334 if (data == NULL)
4335 return eStateInvalid;
4336 else
4337 return data->GetState();
4338}
4339
4340bool
4341Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4342{
4343 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4344 if (data == NULL)
4345 return false;
4346 else
4347 return data->GetRestarted();
4348}
4349
4350void
4351Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4352{
4353 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4354 if (data != NULL)
4355 data->SetRestarted(new_value);
4356}
4357
Jim Ingham0161b492013-02-09 01:29:05 +00004358size_t
4359Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4360{
4361 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4362 if (data != NULL)
4363 return data->GetNumRestartedReasons();
4364 else
4365 return 0;
4366}
4367
4368const char *
4369Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4370{
4371 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4372 if (data != NULL)
4373 return data->GetRestartedReasonAtIndex(idx);
4374 else
4375 return NULL;
4376}
4377
4378void
4379Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4380{
4381 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4382 if (data != NULL)
4383 data->AddRestartedReason(reason);
4384}
4385
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004386bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004387Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4388{
4389 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4390 if (data == NULL)
4391 return false;
4392 else
4393 return data->GetInterrupted ();
4394}
4395
4396void
4397Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4398{
4399 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4400 if (data != NULL)
4401 data->SetInterrupted(new_value);
4402}
4403
4404bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004405Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4406{
4407 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4408 if (data)
4409 {
4410 data->SetUpdateStateOnRemoval();
4411 return true;
4412 }
4413 return false;
4414}
4415
Greg Claytond9e416c2012-02-18 05:35:26 +00004416lldb::TargetSP
4417Process::CalculateTarget ()
4418{
4419 return m_target.shared_from_this();
4420}
4421
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004422void
Greg Clayton0603aa92010-10-04 01:05:56 +00004423Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004424{
Greg Claytonc14ee322011-09-22 04:58:26 +00004425 exe_ctx.SetTargetPtr (&m_target);
4426 exe_ctx.SetProcessPtr (this);
4427 exe_ctx.SetThreadPtr(NULL);
4428 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004429}
4430
Greg Claytone996fd32011-03-08 22:40:15 +00004431//uint32_t
4432//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4433//{
4434// return 0;
4435//}
4436//
4437//ArchSpec
4438//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4439//{
4440// return Host::GetArchSpecForExistingProcess (pid);
4441//}
4442//
4443//ArchSpec
4444//Process::GetArchSpecForExistingProcess (const char *process_name)
4445//{
4446// return Host::GetArchSpecForExistingProcess (process_name);
4447//}
4448//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004449void
4450Process::AppendSTDOUT (const char * s, size_t len)
4451{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004452 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004453 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004454 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004455}
4456
4457void
Greg Clayton93e86192011-11-13 04:45:22 +00004458Process::AppendSTDERR (const char * s, size_t len)
4459{
4460 Mutex::Locker locker (m_stdio_communication_mutex);
4461 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004462 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004463}
4464
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004465void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004466Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004467{
4468 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004469 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004470 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4471}
4472
4473size_t
4474Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4475{
4476 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004477 if (m_profile_data.empty())
4478 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004479
4480 std::string &one_profile_data = m_profile_data.front();
4481 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004482 if (bytes_available > 0)
4483 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004484 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004485 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004486 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004487 if (bytes_available > buf_size)
4488 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004489 memcpy(buf, one_profile_data.c_str(), buf_size);
4490 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004491 bytes_available = buf_size;
4492 }
4493 else
4494 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004495 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004496 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004497 }
4498 }
4499 return bytes_available;
4500}
4501
4502
Greg Clayton93e86192011-11-13 04:45:22 +00004503//------------------------------------------------------------------
4504// Process STDIO
4505//------------------------------------------------------------------
4506
4507size_t
4508Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4509{
4510 Mutex::Locker locker(m_stdio_communication_mutex);
4511 size_t bytes_available = m_stdout_data.size();
4512 if (bytes_available > 0)
4513 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004514 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004515 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004516 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004517 if (bytes_available > buf_size)
4518 {
4519 memcpy(buf, m_stdout_data.c_str(), buf_size);
4520 m_stdout_data.erase(0, buf_size);
4521 bytes_available = buf_size;
4522 }
4523 else
4524 {
4525 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4526 m_stdout_data.clear();
4527 }
4528 }
4529 return bytes_available;
4530}
4531
4532
4533size_t
4534Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4535{
4536 Mutex::Locker locker(m_stdio_communication_mutex);
4537 size_t bytes_available = m_stderr_data.size();
4538 if (bytes_available > 0)
4539 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004540 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004541 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004542 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004543 if (bytes_available > buf_size)
4544 {
4545 memcpy(buf, m_stderr_data.c_str(), buf_size);
4546 m_stderr_data.erase(0, buf_size);
4547 bytes_available = buf_size;
4548 }
4549 else
4550 {
4551 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4552 m_stderr_data.clear();
4553 }
4554 }
4555 return bytes_available;
4556}
4557
4558void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004559Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4560{
4561 Process *process = (Process *) baton;
4562 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4563}
4564
4565size_t
4566Process::ProcessInputReaderCallback (void *baton,
4567 InputReader &reader,
4568 lldb::InputReaderAction notification,
4569 const char *bytes,
4570 size_t bytes_len)
4571{
4572 Process *process = (Process *) baton;
4573
4574 switch (notification)
4575 {
4576 case eInputReaderActivate:
4577 break;
4578
4579 case eInputReaderDeactivate:
4580 break;
4581
4582 case eInputReaderReactivate:
4583 break;
4584
Caroline Tice969ed3d2011-05-02 20:41:46 +00004585 case eInputReaderAsynchronousOutputWritten:
4586 break;
4587
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004588 case eInputReaderGotToken:
4589 {
4590 Error error;
4591 process->PutSTDIN (bytes, bytes_len, error);
4592 }
4593 break;
4594
Caroline Ticeefed6132010-11-19 20:47:54 +00004595 case eInputReaderInterrupt:
Jim Inghamfc65a502013-06-19 00:56:17 +00004596 process->SendAsyncInterrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +00004597 break;
4598
4599 case eInputReaderEndOfFile:
4600 process->AppendSTDOUT ("^D", 2);
4601 break;
4602
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004603 case eInputReaderDone:
4604 break;
4605
4606 }
4607
4608 return bytes_len;
4609}
4610
4611void
4612Process::ResetProcessInputReader ()
4613{
4614 m_process_input_reader.reset();
4615}
4616
4617void
Greg Claytonee95ed52011-11-17 22:14:31 +00004618Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004619{
4620 // First set up the Read Thread for reading/handling process I/O
4621
Greg Clayton7b0992d2013-04-18 22:45:39 +00004622 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004623
4624 if (conn_ap.get())
4625 {
4626 m_stdio_communication.SetConnection (conn_ap.release());
4627 if (m_stdio_communication.IsConnected())
4628 {
4629 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4630 m_stdio_communication.StartReadThread();
4631
4632 // Now read thread is set up, set up input reader.
4633
4634 if (!m_process_input_reader.get())
4635 {
4636 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4637 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4638 this,
4639 eInputReaderGranularityByte,
4640 NULL,
4641 NULL,
4642 false));
4643
4644 if (err.Fail())
4645 m_process_input_reader.reset();
4646 }
4647 }
4648 }
4649}
4650
4651void
4652Process::PushProcessInputReader ()
4653{
4654 if (m_process_input_reader && !m_process_input_reader->IsActive())
4655 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4656}
4657
4658void
4659Process::PopProcessInputReader ()
4660{
4661 if (m_process_input_reader && m_process_input_reader->IsActive())
4662 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4663}
4664
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004665// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004666void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004667Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004668{
Greg Clayton67cc0632012-08-22 17:17:09 +00004669// static std::vector<OptionEnumValueElement> g_plugins;
4670//
4671// int i=0;
4672// const char *name;
4673// OptionEnumValueElement option_enum;
4674// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4675// {
4676// if (name)
4677// {
4678// option_enum.value = i;
4679// option_enum.string_value = name;
4680// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4681// g_plugins.push_back (option_enum);
4682// }
4683// ++i;
4684// }
4685// option_enum.value = 0;
4686// option_enum.string_value = NULL;
4687// option_enum.usage = NULL;
4688// g_plugins.push_back (option_enum);
4689//
4690// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4691// {
4692// if (::strcmp (name, "plugin") == 0)
4693// {
4694// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4695// break;
4696// }
4697// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004698//
Greg Clayton6920b522012-08-22 18:39:03 +00004699 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004700}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004701
Greg Clayton99d0faf2010-11-18 23:32:35 +00004702void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004703Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004704{
Greg Clayton6920b522012-08-22 18:39:03 +00004705 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004706}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004707
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004708ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004709Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004710 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004711 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004712 Stream &errors)
4713{
4714 ExecutionResults return_value = eExecutionSetupError;
4715
Jim Ingham77787032011-01-20 02:03:18 +00004716 if (thread_plan_sp.get() == NULL)
4717 {
4718 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004719 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004720 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004721
4722 if (!thread_plan_sp->ValidatePlan(NULL))
4723 {
4724 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4725 return eExecutionSetupError;
4726 }
4727
Greg Claytonc14ee322011-09-22 04:58:26 +00004728 if (exe_ctx.GetProcessPtr() != this)
4729 {
4730 errors.Printf("RunThreadPlan called on wrong process.");
4731 return eExecutionSetupError;
4732 }
4733
4734 Thread *thread = exe_ctx.GetThreadPtr();
4735 if (thread == NULL)
4736 {
4737 errors.Printf("RunThreadPlan called with invalid thread.");
4738 return eExecutionSetupError;
4739 }
Jim Ingham77787032011-01-20 02:03:18 +00004740
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004741 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4742 // For that to be true the plan can't be private - since private plans suppress themselves in the
4743 // GetCompletedPlan call.
4744
4745 bool orig_plan_private = thread_plan_sp->GetPrivate();
4746 thread_plan_sp->SetPrivate(false);
4747
Jim Ingham444586b2011-01-24 06:34:17 +00004748 if (m_private_state.GetValue() != eStateStopped)
4749 {
4750 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004751 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004752 }
4753
Jim Ingham66243842011-08-13 00:56:10 +00004754 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004755 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004756 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004757 if (!selected_frame_sp)
4758 {
4759 thread->SetSelectedFrame(0);
4760 selected_frame_sp = thread->GetSelectedFrame();
4761 if (!selected_frame_sp)
4762 {
4763 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4764 return eExecutionSetupError;
4765 }
4766 }
4767
4768 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004769
4770 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4771 // so we should arrange to reset them as well.
4772
Greg Claytonc14ee322011-09-22 04:58:26 +00004773 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004774
Jim Ingham66243842011-08-13 00:56:10 +00004775 uint32_t selected_tid;
4776 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004777 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004778 {
4779 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004780 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004781 }
4782 else
4783 {
4784 selected_tid = LLDB_INVALID_THREAD_ID;
4785 }
4786
Jim Ingham372787f2012-04-07 00:00:41 +00004787 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004788 lldb::StateType old_state;
4789 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004790
Greg Clayton5160ce52013-03-27 23:08:40 +00004791 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004792 if (Host::GetCurrentThread() == m_private_state_thread)
4793 {
Jim Ingham076b3042012-04-10 01:21:57 +00004794 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4795 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004796 // 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 +00004797 // we are fielding public events here.
4798 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004799 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 +00004800
4801
Jim Ingham372787f2012-04-07 00:00:41 +00004802 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004803
4804 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4805 // returning control here.
4806 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4807 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4808 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4809 // do just what we want.
4810 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4811 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4812 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4813 old_state = m_public_state.GetValue();
4814 m_public_state.SetValueNoLock(eStateStopped);
4815
4816 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004817 StartPrivateStateThread(true);
4818 }
4819
4820 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004821
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004822 if (options.GetDebug())
4823 {
4824 // In this case, we aren't actually going to run, we just want to stop right away.
4825 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4826 // FIXME: To make this prettier we should invent some stop reason for this, but that
4827 // is only cosmetic, and this functionality is only of use to lldb developers who can
4828 // live with not pretty...
4829 thread->Flush();
4830 return eExecutionStoppedForDebug;
4831 }
4832
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004833 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004834
Sean Callanana46ec452012-07-11 21:31:24 +00004835 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004836
Jim Ingham77787032011-01-20 02:03:18 +00004837 {
Sean Callanana46ec452012-07-11 21:31:24 +00004838 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4839 // restored on exit to the function.
4840 //
4841 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4842 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004843
Sean Callanana46ec452012-07-11 21:31:24 +00004844 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004845
Jim Inghamf48169b2010-11-30 02:22:11 +00004846 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004847 {
4848 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004849 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004850 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004851 thread->GetIndexID(),
4852 thread->GetID(),
4853 s.GetData());
4854 }
4855
4856 bool got_event;
4857 lldb::EventSP event_sp;
4858 lldb::StateType stop_state = lldb::eStateInvalid;
4859
4860 TimeValue* timeout_ptr = NULL;
4861 TimeValue real_timeout;
4862
Jim Ingham0161b492013-02-09 01:29:05 +00004863 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 +00004864 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004865 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004866 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00004867
Jim Ingham0161b492013-02-09 01:29:05 +00004868 // This is just for accounting:
4869 uint32_t num_resumes = 0;
4870
4871 TimeValue one_thread_timeout = TimeValue::Now();
4872 TimeValue final_timeout = one_thread_timeout;
4873
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004874 uint32_t timeout_usec = options.GetTimeoutUsec();
4875 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00004876 {
4877 // If we are running all threads then we take half the time to run all threads, bounded by
4878 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004879 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00004880 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4881 else
4882 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00004883 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00004884 if (computed_timeout > default_one_thread_timeout_usec)
4885 computed_timeout = default_one_thread_timeout_usec;
4886 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4887 }
4888 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4889 }
4890 else
4891 {
4892 if (timeout_usec != 0)
4893 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4894 }
4895
Jim Ingham8559a352012-11-26 23:52:18 +00004896 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4897 // So don't call return anywhere within it.
4898
Sean Callanana46ec452012-07-11 21:31:24 +00004899 while (1)
4900 {
4901 // We usually want to resume the process if we get to the top of the loop.
4902 // The only exception is if we get two running events with no intervening
4903 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004904 if (log)
4905 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4906 do_resume,
4907 handle_running_event,
4908 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004909
Jim Ingham184e9812013-01-15 02:47:48 +00004910 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00004911 {
4912 // Do the initial resume and wait for the running event before going further.
4913
Jim Ingham184e9812013-01-15 02:47:48 +00004914 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00004915 {
Jim Ingham0161b492013-02-09 01:29:05 +00004916 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00004917 Error resume_error = PrivateResume ();
4918 if (!resume_error.Success())
4919 {
Jim Ingham0161b492013-02-09 01:29:05 +00004920 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4921 num_resumes,
4922 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00004923 return_value = eExecutionSetupError;
4924 break;
4925 }
Sean Callanana46ec452012-07-11 21:31:24 +00004926 }
Sean Callanana46ec452012-07-11 21:31:24 +00004927
Jim Ingham0161b492013-02-09 01:29:05 +00004928 TimeValue resume_timeout = TimeValue::Now();
4929 resume_timeout.OffsetWithMicroSeconds(500000);
4930
4931 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00004932 if (!got_event)
4933 {
4934 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004935 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4936 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004937
Jim Ingham0161b492013-02-09 01:29:05 +00004938 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004939 return_value = eExecutionSetupError;
4940 break;
4941 }
4942
4943 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00004944
Sean Callanana46ec452012-07-11 21:31:24 +00004945 if (stop_state != eStateRunning)
4946 {
Jim Ingham0161b492013-02-09 01:29:05 +00004947 bool restarted = false;
4948
4949 if (stop_state == eStateStopped)
4950 {
4951 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4952 if (log)
4953 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4954 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4955 num_resumes,
4956 StateAsCString(stop_state),
4957 restarted,
4958 do_resume,
4959 handle_running_event);
4960 }
4961
4962 if (restarted)
4963 {
4964 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4965 // event here. But if I do, the best thing is to Halt and then get out of here.
4966 Halt();
4967 }
4968
Jim Ingham35e1bda2012-10-16 21:41:58 +00004969 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4970 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004971 return_value = eExecutionSetupError;
4972 break;
4973 }
4974
4975 if (log)
4976 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4977 // We need to call the function synchronously, so spin waiting for it to return.
4978 // If we get interrupted while executing, we're going to lose our context, and
4979 // won't be able to gather the result at this point.
4980 // We set the timeout AFTER the resume, since the resume takes some time and we
4981 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00004982 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004983 else
4984 {
Sean Callanana46ec452012-07-11 21:31:24 +00004985 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004986 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004987 }
Jim Ingham0161b492013-02-09 01:29:05 +00004988
4989 if (before_first_timeout)
4990 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004991 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00004992 timeout_ptr = &one_thread_timeout;
4993 else
4994 {
4995 if (timeout_usec == 0)
4996 timeout_ptr = NULL;
4997 else
4998 timeout_ptr = &final_timeout;
4999 }
5000 }
5001 else
5002 {
5003 if (timeout_usec == 0)
5004 timeout_ptr = NULL;
5005 else
5006 timeout_ptr = &final_timeout;
5007 }
5008
5009 do_resume = true;
5010 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005011
Sean Callanana46ec452012-07-11 21:31:24 +00005012 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005013 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005014
Jim Ingham0f16e732011-02-08 05:20:59 +00005015 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005016 {
Sean Callanana46ec452012-07-11 21:31:24 +00005017 if (timeout_ptr)
5018 {
Matt Kopec676a4872013-02-21 23:55:31 +00005019 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005020 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5021 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005022 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005023 else
Sean Callanana46ec452012-07-11 21:31:24 +00005024 {
5025 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5026 }
5027 }
5028
5029 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5030
5031 if (got_event)
5032 {
5033 if (event_sp.get())
5034 {
5035 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005036 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005037 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005038 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005039 return_value = eExecutionInterrupted;
5040 errors.Printf ("Execution halted by user interrupt.");
5041 if (log)
5042 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005043 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005044 }
5045 else
5046 {
5047 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5048 if (log)
5049 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5050
5051 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005052 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005053 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005054 {
Jim Ingham0161b492013-02-09 01:29:05 +00005055 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005056 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5057 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005058 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005059 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005060 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005061 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5062 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005063 }
5064 else
5065 {
Jim Ingham0161b492013-02-09 01:29:05 +00005066 // If we were restarted, we just need to go back up to fetch another event.
5067 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005068 {
5069 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005070 {
5071 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5072 }
5073 keep_going = true;
5074 do_resume = false;
5075 handle_running_event = true;
5076
Jim Inghamcfc09352012-07-27 23:57:19 +00005077 }
5078 else
5079 {
Jim Ingham0161b492013-02-09 01:29:05 +00005080
5081 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5082 StopReason stop_reason = eStopReasonInvalid;
5083 if (stop_info_sp)
5084 stop_reason = stop_info_sp->GetStopReason();
5085
5086
5087 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5088 // it is OUR plan that is complete?
5089 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005090 {
5091 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005092 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5093 // Now mark this plan as private so it doesn't get reported as the stop reason
5094 // after this point.
5095 if (thread_plan_sp)
5096 thread_plan_sp->SetPrivate (orig_plan_private);
5097 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005098 }
5099 else
5100 {
Jim Ingham0161b492013-02-09 01:29:05 +00005101 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005102 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005103 {
5104 if (log)
5105 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005106 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005107 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005108 {
5109 event_to_broadcast_sp = event_sp;
5110 }
Jim Ingham0161b492013-02-09 01:29:05 +00005111 }
Jim Ingham184e9812013-01-15 02:47:48 +00005112 else
Jim Ingham0161b492013-02-09 01:29:05 +00005113 {
5114 if (log)
5115 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005116 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005117 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005118 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005119 }
Jim Ingham184e9812013-01-15 02:47:48 +00005120 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005121 }
Sean Callanana46ec452012-07-11 21:31:24 +00005122 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005123 }
5124 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005125
Jim Inghamcfc09352012-07-27 23:57:19 +00005126 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005127 // This shouldn't really happen, but sometimes we do get two running events without an
5128 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005129 do_resume = false;
5130 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005131 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005132 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005133
Jim Inghamcfc09352012-07-27 23:57:19 +00005134 default:
5135 if (log)
5136 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5137
5138 if (stop_state == eStateExited)
5139 event_to_broadcast_sp = event_sp;
5140
Sean Callananbf154da2012-08-08 17:35:10 +00005141 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005142 return_value = eExecutionInterrupted;
5143 break;
5144 }
Sean Callanana46ec452012-07-11 21:31:24 +00005145 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005146
Sean Callanana46ec452012-07-11 21:31:24 +00005147 if (keep_going)
5148 continue;
5149 else
5150 break;
5151 }
5152 else
5153 {
5154 if (log)
5155 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5156 return_value = eExecutionInterrupted;
5157 break;
5158 }
5159 }
5160 else
5161 {
5162 // If we didn't get an event that means we've timed out...
5163 // We will interrupt the process here. Depending on what we were asked to do we will
5164 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005165
5166 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005167 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005168 {
Jim Ingham0161b492013-02-09 01:29:05 +00005169 uint64_t remaining_time = final_timeout - TimeValue::Now();
5170 if (before_first_timeout)
5171 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005172 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005173 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005174 else
5175 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005176 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005177 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005178 }
5179 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005180 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005181 "abandoning execution.",
5182 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005183 }
5184
Jim Ingham0161b492013-02-09 01:29:05 +00005185 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5186 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5187 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5188 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5189 // stopped event. That's what this while loop does.
5190
5191 bool back_to_top = true;
5192 uint32_t try_halt_again = 0;
5193 bool do_halt = true;
5194 const uint32_t num_retries = 5;
5195 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005196 {
Jim Ingham0161b492013-02-09 01:29:05 +00005197 Error halt_error;
5198 if (do_halt)
5199 {
5200 if (log)
5201 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5202 halt_error = Halt();
5203 }
5204 if (halt_error.Success())
5205 {
5206 if (log)
5207 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5208
5209 real_timeout = TimeValue::Now();
5210 real_timeout.OffsetWithMicroSeconds(500000);
5211
5212 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005213
Jim Ingham0161b492013-02-09 01:29:05 +00005214 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005215 {
Jim Ingham0161b492013-02-09 01:29:05 +00005216 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5217 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005218 {
Jim Ingham0161b492013-02-09 01:29:05 +00005219 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5220 if (stop_state == lldb::eStateStopped
5221 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5222 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005223 }
5224
Jim Ingham0161b492013-02-09 01:29:05 +00005225 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005226 {
Jim Ingham0161b492013-02-09 01:29:05 +00005227 // Between the time we initiated the Halt and the time we delivered it, the process could have
5228 // already finished its job. Check that here:
5229
5230 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5231 {
5232 if (log)
5233 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5234 "Exiting wait loop.");
5235 return_value = eExecutionCompleted;
5236 back_to_top = false;
5237 break;
5238 }
5239
5240 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5241 {
5242 if (log)
5243 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5244 "Exiting wait loop.");
5245 try_halt_again++;
5246 do_halt = false;
5247 continue;
5248 }
Sean Callanana46ec452012-07-11 21:31:24 +00005249
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005250 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005251 {
5252 if (log)
5253 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5254 return_value = eExecutionInterrupted;
5255 back_to_top = false;
5256 break;
5257 }
5258
5259 if (before_first_timeout)
5260 {
5261 // Set all the other threads to run, and return to the top of the loop, which will continue;
5262 before_first_timeout = false;
5263 thread_plan_sp->SetStopOthers (false);
5264 if (log)
5265 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005266
Jim Ingham0161b492013-02-09 01:29:05 +00005267 back_to_top = true;
5268 break;
5269 }
5270 else
5271 {
5272 // Running all threads failed, so return Interrupted.
5273 if (log)
5274 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5275 return_value = eExecutionInterrupted;
5276 back_to_top = false;
5277 break;
5278 }
Sean Callanana46ec452012-07-11 21:31:24 +00005279 }
5280 }
5281 else
Jim Ingham0161b492013-02-09 01:29:05 +00005282 { if (log)
5283 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5284 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005285 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005286 back_to_top = false;
5287 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005288 }
5289 }
Jim Ingham0161b492013-02-09 01:29:05 +00005290 else
5291 {
5292 try_halt_again++;
5293 continue;
5294 }
Sean Callanana46ec452012-07-11 21:31:24 +00005295 }
Jim Ingham0161b492013-02-09 01:29:05 +00005296
5297 if (!back_to_top || try_halt_again > num_retries)
5298 break;
5299 else
5300 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005301 }
Sean Callanana46ec452012-07-11 21:31:24 +00005302 } // END WAIT LOOP
5303
5304 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5305 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5306 {
5307 StopPrivateStateThread();
5308 Error error;
5309 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005310 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005311 {
5312 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5313 }
5314 m_public_state.SetValueNoLock(old_state);
5315
5316 }
5317
Jim Ingham184e9812013-01-15 02:47:48 +00005318 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5319 // could happen:
5320 // 1) The execution successfully completed
5321 // 2) We hit a breakpoint, and ignore_breakpoints was true
5322 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005323 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5324 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005325
Jim Ingham184e9812013-01-15 02:47:48 +00005326 if (return_value == eExecutionCompleted
5327 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005328 {
5329 thread_plan_sp->RestoreThreadState();
5330 }
Sean Callanana46ec452012-07-11 21:31:24 +00005331
5332 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005333 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005334 {
5335 if (log)
5336 {
5337 StreamString s;
5338 if (event_sp)
5339 event_sp->Dump (&s);
5340 else
5341 {
5342 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5343 }
5344
5345 StreamString ts;
5346
5347 const char *event_explanation = NULL;
5348
5349 do
5350 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005351 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005352 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005353 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005354 break;
5355 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005356 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005357 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005358 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005359 break;
5360 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005361 else
Sean Callanana46ec452012-07-11 21:31:24 +00005362 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005363 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5364
5365 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005366 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005367 event_explanation = "<no event data>";
5368 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005369 }
5370
Jim Inghamcfc09352012-07-27 23:57:19 +00005371 Process *process = event_data->GetProcessSP().get();
5372
5373 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005374 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005375 event_explanation = "<no process>";
5376 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005377 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005378
5379 ThreadList &thread_list = process->GetThreadList();
5380
5381 uint32_t num_threads = thread_list.GetSize();
5382 uint32_t thread_index;
5383
5384 ts.Printf("<%u threads> ", num_threads);
5385
5386 for (thread_index = 0;
5387 thread_index < num_threads;
5388 ++thread_index)
5389 {
5390 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5391
5392 if (!thread)
5393 {
5394 ts.Printf("<?> ");
5395 continue;
5396 }
5397
Daniel Malead01b2952012-11-29 21:49:15 +00005398 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005399 RegisterContext *register_context = thread->GetRegisterContext().get();
5400
5401 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005402 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005403 else
5404 ts.Printf("[ip unknown] ");
5405
5406 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5407 if (stop_info_sp)
5408 {
5409 const char *stop_desc = stop_info_sp->GetDescription();
5410 if (stop_desc)
5411 ts.PutCString (stop_desc);
5412 }
5413 ts.Printf(">");
5414 }
5415
5416 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005417 }
Sean Callanana46ec452012-07-11 21:31:24 +00005418 } while (0);
5419
Jim Inghamcfc09352012-07-27 23:57:19 +00005420 if (event_explanation)
5421 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005422 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005423 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5424 }
5425
Jim Inghame4483cf2013-09-27 01:13:01 +00005426 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005427 {
5428 if (log)
5429 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5430 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5431 thread_plan_sp->SetPrivate (orig_plan_private);
5432 }
5433 else
5434 {
5435 if (log)
5436 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005437 }
5438 }
5439 else if (return_value == eExecutionSetupError)
5440 {
5441 if (log)
5442 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005443
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005444 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005445 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005446 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005447 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005448 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005449 }
5450 else
5451 {
Sean Callanana46ec452012-07-11 21:31:24 +00005452 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005453 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005454 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005455 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5456 return_value = eExecutionCompleted;
5457 }
5458 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5459 {
5460 if (log)
5461 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5462 return_value = eExecutionDiscarded;
5463 }
5464 else
5465 {
5466 if (log)
5467 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005468 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005469 {
5470 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005471 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005472 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5473 thread_plan_sp->SetPrivate (orig_plan_private);
5474 }
5475 }
5476 }
5477
5478 // Thread we ran the function in may have gone away because we ran the target
5479 // Check that it's still there, and if it is put it back in the context. Also restore the
5480 // frame in the context if it is still present.
5481 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5482 if (thread)
5483 {
5484 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5485 }
5486
5487 // Also restore the current process'es selected frame & thread, since this function calling may
5488 // be done behind the user's back.
5489
5490 if (selected_tid != LLDB_INVALID_THREAD_ID)
5491 {
5492 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5493 {
5494 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005495 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005496 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005497 if (old_frame_sp)
5498 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005499 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005500 }
5501 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005502
Sean Callanana46ec452012-07-11 21:31:24 +00005503 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005504
Sean Callanana46ec452012-07-11 21:31:24 +00005505 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005506 {
Sean Callanana46ec452012-07-11 21:31:24 +00005507 if (log)
5508 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5509 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005510 }
5511
5512 return return_value;
5513}
5514
5515const char *
5516Process::ExecutionResultAsCString (ExecutionResults result)
5517{
5518 const char *result_name;
5519
5520 switch (result)
5521 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005522 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005523 result_name = "eExecutionCompleted";
5524 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005525 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005526 result_name = "eExecutionDiscarded";
5527 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005528 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005529 result_name = "eExecutionInterrupted";
5530 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005531 case eExecutionHitBreakpoint:
5532 result_name = "eExecutionHitBreakpoint";
5533 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005534 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005535 result_name = "eExecutionSetupError";
5536 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005537 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005538 result_name = "eExecutionTimedOut";
5539 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005540 case eExecutionStoppedForDebug:
5541 result_name = "eExecutionStoppedForDebug";
5542 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005543 }
5544 return result_name;
5545}
5546
Greg Clayton7260f622011-04-18 08:33:37 +00005547void
5548Process::GetStatus (Stream &strm)
5549{
5550 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005551 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005552 {
5553 if (state == eStateExited)
5554 {
5555 int exit_status = GetExitStatus();
5556 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005557 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005558 GetID(),
5559 exit_status,
5560 exit_status,
5561 exit_description ? exit_description : "");
5562 }
5563 else
5564 {
5565 if (state == eStateConnected)
5566 strm.Printf ("Connected to remote target.\n");
5567 else
Daniel Malead01b2952012-11-29 21:49:15 +00005568 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005569 }
5570 }
5571 else
5572 {
Daniel Malead01b2952012-11-29 21:49:15 +00005573 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005574 }
5575}
5576
5577size_t
5578Process::GetThreadStatus (Stream &strm,
5579 bool only_threads_with_stop_reason,
5580 uint32_t start_frame,
5581 uint32_t num_frames,
5582 uint32_t num_frames_with_source)
5583{
5584 size_t num_thread_infos_dumped = 0;
5585
Jim Ingham41f2b942012-09-10 20:50:15 +00005586 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005587 const size_t num_threads = GetThreadList().GetSize();
5588 for (uint32_t i = 0; i < num_threads; i++)
5589 {
5590 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5591 if (thread)
5592 {
5593 if (only_threads_with_stop_reason)
5594 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005595 StopInfoSP stop_info_sp = thread->GetStopInfo();
5596 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005597 continue;
5598 }
5599 thread->GetStatus (strm,
5600 start_frame,
5601 num_frames,
5602 num_frames_with_source);
5603 ++num_thread_infos_dumped;
5604 }
5605 }
5606 return num_thread_infos_dumped;
5607}
5608
Greg Claytona9f40ad2012-02-22 04:37:26 +00005609void
5610Process::AddInvalidMemoryRegion (const LoadRange &region)
5611{
5612 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5613}
5614
5615bool
5616Process::RemoveInvalidMemoryRange (const LoadRange &region)
5617{
5618 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5619}
5620
Jim Ingham372787f2012-04-07 00:00:41 +00005621void
5622Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5623{
5624 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5625}
5626
5627bool
5628Process::RunPreResumeActions ()
5629{
5630 bool result = true;
5631 while (!m_pre_resume_actions.empty())
5632 {
5633 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5634 m_pre_resume_actions.pop_back();
5635 bool this_result = action.callback (action.baton);
5636 if (result == true) result = this_result;
5637 }
5638 return result;
5639}
5640
5641void
5642Process::ClearPreResumeActions ()
5643{
5644 m_pre_resume_actions.clear();
5645}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005646
Greg Claytonfa559e52012-05-18 02:38:05 +00005647void
5648Process::Flush ()
5649{
5650 m_thread_list.Flush();
5651}
Greg Clayton90ba8112012-12-05 00:16:59 +00005652
5653void
5654Process::DidExec ()
5655{
5656 Target &target = GetTarget();
5657 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005658 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005659 m_dynamic_checkers_ap.reset();
5660 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005661 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005662 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005663 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005664 m_image_tokens.clear();
5665 m_allocated_memory_cache.Clear();
5666 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005667 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005668 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005669 DoDidExec();
5670 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005671 // Flush the process (threads and all stack frames) after running CompleteAttach()
5672 // in case the dynamic loader loaded things in new locations.
5673 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005674
5675 // After we figure out what was loaded/unloaded in CompleteAttach,
5676 // we need to let the target know so it can do any cleanup it needs to.
5677 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005678}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005679