blob: 8b1aba634b776b0182e45f7df30d9670351389c3 [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),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001020 m_queue_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001021 m_thread_id_to_index_id_map (),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001022 m_queue_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023 m_exit_status (-1),
1024 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001025 m_thread_mutex (Mutex::eMutexTypeRecursive),
1026 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +00001028 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +00001029 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001030 m_queue_list (this),
1031 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001032 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001033 m_image_tokens (),
1034 m_listener (listener),
1035 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001036 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001037 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001038 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001039 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001040 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001041 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001042 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001043 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001044 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1045 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001046 m_memory_cache (*this),
1047 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001048 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001049 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001050 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001051 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001052 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001053 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001054 m_clear_thread_plans_on_stop (false),
Jim Ingham0161b492013-02-09 01:29:05 +00001055 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001056 m_destroy_in_process (false),
1057 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001059 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001060
Greg Clayton5160ce52013-03-27 23:08:40 +00001061 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 if (log)
1063 log->Printf ("%p Process::Process()", this);
1064
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001065 SetEventName (eBroadcastBitStateChanged, "state-changed");
1066 SetEventName (eBroadcastBitInterrupt, "interrupt");
1067 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1068 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001069 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001070
Greg Clayton35a4cc52012-10-29 20:52:08 +00001071 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1072 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1073 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075 listener.StartListeningForEvents (this,
1076 eBroadcastBitStateChanged |
1077 eBroadcastBitInterrupt |
1078 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001079 eBroadcastBitSTDERR |
1080 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081
1082 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001083 eBroadcastBitStateChanged |
1084 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085
1086 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1087 eBroadcastInternalStateControlStop |
1088 eBroadcastInternalStateControlPause |
1089 eBroadcastInternalStateControlResume);
1090}
1091
1092//----------------------------------------------------------------------
1093// Destructor
1094//----------------------------------------------------------------------
1095Process::~Process()
1096{
Greg Clayton5160ce52013-03-27 23:08:40 +00001097 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 if (log)
1099 log->Printf ("%p Process::~Process()", this);
1100 StopPrivateStateThread();
1101}
1102
Greg Clayton67cc0632012-08-22 17:17:09 +00001103const ProcessPropertiesSP &
1104Process::GetGlobalProperties()
1105{
1106 static ProcessPropertiesSP g_settings_sp;
1107 if (!g_settings_sp)
1108 g_settings_sp.reset (new ProcessProperties (true));
1109 return g_settings_sp;
1110}
1111
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112void
1113Process::Finalize()
1114{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001115 switch (GetPrivateState())
1116 {
1117 case eStateConnected:
1118 case eStateAttaching:
1119 case eStateLaunching:
1120 case eStateStopped:
1121 case eStateRunning:
1122 case eStateStepping:
1123 case eStateCrashed:
1124 case eStateSuspended:
1125 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001126 {
1127 // FIXME: This will have to be a process setting:
1128 bool keep_stopped = false;
1129 Detach(keep_stopped);
1130 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001131 else
1132 Destroy();
1133 break;
1134
1135 case eStateInvalid:
1136 case eStateUnloaded:
1137 case eStateDetached:
1138 case eStateExited:
1139 break;
1140 }
1141
Greg Clayton1ed54f52011-10-01 00:45:15 +00001142 // Clear our broadcaster before we proceed with destroying
1143 Broadcaster::Clear();
1144
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145 // Do any cleanup needed prior to being destructed... Subclasses
1146 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001147
1148 // We need to destroy the loader before the derived Process class gets destroyed
1149 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001150 m_dynamic_checkers_ap.reset();
1151 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001152 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00001153 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001154 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001155 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001156 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +00001157 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001158 m_queue_list.Clear();
1159 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +00001160 std::vector<Notifications> empty_notifications;
1161 m_notifications.swap(empty_notifications);
1162 m_image_tokens.clear();
1163 m_memory_cache.Clear();
1164 m_allocated_memory_cache.Clear();
1165 m_language_runtimes.clear();
1166 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001167//#ifdef LLDB_CONFIGURATION_DEBUG
1168// StreamFile s(stdout, false);
1169// EventSP event_sp;
1170// while (m_private_state_listener.GetNextEvent(event_sp))
1171// {
1172// event_sp->Dump (&s);
1173// s.EOL();
1174// }
1175//#endif
1176 // We have to be very careful here as the m_private_state_listener might
1177 // contain events that have ProcessSP values in them which can keep this
1178 // process around forever. These events need to be cleared out.
1179 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001180 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1181 m_public_run_lock.SetStopped();
1182 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1183 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001184 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185}
1186
1187void
1188Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1189{
1190 m_notifications.push_back(callbacks);
1191 if (callbacks.initialize != NULL)
1192 callbacks.initialize (callbacks.baton, this);
1193}
1194
1195bool
1196Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1197{
1198 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1199 for (pos = m_notifications.begin(); pos != end; ++pos)
1200 {
1201 if (pos->baton == callbacks.baton &&
1202 pos->initialize == callbacks.initialize &&
1203 pos->process_state_changed == callbacks.process_state_changed)
1204 {
1205 m_notifications.erase(pos);
1206 return true;
1207 }
1208 }
1209 return false;
1210}
1211
1212void
1213Process::SynchronouslyNotifyStateChanged (StateType state)
1214{
1215 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1216 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1217 {
1218 if (notification_pos->process_state_changed)
1219 notification_pos->process_state_changed (notification_pos->baton, this, state);
1220 }
1221}
1222
1223// FIXME: We need to do some work on events before the general Listener sees them.
1224// For instance if we are continuing from a breakpoint, we need to ensure that we do
1225// the little "insert real insn, step & stop" trick. But we can't do that when the
1226// event is delivered by the broadcaster - since that is done on the thread that is
1227// waiting for new events, so if we needed more than one event for our handling, we would
1228// stall. So instead we do it when we fetch the event off of the queue.
1229//
1230
1231StateType
1232Process::GetNextEvent (EventSP &event_sp)
1233{
1234 StateType state = eStateInvalid;
1235
1236 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1237 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1238
1239 return state;
1240}
1241
1242
1243StateType
Daniel Malea9e9919f2013-10-09 16:56:28 +00001244Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001245{
Jim Ingham4b536182011-08-09 02:12:22 +00001246 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1247 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1248 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001249 if (event_sp_ptr)
1250 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001251 StateType state = GetState();
1252 // If we are exited or detached, we won't ever get back to any
1253 // other valid state...
1254 if (state == eStateDetached || state == eStateExited)
1255 return state;
1256
Daniel Malea9e9919f2013-10-09 16:56:28 +00001257 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1258 if (log)
1259 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1260
1261 if (!wait_always &&
1262 StateIsStoppedState(state, true) &&
1263 StateIsStoppedState(GetPrivateState(), true)) {
1264 if (log)
1265 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1266 __FUNCTION__);
1267 return state;
1268 }
1269
Jim Ingham4b536182011-08-09 02:12:22 +00001270 while (state != eStateInvalid)
1271 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001272 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001273 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001274 if (event_sp_ptr && event_sp)
1275 *event_sp_ptr = event_sp;
1276
Jim Ingham4b536182011-08-09 02:12:22 +00001277 switch (state)
1278 {
1279 case eStateCrashed:
1280 case eStateDetached:
1281 case eStateExited:
1282 case eStateUnloaded:
1283 return state;
1284 case eStateStopped:
1285 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1286 continue;
1287 else
1288 return state;
1289 default:
1290 continue;
1291 }
1292 }
1293 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001294}
1295
1296
1297StateType
1298Process::WaitForState
1299(
1300 const TimeValue *timeout,
1301 const StateType *match_states, const uint32_t num_match_states
1302)
1303{
1304 EventSP event_sp;
1305 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001306 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 while (state != eStateInvalid)
1308 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001309 // If we are exited or detached, we won't ever get back to any
1310 // other valid state...
1311 if (state == eStateDetached || state == eStateExited)
1312 return state;
1313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314 state = WaitForStateChangedEvents (timeout, event_sp);
1315
1316 for (i=0; i<num_match_states; ++i)
1317 {
1318 if (match_states[i] == state)
1319 return state;
1320 }
1321 }
1322 return state;
1323}
1324
Jim Ingham30f9b212010-10-11 23:53:14 +00001325bool
1326Process::HijackProcessEvents (Listener *listener)
1327{
1328 if (listener != NULL)
1329 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001330 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001331 }
1332 else
1333 return false;
1334}
1335
1336void
1337Process::RestoreProcessEvents ()
1338{
1339 RestoreBroadcaster();
1340}
1341
Jim Ingham0f16e732011-02-08 05:20:59 +00001342bool
1343Process::HijackPrivateProcessEvents (Listener *listener)
1344{
1345 if (listener != NULL)
1346 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001347 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001348 }
1349 else
1350 return false;
1351}
1352
1353void
1354Process::RestorePrivateProcessEvents ()
1355{
1356 m_private_state_broadcaster.RestoreBroadcaster();
1357}
1358
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001359StateType
1360Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1361{
Greg Clayton5160ce52013-03-27 23:08:40 +00001362 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001363
1364 if (log)
1365 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1366
1367 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001368 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1369 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001370 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001371 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001372 {
1373 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1374 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1375 else if (log)
1376 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1377 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378
1379 if (log)
1380 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1381 __FUNCTION__,
1382 timeout,
1383 StateAsCString(state));
1384 return state;
1385}
1386
1387Event *
1388Process::PeekAtStateChangedEvents ()
1389{
Greg Clayton5160ce52013-03-27 23:08:40 +00001390 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391
1392 if (log)
1393 log->Printf ("Process::%s...", __FUNCTION__);
1394
1395 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001396 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1397 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398 if (log)
1399 {
1400 if (event_ptr)
1401 {
1402 log->Printf ("Process::%s (event_ptr) => %s",
1403 __FUNCTION__,
1404 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1405 }
1406 else
1407 {
1408 log->Printf ("Process::%s no events found",
1409 __FUNCTION__);
1410 }
1411 }
1412 return event_ptr;
1413}
1414
1415StateType
1416Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1417{
Greg Clayton5160ce52013-03-27 23:08:40 +00001418 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419
1420 if (log)
1421 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1422
1423 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001424 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1425 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001426 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001427 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001428 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1429 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430
1431 // This is a bit of a hack, but when we wait here we could very well return
1432 // to the command-line, and that could disable the log, which would render the
1433 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001435 {
1436 if (state == eStateInvalid)
1437 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1438 else
1439 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1440 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441 return state;
1442}
1443
1444bool
1445Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1446{
Greg Clayton5160ce52013-03-27 23:08:40 +00001447 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448
1449 if (log)
1450 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1451
1452 if (control_only)
1453 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1454 else
1455 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1456}
1457
1458bool
1459Process::IsRunning () const
1460{
1461 return StateIsRunningState (m_public_state.GetValue());
1462}
1463
1464int
1465Process::GetExitStatus ()
1466{
1467 if (m_public_state.GetValue() == eStateExited)
1468 return m_exit_status;
1469 return -1;
1470}
1471
Greg Clayton85851dd2010-12-04 00:10:17 +00001472
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001473const char *
1474Process::GetExitDescription ()
1475{
1476 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1477 return m_exit_string.c_str();
1478 return NULL;
1479}
1480
Greg Clayton6779606a2011-01-22 23:43:18 +00001481bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001482Process::SetExitStatus (int status, const char *cstr)
1483{
Greg Clayton5160ce52013-03-27 23:08:40 +00001484 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001485 if (log)
1486 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1487 status, status,
1488 cstr ? "\"" : "",
1489 cstr ? cstr : "NULL",
1490 cstr ? "\"" : "");
1491
Greg Clayton6779606a2011-01-22 23:43:18 +00001492 // We were already in the exited state
1493 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001494 {
Greg Clayton385d6032011-01-26 23:47:29 +00001495 if (log)
1496 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001497 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001498 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001499
1500 m_exit_status = status;
1501 if (cstr)
1502 m_exit_string = cstr;
1503 else
1504 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505
Greg Clayton6779606a2011-01-22 23:43:18 +00001506 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001507
Greg Clayton6779606a2011-01-22 23:43:18 +00001508 SetPrivateState (eStateExited);
1509 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001510}
1511
1512// This static callback can be used to watch for local child processes on
1513// the current host. The the child process exits, the process will be
1514// found in the global target list (we want to be completely sure that the
1515// lldb_private::Process doesn't go away before we can deliver the signal.
1516bool
Greg Claytone4e45922011-11-16 05:37:56 +00001517Process::SetProcessExitStatus (void *callback_baton,
1518 lldb::pid_t pid,
1519 bool exited,
1520 int signo, // Zero for no signal
1521 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001522)
1523{
Greg Clayton5160ce52013-03-27 23:08:40 +00001524 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001525 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001526 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001527 callback_baton,
1528 pid,
1529 exited,
1530 signo,
1531 exit_status);
1532
1533 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001534 {
Greg Clayton66111032010-06-23 01:19:29 +00001535 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536 if (target_sp)
1537 {
1538 ProcessSP process_sp (target_sp->GetProcessSP());
1539 if (process_sp)
1540 {
1541 const char *signal_cstr = NULL;
1542 if (signo)
1543 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1544
1545 process_sp->SetExitStatus (exit_status, signal_cstr);
1546 }
1547 }
1548 return true;
1549 }
1550 return false;
1551}
1552
1553
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001554void
1555Process::UpdateThreadListIfNeeded ()
1556{
1557 const uint32_t stop_id = GetStopID();
1558 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1559 {
Greg Clayton2637f822011-11-17 01:23:07 +00001560 const StateType state = GetPrivateState();
1561 if (StateIsStoppedState (state, true))
1562 {
1563 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001564 // m_thread_list does have its own mutex, but we need to
1565 // hold onto the mutex between the call to UpdateThreadList(...)
1566 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001567 ThreadList &old_thread_list = m_thread_list;
1568 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001569 ThreadList new_thread_list(this);
1570 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001571 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001572 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001573 {
Jim Ingham09437922013-03-01 20:04:25 +00001574 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1575 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1576 // shutting us down, causing a deadlock.
1577 if (!m_destroy_in_process)
1578 {
1579 OperatingSystem *os = GetOperatingSystem ();
1580 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001581 {
1582 // Clear any old backing threads where memory threads might have been
1583 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001584 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001585 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001586 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001587
1588 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001589 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1590 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1591 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 +00001592 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001593 else
1594 {
1595 // No OS plug-in, the new thread list is the same as the real thread list
1596 new_thread_list = real_thread_list;
1597 }
Jim Ingham09437922013-03-01 20:04:25 +00001598 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001599
1600 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001601 m_thread_list.Update (new_thread_list);
1602 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001603
Jason Molenda4ff13262013-11-20 00:31:38 +00001604 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1605 {
1606 // Clear any extended threads that we may have accumulated previously
1607 m_extended_thread_list.Clear();
1608 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001609
1610 m_queue_list.Clear();
1611 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001612 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001613 }
Greg Clayton2637f822011-11-17 01:23:07 +00001614 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001615 }
1616}
1617
Jason Molenda5e8dce42013-12-13 00:29:16 +00001618void
1619Process::UpdateQueueListIfNeeded ()
1620{
1621 if (m_system_runtime_ap.get())
1622 {
1623 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1624 {
1625 const StateType state = GetPrivateState();
1626 if (StateIsStoppedState (state, true))
1627 {
1628 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1629 m_queue_list_stop_id = GetLastNaturalStopID();
1630 }
1631 }
1632 }
1633}
1634
Greg Claytona4d87472013-01-18 23:41:08 +00001635ThreadSP
1636Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1637{
1638 OperatingSystem *os = GetOperatingSystem ();
1639 if (os)
1640 return os->CreateThread(tid, context);
1641 return ThreadSP();
1642}
1643
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001644uint32_t
1645Process::GetNextThreadIndexID (uint64_t thread_id)
1646{
1647 return AssignIndexIDToThread(thread_id);
1648}
1649
1650bool
1651Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1652{
1653 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1654 if (iterator == m_thread_id_to_index_id_map.end())
1655 {
1656 return false;
1657 }
1658 else
1659 {
1660 return true;
1661 }
1662}
1663
1664uint32_t
1665Process::AssignIndexIDToThread(uint64_t thread_id)
1666{
1667 uint32_t result = 0;
1668 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1669 if (iterator == m_thread_id_to_index_id_map.end())
1670 {
1671 result = ++m_thread_index_id;
1672 m_thread_id_to_index_id_map[thread_id] = result;
1673 }
1674 else
1675 {
1676 result = iterator->second;
1677 }
1678
1679 return result;
1680}
1681
Jason Molenda5e8dce42013-12-13 00:29:16 +00001682bool
1683Process::HasAssignedIndexIDToQueue(queue_id_t queue_id)
1684{
1685 std::map<uint64_t, uint32_t>::iterator iterator = m_queue_id_to_index_id_map.find(queue_id);
1686 if (iterator == m_queue_id_to_index_id_map.end())
1687 {
1688 return false;
1689 }
1690 else
1691 {
1692 return true;
1693 }
1694}
1695
1696uint32_t
1697Process::AssignIndexIDToQueue(queue_id_t queue_id)
1698{
1699 uint32_t result = 0;
1700 std::map<uint64_t, uint32_t>::iterator iterator = m_queue_id_to_index_id_map.find(queue_id);
1701 if (iterator == m_queue_id_to_index_id_map.end())
1702 {
1703 result = ++m_queue_index_id;
1704 m_queue_id_to_index_id_map[queue_id] = result;
1705 }
1706 else
1707 {
1708 result = iterator->second;
1709 }
1710
1711 return result;
1712}
1713
1714
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715StateType
1716Process::GetState()
1717{
1718 // If any other threads access this we will need a mutex for it
1719 return m_public_state.GetValue ();
1720}
1721
1722void
Jim Ingham221d51c2013-05-08 00:35:16 +00001723Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001724{
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 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001727 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001728 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001730
1731 // On the transition from Run to Stopped, we unlock the writer end of the
1732 // run lock. The lock gets locked in Resume, which is the public API
1733 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001734 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1735 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001736 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001737 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001738 if (log)
1739 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001740 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001741 }
1742 else
1743 {
1744 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1745 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001746 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001747 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001748 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001749 {
1750 if (log)
1751 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001752 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001753 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001754 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001755 }
1756 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001757}
1758
Jim Ingham3b8285d2012-04-19 01:40:33 +00001759Error
1760Process::Resume ()
1761{
Greg Clayton5160ce52013-03-27 23:08:40 +00001762 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001763 if (log)
1764 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001765 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001766 {
1767 Error error("Resume request failed - process still running.");
1768 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001769 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001770 return error;
1771 }
1772 return PrivateResume();
1773}
1774
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775StateType
1776Process::GetPrivateState ()
1777{
1778 return m_private_state.GetValue();
1779}
1780
1781void
1782Process::SetPrivateState (StateType new_state)
1783{
Greg Clayton5160ce52013-03-27 23:08:40 +00001784 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001785 bool state_changed = false;
1786
1787 if (log)
1788 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1789
Andrew Kaylor29d65742013-05-10 17:19:04 +00001790 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001791 Mutex::Locker locker(m_private_state.GetMutex());
1792
1793 const StateType old_state = m_private_state.GetValueNoLock ();
1794 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001795
Greg Claytonaa49c832013-05-03 22:25:56 +00001796 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1797 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1798 if (old_state_is_stopped != new_state_is_stopped)
1799 {
1800 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001801 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001802 else
Ed Maste64fad602013-07-29 20:58:06 +00001803 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001804 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001805
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 if (state_changed)
1807 {
1808 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001809 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001810 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001811 // Note, this currently assumes that all threads in the list
1812 // stop when the process stops. In the future we will want to
1813 // support a debugging model where some threads continue to run
1814 // while others are stopped. When that happens we will either need
1815 // a way for the thread list to identify which threads are stopping
1816 // or create a special thread list containing only threads which
1817 // actually stopped.
1818 //
1819 // The process plugin is responsible for managing the actual
1820 // behavior of the threads and should have stopped any threads
1821 // that are going to stop before we get here.
1822 m_thread_list.DidStop();
1823
Jim Ingham4b536182011-08-09 02:12:22 +00001824 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001825 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001827 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 }
1829 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001830 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1831 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1832 else
1833 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 }
1835 else
1836 {
1837 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001838 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001839 }
1840}
1841
Jim Ingham0faa43f2011-11-08 03:00:11 +00001842void
1843Process::SetRunningUserExpression (bool on)
1844{
1845 m_mod_id.SetRunningUserExpression (on);
1846}
1847
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848addr_t
1849Process::GetImageInfoAddress()
1850{
1851 return LLDB_INVALID_ADDRESS;
1852}
1853
Greg Clayton8f343b02010-11-04 01:54:29 +00001854//----------------------------------------------------------------------
1855// LoadImage
1856//
1857// This function provides a default implementation that works for most
1858// unix variants. Any Process subclasses that need to do shared library
1859// loading differently should override LoadImage and UnloadImage and
1860// do what is needed.
1861//----------------------------------------------------------------------
1862uint32_t
1863Process::LoadImage (const FileSpec &image_spec, Error &error)
1864{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001865 char path[PATH_MAX];
1866 image_spec.GetPath(path, sizeof(path));
1867
Greg Clayton8f343b02010-11-04 01:54:29 +00001868 DynamicLoader *loader = GetDynamicLoader();
1869 if (loader)
1870 {
1871 error = loader->CanLoadImage();
1872 if (error.Fail())
1873 return LLDB_INVALID_IMAGE_TOKEN;
1874 }
1875
1876 if (error.Success())
1877 {
1878 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001879
1880 if (thread_sp)
1881 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001882 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001883
1884 if (frame_sp)
1885 {
1886 ExecutionContext exe_ctx;
1887 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001888 EvaluateExpressionOptions expr_options;
1889 expr_options.SetUnwindOnError(true);
1890 expr_options.SetIgnoreBreakpoints(true);
1891 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001892 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001893 expr.Printf("dlopen (\"%s\", 2)", path);
1894 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001895 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001896 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001897 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001898 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001899 expr.GetData(),
1900 prefix,
1901 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001902 expr_error);
1903 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001904 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001905 error = result_valobj_sp->GetError();
1906 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001907 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001908 Scalar scalar;
1909 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001910 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001911 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1912 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1913 {
1914 uint32_t image_token = m_image_tokens.size();
1915 m_image_tokens.push_back (image_ptr);
1916 return image_token;
1917 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001918 }
1919 }
1920 }
1921 }
1922 }
1923 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001924 if (!error.AsCString())
1925 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001926 return LLDB_INVALID_IMAGE_TOKEN;
1927}
1928
1929//----------------------------------------------------------------------
1930// UnloadImage
1931//
1932// This function provides a default implementation that works for most
1933// unix variants. Any Process subclasses that need to do shared library
1934// loading differently should override LoadImage and UnloadImage and
1935// do what is needed.
1936//----------------------------------------------------------------------
1937Error
1938Process::UnloadImage (uint32_t image_token)
1939{
1940 Error error;
1941 if (image_token < m_image_tokens.size())
1942 {
1943 const addr_t image_addr = m_image_tokens[image_token];
1944 if (image_addr == LLDB_INVALID_ADDRESS)
1945 {
1946 error.SetErrorString("image already unloaded");
1947 }
1948 else
1949 {
1950 DynamicLoader *loader = GetDynamicLoader();
1951 if (loader)
1952 error = loader->CanLoadImage();
1953
1954 if (error.Success())
1955 {
1956 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001957
1958 if (thread_sp)
1959 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001960 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001961
1962 if (frame_sp)
1963 {
1964 ExecutionContext exe_ctx;
1965 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001966 EvaluateExpressionOptions expr_options;
1967 expr_options.SetUnwindOnError(true);
1968 expr_options.SetIgnoreBreakpoints(true);
1969 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001970 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001971 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001972 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001973 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001974 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001975 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001976 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001977 expr.GetData(),
1978 prefix,
1979 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001980 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001981 if (result_valobj_sp->GetError().Success())
1982 {
1983 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001984 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001985 {
1986 if (scalar.UInt(1))
1987 {
1988 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1989 }
1990 else
1991 {
1992 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1993 }
1994 }
1995 }
1996 else
1997 {
1998 error = result_valobj_sp->GetError();
1999 }
2000 }
2001 }
2002 }
2003 }
2004 }
2005 else
2006 {
2007 error.SetErrorString("invalid image token");
2008 }
2009 return error;
2010}
2011
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002012const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002013Process::GetABI()
2014{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002015 if (!m_abi_sp)
2016 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2017 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002018}
2019
Jim Ingham22777012010-09-23 02:01:19 +00002020LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002021Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002022{
2023 LanguageRuntimeCollection::iterator pos;
2024 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002025 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002026 {
Jim Inghamab175242012-03-10 00:22:19 +00002027 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002028
Jim Inghamab175242012-03-10 00:22:19 +00002029 m_language_runtimes[language] = runtime_sp;
2030 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002031 }
2032 else
2033 return (*pos).second.get();
2034}
2035
2036CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002037Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002038{
Jim Inghamab175242012-03-10 00:22:19 +00002039 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002040 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2041 return static_cast<CPPLanguageRuntime *> (runtime);
2042 return NULL;
2043}
2044
2045ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002046Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002047{
Jim Inghamab175242012-03-10 00:22:19 +00002048 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002049 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2050 return static_cast<ObjCLanguageRuntime *> (runtime);
2051 return NULL;
2052}
2053
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002054bool
2055Process::IsPossibleDynamicValue (ValueObject& in_value)
2056{
2057 if (in_value.IsDynamic())
2058 return false;
2059 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2060
2061 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2062 {
2063 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2064 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2065 }
2066
2067 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2068 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2069 return true;
2070
2071 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2072 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2073}
2074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075BreakpointSiteList &
2076Process::GetBreakpointSiteList()
2077{
2078 return m_breakpoint_site_list;
2079}
2080
2081const BreakpointSiteList &
2082Process::GetBreakpointSiteList() const
2083{
2084 return m_breakpoint_site_list;
2085}
2086
2087
2088void
2089Process::DisableAllBreakpointSites ()
2090{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002091 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2092// bp_site->SetEnabled(true);
2093 DisableBreakpointSite(bp_site);
2094 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095}
2096
2097Error
2098Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2099{
2100 Error error (DisableBreakpointSiteByID (break_id));
2101
2102 if (error.Success())
2103 m_breakpoint_site_list.Remove(break_id);
2104
2105 return error;
2106}
2107
2108Error
2109Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2110{
2111 Error error;
2112 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2113 if (bp_site_sp)
2114 {
2115 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002116 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002117 }
2118 else
2119 {
Daniel Malead01b2952012-11-29 21:49:15 +00002120 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121 }
2122
2123 return error;
2124}
2125
2126Error
2127Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2128{
2129 Error error;
2130 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2131 if (bp_site_sp)
2132 {
2133 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002134 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135 }
2136 else
2137 {
Daniel Malead01b2952012-11-29 21:49:15 +00002138 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002139 }
2140 return error;
2141}
2142
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002143lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002144Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145{
Greg Clayton92bb12c2011-05-19 18:17:41 +00002146 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147 if (load_addr != LLDB_INVALID_ADDRESS)
2148 {
2149 BreakpointSiteSP bp_site_sp;
2150
2151 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2152 // create a new breakpoint site and add it.
2153
2154 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2155
2156 if (bp_site_sp)
2157 {
2158 bp_site_sp->AddOwner (owner);
2159 owner->SetBreakpointSite (bp_site_sp);
2160 return bp_site_sp->GetID();
2161 }
2162 else
2163 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002164 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 if (bp_site_sp)
2166 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002167 Error error = EnableBreakpointSite (bp_site_sp.get());
2168 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169 {
2170 owner->SetBreakpointSite (bp_site_sp);
2171 return m_breakpoint_site_list.Add (bp_site_sp);
2172 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002173 else
2174 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002175 bool show_error = true;
2176 switch (GetState())
2177 {
2178 case eStateInvalid:
2179 case eStateUnloaded:
2180 case eStateConnected:
2181 case eStateAttaching:
2182 case eStateLaunching:
2183 case eStateDetached:
2184 case eStateExited:
2185 show_error = false;
2186 break;
2187
2188 case eStateStopped:
2189 case eStateRunning:
2190 case eStateStepping:
2191 case eStateCrashed:
2192 case eStateSuspended:
2193 show_error = IsAlive();
2194 break;
2195 }
2196
2197 if (show_error)
2198 {
2199 // Report error for setting breakpoint...
2200 m_target.GetDebugger().GetErrorFile().Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2201 load_addr,
2202 owner->GetBreakpoint().GetID(),
2203 owner->GetID(),
2204 error.AsCString() ? error.AsCString() : "unkown error");
2205 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002206 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207 }
2208 }
2209 }
2210 // We failed to enable the breakpoint
2211 return LLDB_INVALID_BREAK_ID;
2212
2213}
2214
2215void
2216Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2217{
2218 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2219 if (num_owners == 0)
2220 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002221 // Don't try to disable the site if we don't have a live process anymore.
2222 if (IsAlive())
2223 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2225 }
2226}
2227
2228
2229size_t
2230Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2231{
2232 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002233 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234
Jim Ingham20c77192011-06-29 19:42:28 +00002235 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002237 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2238 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002239 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002240 addr_t intersect_addr;
2241 size_t intersect_size;
2242 size_t opcode_offset;
2243 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002244 {
2245 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2246 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002247 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002248 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002249 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002250 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002252 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002253 }
2254 return bytes_removed;
2255}
2256
2257
Greg Claytonded470d2011-03-19 01:12:21 +00002258
2259size_t
2260Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2261{
2262 PlatformSP platform_sp (m_target.GetPlatform());
2263 if (platform_sp)
2264 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2265 return 0;
2266}
2267
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268Error
2269Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2270{
2271 Error error;
2272 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002273 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002274 const addr_t bp_addr = bp_site->GetLoadAddress();
2275 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002276 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277 if (bp_site->IsEnabled())
2278 {
2279 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002280 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 +00002281 return error;
2282 }
2283
2284 if (bp_addr == LLDB_INVALID_ADDRESS)
2285 {
2286 error.SetErrorString("BreakpointSite contains an invalid load address.");
2287 return error;
2288 }
2289 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2290 // trap for the breakpoint site
2291 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2292
2293 if (bp_opcode_size == 0)
2294 {
Daniel Malead01b2952012-11-29 21:49:15 +00002295 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296 }
2297 else
2298 {
2299 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2300
2301 if (bp_opcode_bytes == NULL)
2302 {
2303 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2304 return error;
2305 }
2306
2307 // Save the original opcode by reading it
2308 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2309 {
2310 // Write a software breakpoint in place of the original opcode
2311 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2312 {
2313 uint8_t verify_bp_opcode_bytes[64];
2314 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2315 {
2316 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2317 {
2318 bp_site->SetEnabled(true);
2319 bp_site->SetType (BreakpointSite::eSoftware);
2320 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002321 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322 bp_site->GetID(),
2323 (uint64_t)bp_addr);
2324 }
2325 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002326 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327 }
2328 else
2329 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2330 }
2331 else
2332 error.SetErrorString("Unable to write breakpoint trap to memory.");
2333 }
2334 else
2335 error.SetErrorString("Unable to read memory at breakpoint address.");
2336 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002337 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002338 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 bp_site->GetID(),
2340 (uint64_t)bp_addr,
2341 error.AsCString());
2342 return error;
2343}
2344
2345Error
2346Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2347{
2348 Error error;
2349 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002350 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 addr_t bp_addr = bp_site->GetLoadAddress();
2352 lldb::user_id_t breakID = bp_site->GetID();
2353 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002354 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355
2356 if (bp_site->IsHardware())
2357 {
2358 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2359 }
2360 else if (bp_site->IsEnabled())
2361 {
2362 const size_t break_op_size = bp_site->GetByteSize();
2363 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2364 if (break_op_size > 0)
2365 {
2366 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002367 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002368 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369 bool break_op_found = false;
2370
2371 // Read the breakpoint opcode
2372 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2373 {
2374 bool verify = false;
2375 // Make sure we have the a breakpoint opcode exists at this address
2376 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2377 {
2378 break_op_found = true;
2379 // We found a valid breakpoint opcode at this address, now restore
2380 // the saved opcode.
2381 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2382 {
2383 verify = true;
2384 }
2385 else
2386 error.SetErrorString("Memory write failed when restoring original opcode.");
2387 }
2388 else
2389 {
2390 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2391 // Set verify to true and so we can check if the original opcode has already been restored
2392 verify = true;
2393 }
2394
2395 if (verify)
2396 {
Greg Claytonc982c762010-07-09 20:39:50 +00002397 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002398 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399 // Verify that our original opcode made it back to the inferior
2400 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2401 {
2402 // compare the memory we just read with the original opcode
2403 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2404 {
2405 // SUCCESS
2406 bp_site->SetEnabled(false);
2407 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002408 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 +00002409 return error;
2410 }
2411 else
2412 {
2413 if (break_op_found)
2414 error.SetErrorString("Failed to restore original opcode.");
2415 }
2416 }
2417 else
2418 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2419 }
2420 }
2421 else
2422 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2423 }
2424 }
2425 else
2426 {
2427 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002428 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 +00002429 return error;
2430 }
2431
2432 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002433 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 bp_site->GetID(),
2435 (uint64_t)bp_addr,
2436 error.AsCString());
2437 return error;
2438
2439}
2440
Greg Clayton58be07b2011-01-07 06:08:19 +00002441// Uncomment to verify memory caching works after making changes to caching code
2442//#define VERIFY_MEMORY_READS
2443
Sean Callanan64c0cf22012-06-07 22:26:42 +00002444size_t
2445Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2446{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002447 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002448 if (!GetDisableMemoryCache())
2449 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002450#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002451 // Memory caching is enabled, with debug verification
2452
2453 if (buf && size)
2454 {
2455 // Uncomment the line below to make sure memory caching is working.
2456 // I ran this through the test suite and got no assertions, so I am
2457 // pretty confident this is working well. If any changes are made to
2458 // memory caching, uncomment the line below and test your changes!
2459
2460 // Verify all memory reads by using the cache first, then redundantly
2461 // reading the same memory from the inferior and comparing to make sure
2462 // everything is exactly the same.
2463 std::string verify_buf (size, '\0');
2464 assert (verify_buf.size() == size);
2465 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2466 Error verify_error;
2467 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2468 assert (cache_bytes_read == verify_bytes_read);
2469 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2470 assert (verify_error.Success() == error.Success());
2471 return cache_bytes_read;
2472 }
2473 return 0;
2474#else // !defined(VERIFY_MEMORY_READS)
2475 // Memory caching is enabled, without debug verification
2476
2477 return m_memory_cache.Read (addr, buf, size, error);
2478#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002479 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002480 else
2481 {
2482 // Memory caching is disabled
2483
2484 return ReadMemoryFromInferior (addr, buf, size, error);
2485 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002486}
Greg Clayton58be07b2011-01-07 06:08:19 +00002487
Greg Clayton4c82d422012-05-18 23:20:01 +00002488size_t
2489Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2490{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002491 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002492 out_str.clear();
2493 addr_t curr_addr = addr;
2494 while (1)
2495 {
2496 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2497 if (length == 0)
2498 break;
2499 out_str.append(buf, length);
2500 // If we got "length - 1" bytes, we didn't get the whole C string, we
2501 // need to read some more characters
2502 if (length == sizeof(buf) - 1)
2503 curr_addr += length;
2504 else
2505 break;
2506 }
2507 return out_str.size();
2508}
2509
Greg Clayton58be07b2011-01-07 06:08:19 +00002510
2511size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002512Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2513 size_t type_width)
2514{
2515 size_t total_bytes_read = 0;
2516 if (dst && max_bytes && type_width && max_bytes >= type_width)
2517 {
2518 // Ensure a null terminator independent of the number of bytes that is read.
2519 memset (dst, 0, max_bytes);
2520 size_t bytes_left = max_bytes - type_width;
2521
2522 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2523 assert(sizeof(terminator) >= type_width &&
2524 "Attempting to validate a string with more than 4 bytes per character!");
2525
2526 addr_t curr_addr = addr;
2527 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2528 char *curr_dst = dst;
2529
2530 error.Clear();
2531 while (bytes_left > 0 && error.Success())
2532 {
2533 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2534 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2535 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2536
2537 if (bytes_read == 0)
2538 break;
2539
2540 // Search for a null terminator of correct size and alignment in bytes_read
2541 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2542 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2543 if (::strncmp(&dst[i], terminator, type_width) == 0)
2544 {
2545 error.Clear();
2546 return i;
2547 }
2548
2549 total_bytes_read += bytes_read;
2550 curr_dst += bytes_read;
2551 curr_addr += bytes_read;
2552 bytes_left -= bytes_read;
2553 }
2554 }
2555 else
2556 {
2557 if (max_bytes)
2558 error.SetErrorString("invalid arguments");
2559 }
2560 return total_bytes_read;
2561}
2562
2563// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2564// null terminators.
2565size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002566Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002567{
2568 size_t total_cstr_len = 0;
2569 if (dst && dst_max_len)
2570 {
Greg Claytone91b7952011-12-15 03:14:23 +00002571 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002572 // NULL out everything just to be safe
2573 memset (dst, 0, dst_max_len);
2574 Error error;
2575 addr_t curr_addr = addr;
2576 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2577 size_t bytes_left = dst_max_len - 1;
2578 char *curr_dst = dst;
2579
2580 while (bytes_left > 0)
2581 {
2582 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2583 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2584 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2585
2586 if (bytes_read == 0)
2587 {
Greg Claytone91b7952011-12-15 03:14:23 +00002588 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002589 dst[total_cstr_len] = '\0';
2590 break;
2591 }
2592 const size_t len = strlen(curr_dst);
2593
2594 total_cstr_len += len;
2595
2596 if (len < bytes_to_read)
2597 break;
2598
2599 curr_dst += bytes_read;
2600 curr_addr += bytes_read;
2601 bytes_left -= bytes_read;
2602 }
2603 }
Greg Claytone91b7952011-12-15 03:14:23 +00002604 else
2605 {
2606 if (dst == NULL)
2607 result_error.SetErrorString("invalid arguments");
2608 else
2609 result_error.Clear();
2610 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002611 return total_cstr_len;
2612}
2613
2614size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002615Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2616{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 if (buf == NULL || size == 0)
2618 return 0;
2619
2620 size_t bytes_read = 0;
2621 uint8_t *bytes = (uint8_t *)buf;
2622
2623 while (bytes_read < size)
2624 {
2625 const size_t curr_size = size - bytes_read;
2626 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2627 bytes + bytes_read,
2628 curr_size,
2629 error);
2630 bytes_read += curr_bytes_read;
2631 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2632 break;
2633 }
2634
2635 // Replace any software breakpoint opcodes that fall into this range back
2636 // into "buf" before we return
2637 if (bytes_read > 0)
2638 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2639 return bytes_read;
2640}
2641
Greg Clayton58a4c462010-12-16 20:01:20 +00002642uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002643Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002644{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002645 Scalar scalar;
2646 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2647 return scalar.ULongLong(fail_value);
2648 return fail_value;
2649}
2650
2651addr_t
2652Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2653{
2654 Scalar scalar;
2655 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2656 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2657 return LLDB_INVALID_ADDRESS;
2658}
2659
2660
2661bool
2662Process::WritePointerToMemory (lldb::addr_t vm_addr,
2663 lldb::addr_t ptr_value,
2664 Error &error)
2665{
2666 Scalar scalar;
2667 const uint32_t addr_byte_size = GetAddressByteSize();
2668 if (addr_byte_size <= 4)
2669 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002670 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002671 scalar = ptr_value;
2672 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002673}
2674
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002675size_t
2676Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2677{
2678 size_t bytes_written = 0;
2679 const uint8_t *bytes = (const uint8_t *)buf;
2680
2681 while (bytes_written < size)
2682 {
2683 const size_t curr_size = size - bytes_written;
2684 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2685 bytes + bytes_written,
2686 curr_size,
2687 error);
2688 bytes_written += curr_bytes_written;
2689 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2690 break;
2691 }
2692 return bytes_written;
2693}
2694
2695size_t
2696Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2697{
Greg Clayton58be07b2011-01-07 06:08:19 +00002698#if defined (ENABLE_MEMORY_CACHING)
2699 m_memory_cache.Flush (addr, size);
2700#endif
2701
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702 if (buf == NULL || size == 0)
2703 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002704
Jim Ingham4b536182011-08-09 02:12:22 +00002705 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002706
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002707 // We need to write any data that would go where any current software traps
2708 // (enabled software breakpoints) any software traps (breakpoints) that we
2709 // may have placed in our tasks memory.
2710
Greg Claytond8cf1a12013-06-12 00:46:38 +00002711 BreakpointSiteList bp_sites_in_range;
2712
2713 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002715 // No breakpoint sites overlap
2716 if (bp_sites_in_range.IsEmpty())
2717 return WriteMemoryPrivate (addr, buf, size, error);
2718 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002720 const uint8_t *ubuf = (const uint8_t *)buf;
2721 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722
Greg Claytond8cf1a12013-06-12 00:46:38 +00002723 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2724
2725 if (error.Success())
2726 {
2727 addr_t intersect_addr;
2728 size_t intersect_size;
2729 size_t opcode_offset;
2730 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2731 assert(intersects);
2732 assert(addr <= intersect_addr && intersect_addr < addr + size);
2733 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2734 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2735
2736 // Check for bytes before this breakpoint
2737 const addr_t curr_addr = addr + bytes_written;
2738 if (intersect_addr > curr_addr)
2739 {
2740 // There are some bytes before this breakpoint that we need to
2741 // just write to memory
2742 size_t curr_size = intersect_addr - curr_addr;
2743 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2744 ubuf + bytes_written,
2745 curr_size,
2746 error);
2747 bytes_written += curr_bytes_written;
2748 if (curr_bytes_written != curr_size)
2749 {
2750 // We weren't able to write all of the requested bytes, we
2751 // are done looping and will return the number of bytes that
2752 // we have written so far.
2753 if (error.Success())
2754 error.SetErrorToGenericError();
2755 }
2756 }
2757 // Now write any bytes that would cover up any software breakpoints
2758 // directly into the breakpoint opcode buffer
2759 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2760 bytes_written += intersect_size;
2761 }
2762 });
2763
2764 if (bytes_written < size)
2765 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2766 ubuf + bytes_written,
2767 size - bytes_written,
2768 error);
2769 }
2770 }
2771 else
2772 {
2773 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774 }
2775
2776 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002777 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002779
2780size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002781Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002782{
2783 if (byte_size == UINT32_MAX)
2784 byte_size = scalar.GetByteSize();
2785 if (byte_size > 0)
2786 {
2787 uint8_t buf[32];
2788 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2789 if (mem_size > 0)
2790 return WriteMemory(addr, buf, mem_size, error);
2791 else
2792 error.SetErrorString ("failed to get scalar as memory data");
2793 }
2794 else
2795 {
2796 error.SetErrorString ("invalid scalar value");
2797 }
2798 return 0;
2799}
2800
2801size_t
2802Process::ReadScalarIntegerFromMemory (addr_t addr,
2803 uint32_t byte_size,
2804 bool is_signed,
2805 Scalar &scalar,
2806 Error &error)
2807{
Greg Clayton7060f892013-05-01 23:41:30 +00002808 uint64_t uval = 0;
2809 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002810 {
Greg Clayton7060f892013-05-01 23:41:30 +00002811 error.SetErrorString ("byte size is zero");
2812 }
2813 else if (byte_size & (byte_size - 1))
2814 {
2815 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2816 }
2817 else if (byte_size <= sizeof(uval))
2818 {
2819 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002820 if (bytes_read == byte_size)
2821 {
2822 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002823 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002824 if (byte_size <= 4)
2825 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002826 else
Greg Clayton7060f892013-05-01 23:41:30 +00002827 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002828 if (is_signed)
2829 scalar.SignExtend(byte_size * 8);
2830 return bytes_read;
2831 }
2832 }
2833 else
2834 {
2835 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2836 }
2837 return 0;
2838}
2839
Greg Claytond495c532011-05-17 03:37:42 +00002840#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841addr_t
2842Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2843{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002844 if (GetPrivateState() != eStateStopped)
2845 return LLDB_INVALID_ADDRESS;
2846
Greg Claytond495c532011-05-17 03:37:42 +00002847#if defined (USE_ALLOCATE_MEMORY_CACHE)
2848 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2849#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002850 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002851 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002852 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002853 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 +00002854 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002855 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002856 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002857 m_mod_id.GetStopID(),
2858 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002859 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002860#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002861}
2862
Sean Callanan90539452011-09-20 23:01:51 +00002863bool
2864Process::CanJIT ()
2865{
Sean Callanana7b443a2012-02-14 22:50:38 +00002866 if (m_can_jit == eCanJITDontKnow)
2867 {
2868 Error err;
2869
2870 uint64_t allocated_memory = AllocateMemory(8,
2871 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2872 err);
2873
2874 if (err.Success())
2875 m_can_jit = eCanJITYes;
2876 else
2877 m_can_jit = eCanJITNo;
2878
2879 DeallocateMemory (allocated_memory);
2880 }
2881
Sean Callanan90539452011-09-20 23:01:51 +00002882 return m_can_jit == eCanJITYes;
2883}
2884
2885void
2886Process::SetCanJIT (bool can_jit)
2887{
2888 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2889}
2890
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891Error
2892Process::DeallocateMemory (addr_t ptr)
2893{
Greg Claytond495c532011-05-17 03:37:42 +00002894 Error error;
2895#if defined (USE_ALLOCATE_MEMORY_CACHE)
2896 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2897 {
Daniel Malead01b2952012-11-29 21:49:15 +00002898 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002899 }
2900#else
2901 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002902
Greg Clayton5160ce52013-03-27 23:08:40 +00002903 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002904 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002905 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 +00002906 ptr,
2907 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002908 m_mod_id.GetStopID(),
2909 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002910#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002911 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912}
2913
Han Ming Ongc811d382012-11-17 00:33:14 +00002914
Greg Claytonc9660542012-02-05 02:38:54 +00002915ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002916Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002917 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002918{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002919 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002920 if (module_sp)
2921 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002922 Error error;
2923 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2924 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002925 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002926 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002927 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002928}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929
2930Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002931Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932{
2933 Error error;
2934 error.SetErrorString("watchpoints are not supported");
2935 return error;
2936}
2937
2938Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002939Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940{
2941 Error error;
2942 error.SetErrorString("watchpoints are not supported");
2943 return error;
2944}
2945
2946StateType
2947Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2948{
2949 StateType state;
2950 // Now wait for the process to launch and return control to us, and then
2951 // call DidLaunch:
2952 while (1)
2953 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002954 event_sp.reset();
2955 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2956
Greg Clayton2637f822011-11-17 01:23:07 +00002957 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002958 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002959
2960 // If state is invalid, then we timed out
2961 if (state == eStateInvalid)
2962 break;
2963
2964 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965 HandlePrivateEvent (event_sp);
2966 }
2967 return state;
2968}
2969
2970Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002971Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972{
2973 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002974 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002975 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002976 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002977 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002978 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002979
Greg Claytonaa149cb2011-08-11 02:48:45 +00002980 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002981 if (exe_module)
2982 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002983 char local_exec_file_path[PATH_MAX];
2984 char platform_exec_file_path[PATH_MAX];
2985 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2986 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987 if (exe_module->GetFileSpec().Exists())
2988 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002989 // Install anything that might need to be installed prior to launching.
2990 // For host systems, this will do nothing, but if we are connected to a
2991 // remote platform it will install any needed binaries
2992 error = GetTarget().Install(&launch_info);
2993 if (error.Fail())
2994 return error;
2995
Greg Clayton71337622011-02-24 22:24:29 +00002996 if (PrivateStateThreadIsValid ())
2997 PausePrivateStateThread ();
2998
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 error = WillLaunch (exe_module);
3000 if (error.Success())
3001 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003002 const bool restarted = false;
3003 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003004 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005
Ed Maste64fad602013-07-29 20:58:06 +00003006 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003007 {
3008 // Now launch using these arguments.
3009 error = DoLaunch (exe_module, launch_info);
3010 }
3011 else
3012 {
3013 // This shouldn't happen
3014 error.SetErrorString("failed to acquire process run lock");
3015 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016
3017 if (error.Fail())
3018 {
3019 if (GetID() != LLDB_INVALID_PROCESS_ID)
3020 {
3021 SetID (LLDB_INVALID_PROCESS_ID);
3022 const char *error_string = error.AsCString();
3023 if (error_string == NULL)
3024 error_string = "launch failed";
3025 SetExitStatus (-1, error_string);
3026 }
3027 }
3028 else
3029 {
3030 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003031 TimeValue timeout_time;
3032 timeout_time = TimeValue::Now();
3033 timeout_time.OffsetWithSeconds(10);
3034 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035
Greg Clayton1a38ea72011-06-22 01:42:17 +00003036 if (state == eStateInvalid || event_sp.get() == NULL)
3037 {
3038 // We were able to launch the process, but we failed to
3039 // catch the initial stop.
3040 SetExitStatus (0, "failed to catch stop after launch");
3041 Destroy();
3042 }
3043 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003045
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003046 DidLaunch ();
3047
Greg Claytonc859e2d2012-02-13 23:10:39 +00003048 DynamicLoader *dyld = GetDynamicLoader ();
3049 if (dyld)
3050 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003051
Jason Molendaeef51062013-11-05 03:57:19 +00003052 SystemRuntime *system_runtime = GetSystemRuntime ();
3053 if (system_runtime)
3054 system_runtime->DidLaunch();
3055
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003056 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057 // This delays passing the stopped event to listeners till DidLaunch gets
3058 // a chance to complete...
3059 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00003060
3061 if (PrivateStateThreadIsValid ())
3062 ResumePrivateStateThread ();
3063 else
3064 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003065 }
3066 else if (state == eStateExited)
3067 {
3068 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3069 // not likely to work, and return an invalid pid.
3070 HandlePrivateEvent (event_sp);
3071 }
3072 }
3073 }
3074 }
3075 else
3076 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003077 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078 }
3079 }
3080 return error;
3081}
3082
Greg Claytonc3776bf2012-02-09 06:16:32 +00003083
3084Error
3085Process::LoadCore ()
3086{
3087 Error error = DoLoadCore();
3088 if (error.Success())
3089 {
3090 if (PrivateStateThreadIsValid ())
3091 ResumePrivateStateThread ();
3092 else
3093 StartPrivateStateThread ();
3094
Greg Claytonc859e2d2012-02-13 23:10:39 +00003095 DynamicLoader *dyld = GetDynamicLoader ();
3096 if (dyld)
3097 dyld->DidAttach();
3098
Jason Molendaeef51062013-11-05 03:57:19 +00003099 SystemRuntime *system_runtime = GetSystemRuntime ();
3100 if (system_runtime)
3101 system_runtime->DidAttach();
3102
Greg Claytonc859e2d2012-02-13 23:10:39 +00003103 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003104 // We successfully loaded a core file, now pretend we stopped so we can
3105 // show all of the threads in the core file and explore the crashed
3106 // state.
3107 SetPrivateState (eStateStopped);
3108
3109 }
3110 return error;
3111}
3112
Greg Claytonc859e2d2012-02-13 23:10:39 +00003113DynamicLoader *
3114Process::GetDynamicLoader ()
3115{
3116 if (m_dyld_ap.get() == NULL)
3117 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3118 return m_dyld_ap.get();
3119}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003120
Jason Molendaeef51062013-11-05 03:57:19 +00003121SystemRuntime *
3122Process::GetSystemRuntime ()
3123{
3124 if (m_system_runtime_ap.get() == NULL)
3125 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3126 return m_system_runtime_ap.get();
3127}
3128
Greg Claytonc3776bf2012-02-09 06:16:32 +00003129
Jim Inghambb3a2832011-01-29 01:49:25 +00003130Process::NextEventAction::EventActionResult
3131Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132{
Jim Inghambb3a2832011-01-29 01:49:25 +00003133 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3134 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003135 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003136 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003137 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003138 return eEventActionRetry;
3139
3140 case eStateStopped:
3141 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003142 {
3143 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003144 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003145 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003146 // We don't want these events to be reported, so go set the ShouldReportStop here:
3147 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3148
Greg Claytonc9ed4782011-11-12 02:10:56 +00003149 if (m_exec_count > 0)
3150 {
3151 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003152 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003153 return eEventActionRetry;
3154 }
3155 else
3156 {
3157 m_process->CompleteAttach ();
3158 return eEventActionSuccess;
3159 }
3160 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003161 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003162
Greg Clayton513c26c2011-01-29 07:10:55 +00003163 default:
3164 case eStateExited:
3165 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003166 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003167 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003168
3169 m_exit_string.assign ("No valid Process");
3170 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003171}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003172
Jim Inghambb3a2832011-01-29 01:49:25 +00003173Process::NextEventAction::EventActionResult
3174Process::AttachCompletionHandler::HandleBeingInterrupted()
3175{
3176 return eEventActionSuccess;
3177}
3178
3179const char *
3180Process::AttachCompletionHandler::GetExitString ()
3181{
3182 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183}
3184
3185Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003186Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003188 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003189 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003190 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003191 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003192 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003193
Greg Clayton144f3a92011-11-15 03:53:30 +00003194 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003195 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003196 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003197 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003198 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003199
Greg Clayton144f3a92011-11-15 03:53:30 +00003200 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003201 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003202 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3203
3204 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003206 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3207 if (error.Success())
3208 {
Ed Maste64fad602013-07-29 20:58:06 +00003209 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003210 {
3211 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003212 const bool restarted = false;
3213 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003214 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003215 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003216 }
3217 else
3218 {
3219 // This shouldn't happen
3220 error.SetErrorString("failed to acquire process run lock");
3221 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003222
Greg Clayton144f3a92011-11-15 03:53:30 +00003223 if (error.Fail())
3224 {
3225 if (GetID() != LLDB_INVALID_PROCESS_ID)
3226 {
3227 SetID (LLDB_INVALID_PROCESS_ID);
3228 if (error.AsCString() == NULL)
3229 error.SetErrorString("attach failed");
3230
3231 SetExitStatus(-1, error.AsCString());
3232 }
3233 }
3234 else
3235 {
3236 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3237 StartPrivateStateThread();
3238 }
3239 return error;
3240 }
Greg Claytone996fd32011-03-08 22:40:15 +00003241 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003242 else
Greg Claytone996fd32011-03-08 22:40:15 +00003243 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003244 ProcessInstanceInfoList process_infos;
3245 PlatformSP platform_sp (m_target.GetPlatform ());
3246
3247 if (platform_sp)
3248 {
3249 ProcessInstanceInfoMatch match_info;
3250 match_info.GetProcessInfo() = attach_info;
3251 match_info.SetNameMatchType (eNameMatchEquals);
3252 platform_sp->FindProcesses (match_info, process_infos);
3253 const uint32_t num_matches = process_infos.GetSize();
3254 if (num_matches == 1)
3255 {
3256 attach_pid = process_infos.GetProcessIDAtIndex(0);
3257 // Fall through and attach using the above process ID
3258 }
3259 else
3260 {
3261 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3262 if (num_matches > 1)
3263 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3264 else
3265 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3266 }
3267 }
3268 else
3269 {
3270 error.SetErrorString ("invalid platform, can't find processes by name");
3271 return error;
3272 }
Greg Claytone996fd32011-03-08 22:40:15 +00003273 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003274 }
3275 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003276 {
3277 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003278 }
3279 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003280
3281 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003282 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003283 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003284 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003286
Ed Maste64fad602013-07-29 20:58:06 +00003287 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003288 {
3289 // Now attach using these arguments.
3290 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003291 const bool restarted = false;
3292 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003293 error = DoAttachToProcessWithID (attach_pid, attach_info);
3294 }
3295 else
3296 {
3297 // This shouldn't happen
3298 error.SetErrorString("failed to acquire process run lock");
3299 }
3300
Greg Clayton144f3a92011-11-15 03:53:30 +00003301 if (error.Success())
3302 {
3303
3304 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3305 StartPrivateStateThread();
3306 }
3307 else
Greg Claytone996fd32011-03-08 22:40:15 +00003308 {
3309 if (GetID() != LLDB_INVALID_PROCESS_ID)
3310 {
3311 SetID (LLDB_INVALID_PROCESS_ID);
3312 const char *error_string = error.AsCString();
3313 if (error_string == NULL)
3314 error_string = "attach failed";
3315
3316 SetExitStatus(-1, error_string);
3317 }
3318 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003319 }
3320 }
3321 return error;
3322}
3323
Greg Clayton93d3c8332011-02-16 04:46:07 +00003324void
3325Process::CompleteAttach ()
3326{
3327 // Let the process subclass figure out at much as it can about the process
3328 // before we go looking for a dynamic loader plug-in.
3329 DidAttach();
3330
Jim Ingham4299fdb2011-09-15 01:10:17 +00003331 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3332 // the same as the one we've already set, switch architectures.
3333 PlatformSP platform_sp (m_target.GetPlatform ());
3334 assert (platform_sp.get());
3335 if (platform_sp)
3336 {
Greg Clayton70512312012-05-08 01:45:38 +00003337 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003338 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003339 {
3340 ArchSpec platform_arch;
3341 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3342 if (platform_sp)
3343 {
3344 m_target.SetPlatform (platform_sp);
3345 m_target.SetArchitecture(platform_arch);
3346 }
3347 }
3348 else
3349 {
3350 ProcessInstanceInfo process_info;
3351 platform_sp->GetProcessInfo (GetID(), process_info);
3352 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003353 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003354 m_target.SetArchitecture (process_arch);
3355 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003356 }
3357
3358 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003359 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003360 DynamicLoader *dyld = GetDynamicLoader ();
3361 if (dyld)
3362 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003363
Jason Molendaeef51062013-11-05 03:57:19 +00003364 SystemRuntime *system_runtime = GetSystemRuntime ();
3365 if (system_runtime)
3366 system_runtime->DidAttach();
3367
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003368 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003369 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003370 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003371 Mutex::Locker modules_locker(target_modules.GetMutex());
3372 size_t num_modules = target_modules.GetSize();
3373 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003374
Andy Gibbsa297a972013-06-19 19:04:53 +00003375 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003376 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003377 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003378 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003379 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003380 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003381 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003382 break;
3383 }
3384 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003385 if (new_executable_module_sp)
3386 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003387}
3388
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003389Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003390Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003391{
Greg Claytonb766a732011-02-04 01:58:07 +00003392 m_abi_sp.reset();
3393 m_process_input_reader.reset();
3394
3395 // Find the process and its architecture. Make sure it matches the architecture
3396 // of the current Target, and if not adjust it.
3397
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003398 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003399 if (error.Success())
3400 {
Greg Clayton71337622011-02-24 22:24:29 +00003401 if (GetID() != LLDB_INVALID_PROCESS_ID)
3402 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003403 EventSP event_sp;
3404 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3405
3406 if (state == eStateStopped || state == eStateCrashed)
3407 {
3408 // If we attached and actually have a process on the other end, then
3409 // this ended up being the equivalent of an attach.
3410 CompleteAttach ();
3411
3412 // This delays passing the stopped event to listeners till
3413 // CompleteAttach gets a chance to complete...
3414 HandlePrivateEvent (event_sp);
3415
3416 }
Greg Clayton71337622011-02-24 22:24:29 +00003417 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003418
3419 if (PrivateStateThreadIsValid ())
3420 ResumePrivateStateThread ();
3421 else
3422 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003423 }
3424 return error;
3425}
3426
3427
3428Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003429Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430{
Greg Clayton5160ce52013-03-27 23:08:40 +00003431 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003432 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003433 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003434 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003435 StateAsCString(m_public_state.GetValue()),
3436 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437
3438 Error error (WillResume());
3439 // Tell the process it is about to resume before the thread list
3440 if (error.Success())
3441 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003442 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003443 // can let all of our threads know that they are about to be
3444 // resumed. Threads will each be called with
3445 // Thread::WillResume(StateType) where StateType contains the state
3446 // that they are supposed to have when the process is resumed
3447 // (suspended/running/stepping). Threads should also check
3448 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003449 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003450 if (m_thread_list.WillResume())
3451 {
Jim Ingham372787f2012-04-07 00:00:41 +00003452 // Last thing, do the PreResumeActions.
3453 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454 {
Jim Ingham0161b492013-02-09 01:29:05 +00003455 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003456 }
3457 else
3458 {
3459 m_mod_id.BumpResumeID();
3460 error = DoResume();
3461 if (error.Success())
3462 {
3463 DidResume();
3464 m_thread_list.DidResume();
3465 if (log)
3466 log->Printf ("Process thinks the process has resumed.");
3467 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003468 }
3469 }
3470 else
3471 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003472 // Somebody wanted to run without running. So generate a continue & a stopped event,
3473 // and let the world handle them.
3474 if (log)
3475 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3476
3477 SetPrivateState(eStateRunning);
3478 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003479 }
3480 }
Jim Ingham444586b2011-01-24 06:34:17 +00003481 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003482 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003483 return error;
3484}
3485
3486Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003487Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003489 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3490 // in case it was already set and some thread plan logic calls halt on its
3491 // own.
3492 m_clear_thread_plans_on_stop |= clear_thread_plans;
3493
Jim Inghamaacc3182012-06-06 00:29:30 +00003494 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3495 // we could just straightaway get another event. It just narrows the window...
3496 m_currently_handling_event.WaitForValueEqualTo(false);
3497
3498
Jim Inghambb3a2832011-01-29 01:49:25 +00003499 // Pause our private state thread so we can ensure no one else eats
3500 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003501 Listener halt_listener ("lldb.process.halt_listener");
3502 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003503
Jim Inghambb3a2832011-01-29 01:49:25 +00003504 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003505 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003506
Greg Clayton513c26c2011-01-29 07:10:55 +00003507 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003508 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003509
Greg Clayton513c26c2011-01-29 07:10:55 +00003510 bool caused_stop = false;
3511
3512 // Ask the process subclass to actually halt our process
3513 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003514 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003515 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003516 if (m_public_state.GetValue() == eStateAttaching)
3517 {
3518 SetExitStatus(SIGKILL, "Cancelled async attach.");
3519 Destroy ();
3520 }
3521 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003522 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003523 // If "caused_stop" is true, then DoHalt stopped the process. If
3524 // "caused_stop" is false, the process was already stopped.
3525 // If the DoHalt caused the process to stop, then we want to catch
3526 // this event and set the interrupted bool to true before we pass
3527 // this along so clients know that the process was interrupted by
3528 // a halt command.
3529 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003530 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003531 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003532 TimeValue timeout_time;
3533 timeout_time = TimeValue::Now();
3534 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003535 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3536 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003537
Jim Ingham0f16e732011-02-08 05:20:59 +00003538 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003539 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003540 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003541 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003542 }
3543 else
3544 {
Greg Clayton2637f822011-11-17 01:23:07 +00003545 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003546 {
3547 // We caused the process to interrupt itself, so mark this
3548 // as such in the stop event so clients can tell an interrupted
3549 // process from a natural stop
3550 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3551 }
3552 else
3553 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003554 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003555 if (log)
3556 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3557 error.SetErrorString ("Did not get stopped event after halt.");
3558 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003559 }
3560 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003561 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003562 }
3563 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003564 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003565 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003566 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003567
3568 // Post any event we might have consumed. If all goes well, we will have
3569 // stopped the process, intercepted the event and set the interrupted
3570 // bool in the event. Post it to the private event queue and that will end up
3571 // correctly setting the state.
3572 if (event_sp)
3573 m_private_state_broadcaster.BroadcastEvent(event_sp);
3574
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003575 return error;
3576}
3577
3578Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003579Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3580{
3581 Error error;
3582 if (m_public_state.GetValue() == eStateRunning)
3583 {
3584 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3585 if (log)
3586 log->Printf("Process::Destroy() About to halt.");
3587 error = Halt();
3588 if (error.Success())
3589 {
3590 // Consume the halt event.
3591 TimeValue timeout (TimeValue::Now());
3592 timeout.OffsetWithSeconds(1);
3593 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3594
3595 // If the process exited while we were waiting for it to stop, put the exited event into
3596 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3597 // they don't have a process anymore...
3598
3599 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3600 {
3601 if (log)
3602 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3603 return error;
3604 }
3605 else
3606 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3607
3608 if (state != eStateStopped)
3609 {
3610 if (log)
3611 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3612 // If we really couldn't stop the process then we should just error out here, but if the
3613 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3614 StateType private_state = m_private_state.GetValue();
3615 if (private_state != eStateStopped)
3616 {
3617 return error;
3618 }
3619 }
3620 }
3621 else
3622 {
3623 if (log)
3624 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3625 }
3626 }
3627 return error;
3628}
3629
3630Error
Jim Inghamacff8952013-05-02 00:27:30 +00003631Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003633 EventSP exit_event_sp;
3634 Error error;
3635 m_destroy_in_process = true;
3636
3637 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003638
3639 if (error.Success())
3640 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003641 if (DetachRequiresHalt())
3642 {
3643 error = HaltForDestroyOrDetach (exit_event_sp);
3644 if (!error.Success())
3645 {
3646 m_destroy_in_process = false;
3647 return error;
3648 }
3649 else if (exit_event_sp)
3650 {
3651 // We shouldn't need to do anything else here. There's no process left to detach from...
3652 StopPrivateStateThread();
3653 m_destroy_in_process = false;
3654 return error;
3655 }
3656 }
3657
Jim Inghamacff8952013-05-02 00:27:30 +00003658 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003659 if (error.Success())
3660 {
3661 DidDetach();
3662 StopPrivateStateThread();
3663 }
Jim Inghamacff8952013-05-02 00:27:30 +00003664 else
3665 {
3666 return error;
3667 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003668 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003669 m_destroy_in_process = false;
3670
3671 // If we exited when we were waiting for a process to stop, then
3672 // forward the event here so we don't lose the event
3673 if (exit_event_sp)
3674 {
3675 // Directly broadcast our exited event because we shut down our
3676 // private state thread above
3677 BroadcastEvent(exit_event_sp);
3678 }
3679
3680 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3681 // the last events through the event system, in which case we might strand the write lock. Unlock
3682 // it here so when we do to tear down the process we don't get an error destroying the lock.
3683
Ed Maste64fad602013-07-29 20:58:06 +00003684 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003685 return error;
3686}
3687
3688Error
3689Process::Destroy ()
3690{
Jim Ingham09437922013-03-01 20:04:25 +00003691
3692 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3693 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3694 // failed and the process stays around for some reason it won't be in a confused state.
3695
3696 m_destroy_in_process = true;
3697
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003698 Error error (WillDestroy());
3699 if (error.Success())
3700 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003701 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003702 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003703 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003704 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003705 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003706
Jim Inghamaacc3182012-06-06 00:29:30 +00003707 if (m_public_state.GetValue() != eStateRunning)
3708 {
3709 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3710 // kill it, we don't want it hitting a breakpoint...
3711 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3712 // we're not going to have much luck doing this now.
3713 m_thread_list.DiscardThreadPlans();
3714 DisableAllBreakpointSites();
3715 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717 error = DoDestroy();
3718 if (error.Success())
3719 {
3720 DidDestroy();
3721 StopPrivateStateThread();
3722 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003723 m_stdio_communication.StopReadThread();
3724 m_stdio_communication.Disconnect();
3725 if (m_process_input_reader && m_process_input_reader->IsActive())
3726 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3727 if (m_process_input_reader)
3728 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003729
3730 // If we exited when we were waiting for a process to stop, then
3731 // forward the event here so we don't lose the event
3732 if (exit_event_sp)
3733 {
3734 // Directly broadcast our exited event because we shut down our
3735 // private state thread above
3736 BroadcastEvent(exit_event_sp);
3737 }
3738
Jim Inghamb1e2e842012-04-12 18:49:31 +00003739 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3740 // the last events through the event system, in which case we might strand the write lock. Unlock
3741 // 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 +00003742 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003743 }
Jim Ingham09437922013-03-01 20:04:25 +00003744
3745 m_destroy_in_process = false;
3746
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747 return error;
3748}
3749
3750Error
3751Process::Signal (int signal)
3752{
3753 Error error (WillSignal());
3754 if (error.Success())
3755 {
3756 error = DoSignal(signal);
3757 if (error.Success())
3758 DidSignal();
3759 }
3760 return error;
3761}
3762
Greg Clayton514487e2011-02-15 21:59:32 +00003763lldb::ByteOrder
3764Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765{
Greg Clayton514487e2011-02-15 21:59:32 +00003766 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767}
3768
3769uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003770Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771{
Greg Clayton514487e2011-02-15 21:59:32 +00003772 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773}
3774
Greg Clayton514487e2011-02-15 21:59:32 +00003775
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003776bool
3777Process::ShouldBroadcastEvent (Event *event_ptr)
3778{
3779 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3780 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003781 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003782
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783 switch (state)
3784 {
Greg Claytonb766a732011-02-04 01:58:07 +00003785 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786 case eStateAttaching:
3787 case eStateLaunching:
3788 case eStateDetached:
3789 case eStateExited:
3790 case eStateUnloaded:
3791 // These events indicate changes in the state of the debugging session, always report them.
3792 return_value = true;
3793 break;
3794 case eStateInvalid:
3795 // We stopped for no apparent reason, don't report it.
3796 return_value = false;
3797 break;
3798 case eStateRunning:
3799 case eStateStepping:
3800 // If we've started the target running, we handle the cases where we
3801 // are already running and where there is a transition from stopped to
3802 // running differently.
3803 // running -> running: Automatically suppress extra running events
3804 // stopped -> running: Report except when there is one or more no votes
3805 // and no yes votes.
3806 SynchronouslyNotifyStateChanged (state);
Jim Ingham0161b492013-02-09 01:29:05 +00003807 switch (m_last_broadcast_state)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003808 {
3809 case eStateRunning:
3810 case eStateStepping:
3811 // We always suppress multiple runnings with no PUBLIC stop in between.
3812 return_value = false;
3813 break;
3814 default:
3815 // TODO: make this work correctly. For now always report
3816 // run if we aren't running so we don't miss any runnning
3817 // events. If I run the lldb/test/thread/a.out file and
3818 // break at main.cpp:58, run and hit the breakpoints on
3819 // multiple threads, then somehow during the stepping over
3820 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821
3822 // This is a transition from stop to run.
3823 switch (m_thread_list.ShouldReportRun (event_ptr))
3824 {
3825 case eVoteYes:
3826 case eVoteNoOpinion:
3827 return_value = true;
3828 break;
3829 case eVoteNo:
3830 return_value = false;
3831 break;
3832 }
3833 break;
3834 }
3835 break;
3836 case eStateStopped:
3837 case eStateCrashed:
3838 case eStateSuspended:
3839 {
3840 // We've stopped. First see if we're going to restart the target.
3841 // If we are going to stop, then we always broadcast the event.
3842 // 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 +00003843 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003844
Jim Inghamcb4ca112012-05-16 01:32:14 +00003845 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003846 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003848 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003849 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3850 event_ptr,
3851 StateAsCString(state));
3852 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003853 }
3854 else
3855 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003856 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3857 bool should_resume = false;
3858
Jim Ingham0161b492013-02-09 01:29:05 +00003859 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3860 // Asking the thread list is also not likely to go well, since we are running again.
3861 // So in that case just report the event.
3862
Jim Ingham0161b492013-02-09 01:29:05 +00003863 if (!was_restarted)
3864 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003865
3866 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867 {
Jim Ingham0161b492013-02-09 01:29:05 +00003868 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3869 if (log)
3870 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3871 should_resume,
3872 StateAsCString(state),
3873 was_restarted,
3874 stop_vote);
3875
3876 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877 {
3878 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003879 return_value = true;
3880 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003881 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003882 case eVoteNo:
3883 return_value = false;
3884 break;
3885 }
Jim Ingham0161b492013-02-09 01:29:05 +00003886
Jim Inghamcb95f342012-09-05 21:13:56 +00003887 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003888 {
3889 if (log)
3890 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3891 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003892 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003893 }
3894
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003895 }
3896 else
3897 {
3898 return_value = true;
3899 SynchronouslyNotifyStateChanged (state);
3900 }
3901 }
3902 }
Jim Ingham0161b492013-02-09 01:29:05 +00003903 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003904 }
Jim Ingham0161b492013-02-09 01:29:05 +00003905
3906 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3907 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3908 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3909 // because the PublicState reflects the last event pulled off the queue, and there may be several
3910 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3911 // yet. m_last_broadcast_state gets updated here.
3912
3913 if (return_value)
3914 m_last_broadcast_state = state;
3915
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003916 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003917 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3918 event_ptr,
3919 StateAsCString(state),
3920 StateAsCString(m_last_broadcast_state),
3921 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003922 return return_value;
3923}
3924
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003925
3926bool
Jim Ingham372787f2012-04-07 00:00:41 +00003927Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003928{
Greg Clayton5160ce52013-03-27 23:08:40 +00003929 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930
Greg Clayton8b82f082011-04-12 05:54:46 +00003931 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003932 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003933 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3934
Jim Ingham372787f2012-04-07 00:00:41 +00003935 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003936 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937
3938 // Create a thread that watches our internal state and controls which
3939 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003940 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003941 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003942 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003943 else
Daniel Malead01b2952012-11-29 21:49:15 +00003944 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003945
3946 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003947 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003948 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3949 if (success)
3950 {
3951 ResumePrivateStateThread();
3952 return true;
3953 }
3954 else
3955 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003956}
3957
3958void
3959Process::PausePrivateStateThread ()
3960{
3961 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3962}
3963
3964void
3965Process::ResumePrivateStateThread ()
3966{
3967 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3968}
3969
3970void
3971Process::StopPrivateStateThread ()
3972{
Greg Clayton8b82f082011-04-12 05:54:46 +00003973 if (PrivateStateThreadIsValid ())
3974 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003975 else
3976 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003977 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003978 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003979 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003980 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981}
3982
3983void
3984Process::ControlPrivateStateThread (uint32_t signal)
3985{
Greg Clayton5160ce52013-03-27 23:08:40 +00003986 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003987
3988 assert (signal == eBroadcastInternalStateControlStop ||
3989 signal == eBroadcastInternalStateControlPause ||
3990 signal == eBroadcastInternalStateControlResume);
3991
3992 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003993 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003994
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003995 // Signal the private state thread. First we should copy this is case the
3996 // thread starts exiting since the private state thread will NULL this out
3997 // when it exits
3998 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003999 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004000 {
4001 TimeValue timeout_time;
4002 bool timed_out;
4003
4004 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4005
4006 timeout_time = TimeValue::Now();
4007 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004008 if (log)
4009 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004010 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4011 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4012
4013 if (signal == eBroadcastInternalStateControlStop)
4014 {
4015 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004016 {
4017 Error error;
4018 Host::ThreadCancel (private_state_thread, &error);
4019 if (log)
4020 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4021 }
4022 else
4023 {
4024 if (log)
4025 log->Printf ("The control event killed the private state thread without having to cancel.");
4026 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004027
4028 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004029 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00004030 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004031 }
4032 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004033 else
4034 {
4035 if (log)
4036 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4037 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038}
4039
4040void
Jim Inghamcfc09352012-07-27 23:57:19 +00004041Process::SendAsyncInterrupt ()
4042{
4043 if (PrivateStateThreadIsValid())
4044 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4045 else
4046 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4047}
4048
4049void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050Process::HandlePrivateEvent (EventSP &event_sp)
4051{
Greg Clayton5160ce52013-03-27 23:08:40 +00004052 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004053 m_resume_requested = false;
4054
Jim Inghamaacc3182012-06-06 00:29:30 +00004055 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004056
Greg Clayton414f5d32011-01-25 02:58:48 +00004057 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004058
4059 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004060 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004061 {
Jim Ingham754ab982011-01-29 04:05:41 +00004062 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004063 if (log)
4064 log->Printf ("Ran next event action, result was %d.", action_result);
4065
Jim Inghambb3a2832011-01-29 01:49:25 +00004066 switch (action_result)
4067 {
4068 case NextEventAction::eEventActionSuccess:
4069 SetNextEventAction(NULL);
4070 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004071
Jim Inghambb3a2832011-01-29 01:49:25 +00004072 case NextEventAction::eEventActionRetry:
4073 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004074
Jim Inghambb3a2832011-01-29 01:49:25 +00004075 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004076 // Handle Exiting Here. If we already got an exited event,
4077 // we should just propagate it. Otherwise, swallow this event,
4078 // and set our state to exit so the next event will kill us.
4079 if (new_state != eStateExited)
4080 {
4081 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004082 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004083 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004084 SetNextEventAction(NULL);
4085 return;
4086 }
4087 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004088 break;
4089 }
4090 }
4091
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092 // See if we should broadcast this state to external clients?
4093 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094
4095 if (should_broadcast)
4096 {
4097 if (log)
4098 {
Daniel Malead01b2952012-11-29 21:49:15 +00004099 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004100 __FUNCTION__,
4101 GetID(),
4102 StateAsCString(new_state),
4103 StateAsCString (GetState ()),
4104 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004105 }
Jim Ingham9575d842011-03-11 03:53:59 +00004106 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004107 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004108 PushProcessInputReader ();
Jim Inghamb78d73f2013-05-15 01:21:48 +00004109 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004110 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00004111
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004112 BroadcastEvent (event_sp);
4113 }
4114 else
4115 {
4116 if (log)
4117 {
Daniel Malead01b2952012-11-29 21:49:15 +00004118 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004119 __FUNCTION__,
4120 GetID(),
4121 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004122 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004123 }
4124 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004125 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004126}
4127
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004128thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004129Process::PrivateStateThread (void *arg)
4130{
4131 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004132 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004133 return result;
4134}
4135
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004136thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004137Process::RunPrivateStateThread ()
4138{
Jim Ingham076b3042012-04-10 01:21:57 +00004139 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004140 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004141
Greg Clayton5160ce52013-03-27 23:08:40 +00004142 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004143 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004144 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145
4146 bool exit_now = false;
4147 while (!exit_now)
4148 {
4149 EventSP event_sp;
4150 WaitForEventsPrivate (NULL, event_sp, control_only);
4151 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4152 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004153 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004154 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 +00004155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156 switch (event_sp->GetType())
4157 {
4158 case eBroadcastInternalStateControlStop:
4159 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004160 break; // doing any internal state managment below
4161
4162 case eBroadcastInternalStateControlPause:
4163 control_only = true;
4164 break;
4165
4166 case eBroadcastInternalStateControlResume:
4167 control_only = false;
4168 break;
4169 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004170
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004171 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004172 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004173 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004174 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4175 {
4176 if (m_public_state.GetValue() == eStateAttaching)
4177 {
4178 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004179 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 +00004180 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4181 }
4182 else
4183 {
4184 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004185 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004186 Halt();
4187 }
4188 continue;
4189 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004190
4191 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4192
4193 if (internal_state != eStateInvalid)
4194 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004195 if (m_clear_thread_plans_on_stop &&
4196 StateIsStoppedState(internal_state, true))
4197 {
4198 m_clear_thread_plans_on_stop = false;
4199 m_thread_list.DiscardThreadPlans();
4200 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004201 HandlePrivateEvent (event_sp);
4202 }
4203
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004204 if (internal_state == eStateInvalid ||
4205 internal_state == eStateExited ||
4206 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004207 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004208 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004209 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 +00004210
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004211 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004212 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213 }
4214
Caroline Tice20ad3c42010-10-29 21:48:37 +00004215 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004216 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004217 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004218
Ed Maste64fad602013-07-29 20:58:06 +00004219 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004220 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4221 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004222 return NULL;
4223}
4224
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225//------------------------------------------------------------------
4226// Process Event Data
4227//------------------------------------------------------------------
4228
4229Process::ProcessEventData::ProcessEventData () :
4230 EventData (),
4231 m_process_sp (),
4232 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004233 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004234 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004235 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004236{
4237}
4238
4239Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4240 EventData (),
4241 m_process_sp (process_sp),
4242 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004243 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004244 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004245 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004246{
4247}
4248
4249Process::ProcessEventData::~ProcessEventData()
4250{
4251}
4252
4253const ConstString &
4254Process::ProcessEventData::GetFlavorString ()
4255{
4256 static ConstString g_flavor ("Process::ProcessEventData");
4257 return g_flavor;
4258}
4259
4260const ConstString &
4261Process::ProcessEventData::GetFlavor () const
4262{
4263 return ProcessEventData::GetFlavorString ();
4264}
4265
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004266void
4267Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4268{
4269 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004270 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4271 // the public event queue, then other times when we're pretending that this is where we stopped at the
4272 // end of expression evaluation. m_update_state is used to distinguish these
4273 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004274 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004275 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004276 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004277
Jim Ingham221d51c2013-05-08 00:35:16 +00004278 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004279
4280 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4281 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004282 {
4283 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004284 uint32_t num_threads = curr_thread_list.GetSize();
4285 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004286
Jim Ingham4b536182011-08-09 02:12:22 +00004287 // The actions might change one of the thread's stop_info's opinions about whether we should
4288 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004289
4290 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4291 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4292 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4293 // 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
4294 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004295 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004296 for (idx = 0; idx < num_threads; ++idx)
4297 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4298
Jim Inghamc7078c22012-12-13 22:24:15 +00004299 // Use this to track whether we should continue from here. We will only continue the target running if
4300 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4301 // then it doesn't matter what the other threads say...
4302
4303 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004304
Jim Ingham0ad7e052013-04-25 02:04:59 +00004305 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4306 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4307 // thing to do is, and it's better to let the user decide than continue behind their backs.
4308
4309 bool does_anybody_have_an_opinion = false;
4310
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004311 for (idx = 0; idx < num_threads; ++idx)
4312 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004313 curr_thread_list = m_process_sp->GetThreadList();
4314 if (curr_thread_list.GetSize() != num_threads)
4315 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004316 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004317 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004318 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 +00004319 break;
4320 }
4321
4322 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4323
4324 if (thread_sp->GetIndexID() != thread_index_array[idx])
4325 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004326 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004327 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004328 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004329 idx,
4330 thread_index_array[idx],
4331 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004332 break;
4333 }
4334
Jim Inghamb15bfc72010-10-20 00:39:53 +00004335 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004336 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004337 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004338 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004339 bool this_thread_wants_to_stop;
4340 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004341 {
Jim Ingham0161b492013-02-09 01:29:05 +00004342 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4343 }
4344 else
4345 {
4346 stop_info_sp->PerformAction(event_ptr);
4347 // The stop action might restart the target. If it does, then we want to mark that in the
4348 // event so that whoever is receiving it will know to wait for the running event and reflect
4349 // that state appropriately.
4350 // We also need to stop processing actions, since they aren't expecting the target to be running.
4351
4352 // FIXME: we might have run.
4353 if (stop_info_sp->HasTargetRunSinceMe())
4354 {
4355 SetRestarted (true);
4356 break;
4357 }
4358
4359 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004360 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004361
Jim Inghamc7078c22012-12-13 22:24:15 +00004362 if (still_should_stop == false)
4363 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004364 }
4365 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004366
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004367
Jim Inghama8ca6e22013-05-03 23:04:37 +00004368 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004369 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004370 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004371 {
4372 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004373 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004374 // Use the public resume method here, since this is just
4375 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004376 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004377 }
4378 else
4379 {
4380 // If we didn't restart, run the Stop Hooks here:
4381 // They might also restart the target, so watch for that.
4382 m_process_sp->GetTarget().RunStopHooks();
4383 if (m_process_sp->GetPrivateState() == eStateRunning)
4384 SetRestarted(true);
4385 }
Jim Ingham9575d842011-03-11 03:53:59 +00004386 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004387 }
4388}
4389
4390void
4391Process::ProcessEventData::Dump (Stream *s) const
4392{
4393 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004394 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004395
Greg Clayton8b82f082011-04-12 05:54:46 +00004396 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004397}
4398
4399const Process::ProcessEventData *
4400Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4401{
4402 if (event_ptr)
4403 {
4404 const EventData *event_data = event_ptr->GetData();
4405 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4406 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4407 }
4408 return NULL;
4409}
4410
4411ProcessSP
4412Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4413{
4414 ProcessSP process_sp;
4415 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4416 if (data)
4417 process_sp = data->GetProcessSP();
4418 return process_sp;
4419}
4420
4421StateType
4422Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4423{
4424 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4425 if (data == NULL)
4426 return eStateInvalid;
4427 else
4428 return data->GetState();
4429}
4430
4431bool
4432Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4433{
4434 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4435 if (data == NULL)
4436 return false;
4437 else
4438 return data->GetRestarted();
4439}
4440
4441void
4442Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4443{
4444 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4445 if (data != NULL)
4446 data->SetRestarted(new_value);
4447}
4448
Jim Ingham0161b492013-02-09 01:29:05 +00004449size_t
4450Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4451{
4452 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4453 if (data != NULL)
4454 return data->GetNumRestartedReasons();
4455 else
4456 return 0;
4457}
4458
4459const char *
4460Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4461{
4462 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4463 if (data != NULL)
4464 return data->GetRestartedReasonAtIndex(idx);
4465 else
4466 return NULL;
4467}
4468
4469void
4470Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4471{
4472 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4473 if (data != NULL)
4474 data->AddRestartedReason(reason);
4475}
4476
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004477bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004478Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4479{
4480 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4481 if (data == NULL)
4482 return false;
4483 else
4484 return data->GetInterrupted ();
4485}
4486
4487void
4488Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4489{
4490 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4491 if (data != NULL)
4492 data->SetInterrupted(new_value);
4493}
4494
4495bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004496Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4497{
4498 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4499 if (data)
4500 {
4501 data->SetUpdateStateOnRemoval();
4502 return true;
4503 }
4504 return false;
4505}
4506
Greg Claytond9e416c2012-02-18 05:35:26 +00004507lldb::TargetSP
4508Process::CalculateTarget ()
4509{
4510 return m_target.shared_from_this();
4511}
4512
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004513void
Greg Clayton0603aa92010-10-04 01:05:56 +00004514Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004515{
Greg Claytonc14ee322011-09-22 04:58:26 +00004516 exe_ctx.SetTargetPtr (&m_target);
4517 exe_ctx.SetProcessPtr (this);
4518 exe_ctx.SetThreadPtr(NULL);
4519 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004520}
4521
Greg Claytone996fd32011-03-08 22:40:15 +00004522//uint32_t
4523//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4524//{
4525// return 0;
4526//}
4527//
4528//ArchSpec
4529//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4530//{
4531// return Host::GetArchSpecForExistingProcess (pid);
4532//}
4533//
4534//ArchSpec
4535//Process::GetArchSpecForExistingProcess (const char *process_name)
4536//{
4537// return Host::GetArchSpecForExistingProcess (process_name);
4538//}
4539//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004540void
4541Process::AppendSTDOUT (const char * s, size_t len)
4542{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004543 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004544 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004545 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004546}
4547
4548void
Greg Clayton93e86192011-11-13 04:45:22 +00004549Process::AppendSTDERR (const char * s, size_t len)
4550{
4551 Mutex::Locker locker (m_stdio_communication_mutex);
4552 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004553 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004554}
4555
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004556void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004557Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004558{
4559 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004560 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004561 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4562}
4563
4564size_t
4565Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4566{
4567 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004568 if (m_profile_data.empty())
4569 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004570
4571 std::string &one_profile_data = m_profile_data.front();
4572 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004573 if (bytes_available > 0)
4574 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004575 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004576 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004577 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004578 if (bytes_available > buf_size)
4579 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004580 memcpy(buf, one_profile_data.c_str(), buf_size);
4581 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004582 bytes_available = buf_size;
4583 }
4584 else
4585 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004586 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004587 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004588 }
4589 }
4590 return bytes_available;
4591}
4592
4593
Greg Clayton93e86192011-11-13 04:45:22 +00004594//------------------------------------------------------------------
4595// Process STDIO
4596//------------------------------------------------------------------
4597
4598size_t
4599Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4600{
4601 Mutex::Locker locker(m_stdio_communication_mutex);
4602 size_t bytes_available = m_stdout_data.size();
4603 if (bytes_available > 0)
4604 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004605 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004606 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004607 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004608 if (bytes_available > buf_size)
4609 {
4610 memcpy(buf, m_stdout_data.c_str(), buf_size);
4611 m_stdout_data.erase(0, buf_size);
4612 bytes_available = buf_size;
4613 }
4614 else
4615 {
4616 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4617 m_stdout_data.clear();
4618 }
4619 }
4620 return bytes_available;
4621}
4622
4623
4624size_t
4625Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4626{
4627 Mutex::Locker locker(m_stdio_communication_mutex);
4628 size_t bytes_available = m_stderr_data.size();
4629 if (bytes_available > 0)
4630 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004631 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004632 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004633 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004634 if (bytes_available > buf_size)
4635 {
4636 memcpy(buf, m_stderr_data.c_str(), buf_size);
4637 m_stderr_data.erase(0, buf_size);
4638 bytes_available = buf_size;
4639 }
4640 else
4641 {
4642 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4643 m_stderr_data.clear();
4644 }
4645 }
4646 return bytes_available;
4647}
4648
4649void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004650Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4651{
4652 Process *process = (Process *) baton;
4653 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4654}
4655
4656size_t
4657Process::ProcessInputReaderCallback (void *baton,
4658 InputReader &reader,
4659 lldb::InputReaderAction notification,
4660 const char *bytes,
4661 size_t bytes_len)
4662{
4663 Process *process = (Process *) baton;
4664
4665 switch (notification)
4666 {
4667 case eInputReaderActivate:
4668 break;
4669
4670 case eInputReaderDeactivate:
4671 break;
4672
4673 case eInputReaderReactivate:
4674 break;
4675
Caroline Tice969ed3d2011-05-02 20:41:46 +00004676 case eInputReaderAsynchronousOutputWritten:
4677 break;
4678
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004679 case eInputReaderGotToken:
4680 {
4681 Error error;
4682 process->PutSTDIN (bytes, bytes_len, error);
4683 }
4684 break;
4685
Caroline Ticeefed6132010-11-19 20:47:54 +00004686 case eInputReaderInterrupt:
Jim Inghamfc65a502013-06-19 00:56:17 +00004687 process->SendAsyncInterrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +00004688 break;
4689
4690 case eInputReaderEndOfFile:
4691 process->AppendSTDOUT ("^D", 2);
4692 break;
4693
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004694 case eInputReaderDone:
4695 break;
4696
4697 }
4698
4699 return bytes_len;
4700}
4701
4702void
4703Process::ResetProcessInputReader ()
4704{
4705 m_process_input_reader.reset();
4706}
4707
4708void
Greg Claytonee95ed52011-11-17 22:14:31 +00004709Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004710{
4711 // First set up the Read Thread for reading/handling process I/O
4712
Greg Clayton7b0992d2013-04-18 22:45:39 +00004713 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004714
4715 if (conn_ap.get())
4716 {
4717 m_stdio_communication.SetConnection (conn_ap.release());
4718 if (m_stdio_communication.IsConnected())
4719 {
4720 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4721 m_stdio_communication.StartReadThread();
4722
4723 // Now read thread is set up, set up input reader.
4724
4725 if (!m_process_input_reader.get())
4726 {
4727 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4728 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4729 this,
4730 eInputReaderGranularityByte,
4731 NULL,
4732 NULL,
4733 false));
4734
4735 if (err.Fail())
4736 m_process_input_reader.reset();
4737 }
4738 }
4739 }
4740}
4741
4742void
4743Process::PushProcessInputReader ()
4744{
4745 if (m_process_input_reader && !m_process_input_reader->IsActive())
4746 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4747}
4748
4749void
4750Process::PopProcessInputReader ()
4751{
4752 if (m_process_input_reader && m_process_input_reader->IsActive())
4753 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4754}
4755
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004756// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004757void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004758Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004759{
Greg Clayton67cc0632012-08-22 17:17:09 +00004760// static std::vector<OptionEnumValueElement> g_plugins;
4761//
4762// int i=0;
4763// const char *name;
4764// OptionEnumValueElement option_enum;
4765// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4766// {
4767// if (name)
4768// {
4769// option_enum.value = i;
4770// option_enum.string_value = name;
4771// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4772// g_plugins.push_back (option_enum);
4773// }
4774// ++i;
4775// }
4776// option_enum.value = 0;
4777// option_enum.string_value = NULL;
4778// option_enum.usage = NULL;
4779// g_plugins.push_back (option_enum);
4780//
4781// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4782// {
4783// if (::strcmp (name, "plugin") == 0)
4784// {
4785// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4786// break;
4787// }
4788// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004789//
Greg Clayton6920b522012-08-22 18:39:03 +00004790 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004791}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004792
Greg Clayton99d0faf2010-11-18 23:32:35 +00004793void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004794Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004795{
Greg Clayton6920b522012-08-22 18:39:03 +00004796 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004797}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004798
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004799ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004800Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004801 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004802 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004803 Stream &errors)
4804{
4805 ExecutionResults return_value = eExecutionSetupError;
4806
Jim Ingham77787032011-01-20 02:03:18 +00004807 if (thread_plan_sp.get() == NULL)
4808 {
4809 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004810 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004811 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004812
4813 if (!thread_plan_sp->ValidatePlan(NULL))
4814 {
4815 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4816 return eExecutionSetupError;
4817 }
4818
Greg Claytonc14ee322011-09-22 04:58:26 +00004819 if (exe_ctx.GetProcessPtr() != this)
4820 {
4821 errors.Printf("RunThreadPlan called on wrong process.");
4822 return eExecutionSetupError;
4823 }
4824
4825 Thread *thread = exe_ctx.GetThreadPtr();
4826 if (thread == NULL)
4827 {
4828 errors.Printf("RunThreadPlan called with invalid thread.");
4829 return eExecutionSetupError;
4830 }
Jim Ingham77787032011-01-20 02:03:18 +00004831
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004832 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4833 // For that to be true the plan can't be private - since private plans suppress themselves in the
4834 // GetCompletedPlan call.
4835
4836 bool orig_plan_private = thread_plan_sp->GetPrivate();
4837 thread_plan_sp->SetPrivate(false);
4838
Jim Ingham444586b2011-01-24 06:34:17 +00004839 if (m_private_state.GetValue() != eStateStopped)
4840 {
4841 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004842 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004843 }
4844
Jim Ingham66243842011-08-13 00:56:10 +00004845 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004846 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004847 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004848 if (!selected_frame_sp)
4849 {
4850 thread->SetSelectedFrame(0);
4851 selected_frame_sp = thread->GetSelectedFrame();
4852 if (!selected_frame_sp)
4853 {
4854 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4855 return eExecutionSetupError;
4856 }
4857 }
4858
4859 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004860
4861 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4862 // so we should arrange to reset them as well.
4863
Greg Claytonc14ee322011-09-22 04:58:26 +00004864 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004865
Jim Ingham66243842011-08-13 00:56:10 +00004866 uint32_t selected_tid;
4867 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004868 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004869 {
4870 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004871 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004872 }
4873 else
4874 {
4875 selected_tid = LLDB_INVALID_THREAD_ID;
4876 }
4877
Jim Ingham372787f2012-04-07 00:00:41 +00004878 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004879 lldb::StateType old_state;
4880 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004881
Greg Clayton5160ce52013-03-27 23:08:40 +00004882 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004883 if (Host::GetCurrentThread() == m_private_state_thread)
4884 {
Jim Ingham076b3042012-04-10 01:21:57 +00004885 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4886 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004887 // 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 +00004888 // we are fielding public events here.
4889 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004890 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 +00004891
4892
Jim Ingham372787f2012-04-07 00:00:41 +00004893 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004894
4895 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4896 // returning control here.
4897 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4898 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4899 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4900 // do just what we want.
4901 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4902 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4903 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4904 old_state = m_public_state.GetValue();
4905 m_public_state.SetValueNoLock(eStateStopped);
4906
4907 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004908 StartPrivateStateThread(true);
4909 }
4910
4911 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004912
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004913 if (options.GetDebug())
4914 {
4915 // In this case, we aren't actually going to run, we just want to stop right away.
4916 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4917 // FIXME: To make this prettier we should invent some stop reason for this, but that
4918 // is only cosmetic, and this functionality is only of use to lldb developers who can
4919 // live with not pretty...
4920 thread->Flush();
4921 return eExecutionStoppedForDebug;
4922 }
4923
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004924 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004925
Sean Callanana46ec452012-07-11 21:31:24 +00004926 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004927
Jim Ingham77787032011-01-20 02:03:18 +00004928 {
Sean Callanana46ec452012-07-11 21:31:24 +00004929 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4930 // restored on exit to the function.
4931 //
4932 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4933 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004934
Sean Callanana46ec452012-07-11 21:31:24 +00004935 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004936
Jim Inghamf48169b2010-11-30 02:22:11 +00004937 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004938 {
4939 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004940 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004941 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004942 thread->GetIndexID(),
4943 thread->GetID(),
4944 s.GetData());
4945 }
4946
4947 bool got_event;
4948 lldb::EventSP event_sp;
4949 lldb::StateType stop_state = lldb::eStateInvalid;
4950
4951 TimeValue* timeout_ptr = NULL;
4952 TimeValue real_timeout;
4953
Jim Ingham0161b492013-02-09 01:29:05 +00004954 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 +00004955 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004956 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004957 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00004958
Jim Ingham0161b492013-02-09 01:29:05 +00004959 // This is just for accounting:
4960 uint32_t num_resumes = 0;
4961
4962 TimeValue one_thread_timeout = TimeValue::Now();
4963 TimeValue final_timeout = one_thread_timeout;
4964
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004965 uint32_t timeout_usec = options.GetTimeoutUsec();
4966 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00004967 {
4968 // If we are running all threads then we take half the time to run all threads, bounded by
4969 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004970 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00004971 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4972 else
4973 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00004974 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00004975 if (computed_timeout > default_one_thread_timeout_usec)
4976 computed_timeout = default_one_thread_timeout_usec;
4977 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4978 }
4979 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4980 }
4981 else
4982 {
4983 if (timeout_usec != 0)
4984 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4985 }
4986
Jim Ingham8559a352012-11-26 23:52:18 +00004987 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4988 // So don't call return anywhere within it.
4989
Sean Callanana46ec452012-07-11 21:31:24 +00004990 while (1)
4991 {
4992 // We usually want to resume the process if we get to the top of the loop.
4993 // The only exception is if we get two running events with no intervening
4994 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004995 if (log)
4996 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4997 do_resume,
4998 handle_running_event,
4999 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00005000
Jim Ingham184e9812013-01-15 02:47:48 +00005001 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005002 {
5003 // Do the initial resume and wait for the running event before going further.
5004
Jim Ingham184e9812013-01-15 02:47:48 +00005005 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005006 {
Jim Ingham0161b492013-02-09 01:29:05 +00005007 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005008 Error resume_error = PrivateResume ();
5009 if (!resume_error.Success())
5010 {
Jim Ingham0161b492013-02-09 01:29:05 +00005011 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5012 num_resumes,
5013 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00005014 return_value = eExecutionSetupError;
5015 break;
5016 }
Sean Callanana46ec452012-07-11 21:31:24 +00005017 }
Sean Callanana46ec452012-07-11 21:31:24 +00005018
Jim Ingham0161b492013-02-09 01:29:05 +00005019 TimeValue resume_timeout = TimeValue::Now();
5020 resume_timeout.OffsetWithMicroSeconds(500000);
5021
5022 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005023 if (!got_event)
5024 {
5025 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005026 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5027 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005028
Jim Ingham0161b492013-02-09 01:29:05 +00005029 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005030 return_value = eExecutionSetupError;
5031 break;
5032 }
5033
5034 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005035
Sean Callanana46ec452012-07-11 21:31:24 +00005036 if (stop_state != eStateRunning)
5037 {
Jim Ingham0161b492013-02-09 01:29:05 +00005038 bool restarted = false;
5039
5040 if (stop_state == eStateStopped)
5041 {
5042 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5043 if (log)
5044 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5045 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5046 num_resumes,
5047 StateAsCString(stop_state),
5048 restarted,
5049 do_resume,
5050 handle_running_event);
5051 }
5052
5053 if (restarted)
5054 {
5055 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5056 // event here. But if I do, the best thing is to Halt and then get out of here.
5057 Halt();
5058 }
5059
Jim Ingham35e1bda2012-10-16 21:41:58 +00005060 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5061 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00005062 return_value = eExecutionSetupError;
5063 break;
5064 }
5065
5066 if (log)
5067 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5068 // We need to call the function synchronously, so spin waiting for it to return.
5069 // If we get interrupted while executing, we're going to lose our context, and
5070 // won't be able to gather the result at this point.
5071 // We set the timeout AFTER the resume, since the resume takes some time and we
5072 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005073 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005074 else
5075 {
Sean Callanana46ec452012-07-11 21:31:24 +00005076 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005077 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005078 }
Jim Ingham0161b492013-02-09 01:29:05 +00005079
5080 if (before_first_timeout)
5081 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005082 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005083 timeout_ptr = &one_thread_timeout;
5084 else
5085 {
5086 if (timeout_usec == 0)
5087 timeout_ptr = NULL;
5088 else
5089 timeout_ptr = &final_timeout;
5090 }
5091 }
5092 else
5093 {
5094 if (timeout_usec == 0)
5095 timeout_ptr = NULL;
5096 else
5097 timeout_ptr = &final_timeout;
5098 }
5099
5100 do_resume = true;
5101 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005102
Sean Callanana46ec452012-07-11 21:31:24 +00005103 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005104 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005105
Jim Ingham0f16e732011-02-08 05:20:59 +00005106 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005107 {
Sean Callanana46ec452012-07-11 21:31:24 +00005108 if (timeout_ptr)
5109 {
Matt Kopec676a4872013-02-21 23:55:31 +00005110 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005111 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5112 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005113 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005114 else
Sean Callanana46ec452012-07-11 21:31:24 +00005115 {
5116 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5117 }
5118 }
5119
5120 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5121
5122 if (got_event)
5123 {
5124 if (event_sp.get())
5125 {
5126 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005127 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005128 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005129 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005130 return_value = eExecutionInterrupted;
5131 errors.Printf ("Execution halted by user interrupt.");
5132 if (log)
5133 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005134 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005135 }
5136 else
5137 {
5138 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5139 if (log)
5140 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5141
5142 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005143 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005144 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005145 {
Jim Ingham0161b492013-02-09 01:29:05 +00005146 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005147 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5148 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005149 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005150 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005151 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005152 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5153 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005154 }
5155 else
5156 {
Jim Ingham0161b492013-02-09 01:29:05 +00005157 // If we were restarted, we just need to go back up to fetch another event.
5158 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005159 {
5160 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005161 {
5162 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5163 }
5164 keep_going = true;
5165 do_resume = false;
5166 handle_running_event = true;
5167
Jim Inghamcfc09352012-07-27 23:57:19 +00005168 }
5169 else
5170 {
Jim Ingham0161b492013-02-09 01:29:05 +00005171
5172 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5173 StopReason stop_reason = eStopReasonInvalid;
5174 if (stop_info_sp)
5175 stop_reason = stop_info_sp->GetStopReason();
5176
5177
5178 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5179 // it is OUR plan that is complete?
5180 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005181 {
5182 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005183 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5184 // Now mark this plan as private so it doesn't get reported as the stop reason
5185 // after this point.
5186 if (thread_plan_sp)
5187 thread_plan_sp->SetPrivate (orig_plan_private);
5188 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005189 }
5190 else
5191 {
Jim Ingham0161b492013-02-09 01:29:05 +00005192 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005193 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005194 {
5195 if (log)
5196 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005197 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005198 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005199 {
5200 event_to_broadcast_sp = event_sp;
5201 }
Jim Ingham0161b492013-02-09 01:29:05 +00005202 }
Jim Ingham184e9812013-01-15 02:47:48 +00005203 else
Jim Ingham0161b492013-02-09 01:29:05 +00005204 {
5205 if (log)
5206 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005207 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005208 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005209 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005210 }
Jim Ingham184e9812013-01-15 02:47:48 +00005211 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005212 }
Sean Callanana46ec452012-07-11 21:31:24 +00005213 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005214 }
5215 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005216
Jim Inghamcfc09352012-07-27 23:57:19 +00005217 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005218 // This shouldn't really happen, but sometimes we do get two running events without an
5219 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005220 do_resume = false;
5221 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005222 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005223 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005224
Jim Inghamcfc09352012-07-27 23:57:19 +00005225 default:
5226 if (log)
5227 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5228
5229 if (stop_state == eStateExited)
5230 event_to_broadcast_sp = event_sp;
5231
Sean Callananbf154da2012-08-08 17:35:10 +00005232 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005233 return_value = eExecutionInterrupted;
5234 break;
5235 }
Sean Callanana46ec452012-07-11 21:31:24 +00005236 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005237
Sean Callanana46ec452012-07-11 21:31:24 +00005238 if (keep_going)
5239 continue;
5240 else
5241 break;
5242 }
5243 else
5244 {
5245 if (log)
5246 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5247 return_value = eExecutionInterrupted;
5248 break;
5249 }
5250 }
5251 else
5252 {
5253 // If we didn't get an event that means we've timed out...
5254 // We will interrupt the process here. Depending on what we were asked to do we will
5255 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005256
5257 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005258 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005259 {
Jim Ingham0161b492013-02-09 01:29:05 +00005260 uint64_t remaining_time = final_timeout - TimeValue::Now();
5261 if (before_first_timeout)
5262 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005263 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005264 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005265 else
5266 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005267 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005268 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005269 }
5270 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005271 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005272 "abandoning execution.",
5273 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005274 }
5275
Jim Ingham0161b492013-02-09 01:29:05 +00005276 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5277 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5278 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5279 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5280 // stopped event. That's what this while loop does.
5281
5282 bool back_to_top = true;
5283 uint32_t try_halt_again = 0;
5284 bool do_halt = true;
5285 const uint32_t num_retries = 5;
5286 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005287 {
Jim Ingham0161b492013-02-09 01:29:05 +00005288 Error halt_error;
5289 if (do_halt)
5290 {
5291 if (log)
5292 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5293 halt_error = Halt();
5294 }
5295 if (halt_error.Success())
5296 {
5297 if (log)
5298 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5299
5300 real_timeout = TimeValue::Now();
5301 real_timeout.OffsetWithMicroSeconds(500000);
5302
5303 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005304
Jim Ingham0161b492013-02-09 01:29:05 +00005305 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005306 {
Jim Ingham0161b492013-02-09 01:29:05 +00005307 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5308 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005309 {
Jim Ingham0161b492013-02-09 01:29:05 +00005310 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5311 if (stop_state == lldb::eStateStopped
5312 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5313 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005314 }
5315
Jim Ingham0161b492013-02-09 01:29:05 +00005316 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005317 {
Jim Ingham0161b492013-02-09 01:29:05 +00005318 // Between the time we initiated the Halt and the time we delivered it, the process could have
5319 // already finished its job. Check that here:
5320
5321 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5322 {
5323 if (log)
5324 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5325 "Exiting wait loop.");
5326 return_value = eExecutionCompleted;
5327 back_to_top = false;
5328 break;
5329 }
5330
5331 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5332 {
5333 if (log)
5334 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5335 "Exiting wait loop.");
5336 try_halt_again++;
5337 do_halt = false;
5338 continue;
5339 }
Sean Callanana46ec452012-07-11 21:31:24 +00005340
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005341 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005342 {
5343 if (log)
5344 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5345 return_value = eExecutionInterrupted;
5346 back_to_top = false;
5347 break;
5348 }
5349
5350 if (before_first_timeout)
5351 {
5352 // Set all the other threads to run, and return to the top of the loop, which will continue;
5353 before_first_timeout = false;
5354 thread_plan_sp->SetStopOthers (false);
5355 if (log)
5356 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005357
Jim Ingham0161b492013-02-09 01:29:05 +00005358 back_to_top = true;
5359 break;
5360 }
5361 else
5362 {
5363 // Running all threads failed, so return Interrupted.
5364 if (log)
5365 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5366 return_value = eExecutionInterrupted;
5367 back_to_top = false;
5368 break;
5369 }
Sean Callanana46ec452012-07-11 21:31:24 +00005370 }
5371 }
5372 else
Jim Ingham0161b492013-02-09 01:29:05 +00005373 { if (log)
5374 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5375 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005376 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005377 back_to_top = false;
5378 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005379 }
5380 }
Jim Ingham0161b492013-02-09 01:29:05 +00005381 else
5382 {
5383 try_halt_again++;
5384 continue;
5385 }
Sean Callanana46ec452012-07-11 21:31:24 +00005386 }
Jim Ingham0161b492013-02-09 01:29:05 +00005387
5388 if (!back_to_top || try_halt_again > num_retries)
5389 break;
5390 else
5391 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005392 }
Sean Callanana46ec452012-07-11 21:31:24 +00005393 } // END WAIT LOOP
5394
5395 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5396 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5397 {
5398 StopPrivateStateThread();
5399 Error error;
5400 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005401 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005402 {
5403 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5404 }
5405 m_public_state.SetValueNoLock(old_state);
5406
5407 }
5408
Jim Ingham184e9812013-01-15 02:47:48 +00005409 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5410 // could happen:
5411 // 1) The execution successfully completed
5412 // 2) We hit a breakpoint, and ignore_breakpoints was true
5413 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005414 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5415 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005416
Jim Ingham184e9812013-01-15 02:47:48 +00005417 if (return_value == eExecutionCompleted
5418 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005419 {
5420 thread_plan_sp->RestoreThreadState();
5421 }
Sean Callanana46ec452012-07-11 21:31:24 +00005422
5423 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005424 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005425 {
5426 if (log)
5427 {
5428 StreamString s;
5429 if (event_sp)
5430 event_sp->Dump (&s);
5431 else
5432 {
5433 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5434 }
5435
5436 StreamString ts;
5437
5438 const char *event_explanation = NULL;
5439
5440 do
5441 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005442 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005443 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005444 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005445 break;
5446 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005447 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005448 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005449 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005450 break;
5451 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005452 else
Sean Callanana46ec452012-07-11 21:31:24 +00005453 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005454 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5455
5456 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005457 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005458 event_explanation = "<no event data>";
5459 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005460 }
5461
Jim Inghamcfc09352012-07-27 23:57:19 +00005462 Process *process = event_data->GetProcessSP().get();
5463
5464 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005465 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005466 event_explanation = "<no process>";
5467 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005468 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005469
5470 ThreadList &thread_list = process->GetThreadList();
5471
5472 uint32_t num_threads = thread_list.GetSize();
5473 uint32_t thread_index;
5474
5475 ts.Printf("<%u threads> ", num_threads);
5476
5477 for (thread_index = 0;
5478 thread_index < num_threads;
5479 ++thread_index)
5480 {
5481 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5482
5483 if (!thread)
5484 {
5485 ts.Printf("<?> ");
5486 continue;
5487 }
5488
Daniel Malead01b2952012-11-29 21:49:15 +00005489 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005490 RegisterContext *register_context = thread->GetRegisterContext().get();
5491
5492 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005493 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005494 else
5495 ts.Printf("[ip unknown] ");
5496
5497 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5498 if (stop_info_sp)
5499 {
5500 const char *stop_desc = stop_info_sp->GetDescription();
5501 if (stop_desc)
5502 ts.PutCString (stop_desc);
5503 }
5504 ts.Printf(">");
5505 }
5506
5507 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005508 }
Sean Callanana46ec452012-07-11 21:31:24 +00005509 } while (0);
5510
Jim Inghamcfc09352012-07-27 23:57:19 +00005511 if (event_explanation)
5512 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005513 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005514 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5515 }
5516
Jim Inghame4483cf2013-09-27 01:13:01 +00005517 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005518 {
5519 if (log)
5520 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5521 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5522 thread_plan_sp->SetPrivate (orig_plan_private);
5523 }
5524 else
5525 {
5526 if (log)
5527 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005528 }
5529 }
5530 else if (return_value == eExecutionSetupError)
5531 {
5532 if (log)
5533 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005534
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005535 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005536 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005537 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005538 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005539 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005540 }
5541 else
5542 {
Sean Callanana46ec452012-07-11 21:31:24 +00005543 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005544 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005545 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005546 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5547 return_value = eExecutionCompleted;
5548 }
5549 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5550 {
5551 if (log)
5552 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5553 return_value = eExecutionDiscarded;
5554 }
5555 else
5556 {
5557 if (log)
5558 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005559 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005560 {
5561 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005562 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005563 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5564 thread_plan_sp->SetPrivate (orig_plan_private);
5565 }
5566 }
5567 }
5568
5569 // Thread we ran the function in may have gone away because we ran the target
5570 // Check that it's still there, and if it is put it back in the context. Also restore the
5571 // frame in the context if it is still present.
5572 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5573 if (thread)
5574 {
5575 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5576 }
5577
5578 // Also restore the current process'es selected frame & thread, since this function calling may
5579 // be done behind the user's back.
5580
5581 if (selected_tid != LLDB_INVALID_THREAD_ID)
5582 {
5583 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5584 {
5585 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005586 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005587 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005588 if (old_frame_sp)
5589 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005590 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005591 }
5592 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005593
Sean Callanana46ec452012-07-11 21:31:24 +00005594 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005595
Sean Callanana46ec452012-07-11 21:31:24 +00005596 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005597 {
Sean Callanana46ec452012-07-11 21:31:24 +00005598 if (log)
5599 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5600 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005601 }
5602
5603 return return_value;
5604}
5605
5606const char *
5607Process::ExecutionResultAsCString (ExecutionResults result)
5608{
5609 const char *result_name;
5610
5611 switch (result)
5612 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005613 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005614 result_name = "eExecutionCompleted";
5615 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005616 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005617 result_name = "eExecutionDiscarded";
5618 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005619 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005620 result_name = "eExecutionInterrupted";
5621 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005622 case eExecutionHitBreakpoint:
5623 result_name = "eExecutionHitBreakpoint";
5624 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005625 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005626 result_name = "eExecutionSetupError";
5627 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005628 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005629 result_name = "eExecutionTimedOut";
5630 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005631 case eExecutionStoppedForDebug:
5632 result_name = "eExecutionStoppedForDebug";
5633 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005634 }
5635 return result_name;
5636}
5637
Greg Clayton7260f622011-04-18 08:33:37 +00005638void
5639Process::GetStatus (Stream &strm)
5640{
5641 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005642 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005643 {
5644 if (state == eStateExited)
5645 {
5646 int exit_status = GetExitStatus();
5647 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005648 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005649 GetID(),
5650 exit_status,
5651 exit_status,
5652 exit_description ? exit_description : "");
5653 }
5654 else
5655 {
5656 if (state == eStateConnected)
5657 strm.Printf ("Connected to remote target.\n");
5658 else
Daniel Malead01b2952012-11-29 21:49:15 +00005659 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005660 }
5661 }
5662 else
5663 {
Daniel Malead01b2952012-11-29 21:49:15 +00005664 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005665 }
5666}
5667
5668size_t
5669Process::GetThreadStatus (Stream &strm,
5670 bool only_threads_with_stop_reason,
5671 uint32_t start_frame,
5672 uint32_t num_frames,
5673 uint32_t num_frames_with_source)
5674{
5675 size_t num_thread_infos_dumped = 0;
5676
Jim Ingham41f2b942012-09-10 20:50:15 +00005677 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005678 const size_t num_threads = GetThreadList().GetSize();
5679 for (uint32_t i = 0; i < num_threads; i++)
5680 {
5681 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5682 if (thread)
5683 {
5684 if (only_threads_with_stop_reason)
5685 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005686 StopInfoSP stop_info_sp = thread->GetStopInfo();
5687 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005688 continue;
5689 }
5690 thread->GetStatus (strm,
5691 start_frame,
5692 num_frames,
5693 num_frames_with_source);
5694 ++num_thread_infos_dumped;
5695 }
5696 }
5697 return num_thread_infos_dumped;
5698}
5699
Greg Claytona9f40ad2012-02-22 04:37:26 +00005700void
5701Process::AddInvalidMemoryRegion (const LoadRange &region)
5702{
5703 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5704}
5705
5706bool
5707Process::RemoveInvalidMemoryRange (const LoadRange &region)
5708{
5709 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5710}
5711
Jim Ingham372787f2012-04-07 00:00:41 +00005712void
5713Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5714{
5715 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5716}
5717
5718bool
5719Process::RunPreResumeActions ()
5720{
5721 bool result = true;
5722 while (!m_pre_resume_actions.empty())
5723 {
5724 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5725 m_pre_resume_actions.pop_back();
5726 bool this_result = action.callback (action.baton);
5727 if (result == true) result = this_result;
5728 }
5729 return result;
5730}
5731
5732void
5733Process::ClearPreResumeActions ()
5734{
5735 m_pre_resume_actions.clear();
5736}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005737
Greg Claytonfa559e52012-05-18 02:38:05 +00005738void
5739Process::Flush ()
5740{
5741 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005742 m_extended_thread_list.Flush();
5743 m_extended_thread_stop_id = 0;
5744 m_queue_list.Clear();
5745 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005746}
Greg Clayton90ba8112012-12-05 00:16:59 +00005747
5748void
5749Process::DidExec ()
5750{
5751 Target &target = GetTarget();
5752 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005753 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005754 m_dynamic_checkers_ap.reset();
5755 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005756 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005757 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005758 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005759 m_image_tokens.clear();
5760 m_allocated_memory_cache.Clear();
5761 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005762 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005763 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005764 DoDidExec();
5765 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005766 // Flush the process (threads and all stack frames) after running CompleteAttach()
5767 // in case the dynamic loader loaded things in new locations.
5768 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005769
5770 // After we figure out what was loaded/unloaded in CompleteAttach,
5771 // we need to let the target know so it can do any cleanup it needs to.
5772 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005773}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005774