blob: 950df69152f7edfcaba048bd7670dd92fb9cabd9 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000038#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039#include "lldb/Target/Target.h"
40#include "lldb/Target/TargetList.h"
41#include "lldb/Target/Thread.h"
42#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000043#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Charles Davis510938e2013-08-27 05:04:57 +000045#ifndef LLDB_DISABLE_POSIX
46#include <spawn.h>
47#endif
48
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049using namespace lldb;
50using namespace lldb_private;
51
Greg Clayton67cc0632012-08-22 17:17:09 +000052
53// Comment out line below to disable memory caching, overriding the process setting
54// target.process.disable-memory-cache
55#define ENABLE_MEMORY_CACHING
56
57#ifdef ENABLE_MEMORY_CACHING
58#define DISABLE_MEM_CACHE_DEFAULT false
59#else
60#define DISABLE_MEM_CACHE_DEFAULT true
61#endif
62
63class ProcessOptionValueProperties : public OptionValueProperties
64{
65public:
66 ProcessOptionValueProperties (const ConstString &name) :
67 OptionValueProperties (name)
68 {
69 }
70
71 // This constructor is used when creating ProcessOptionValueProperties when it
72 // is part of a new lldb_private::Process instance. It will copy all current
73 // global property values as needed
74 ProcessOptionValueProperties (ProcessProperties *global_properties) :
75 OptionValueProperties(*global_properties->GetValueProperties())
76 {
77 }
78
79 virtual const Property *
80 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
81 {
82 // When gettings the value for a key from the process options, we will always
83 // try and grab the setting from the current process if there is one. Else we just
84 // use the one from this instance.
85 if (exe_ctx)
86 {
87 Process *process = exe_ctx->GetProcessPtr();
88 if (process)
89 {
90 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
91 if (this != instance_properties)
92 return instance_properties->ProtectedGetPropertyAtIndex (idx);
93 }
94 }
95 return ProtectedGetPropertyAtIndex (idx);
96 }
97};
98
99static PropertyDefinition
100g_properties[] =
101{
102 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Ingham8c3f2762012-11-29 00:41:12 +0000103 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
104 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000105 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
106 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Claytone1e835c2012-11-29 18:48:47 +0000107 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham29950772013-01-26 02:19:28 +0000108 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Jim Inghamacff8952013-05-02 00:27:30 +0000109 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000110 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
111};
112
113enum {
114 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000115 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000116 ePropertyIgnoreBreakpointsInExpressions,
117 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000118 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000119 ePropertyStopOnSharedLibraryEvents,
120 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000121};
122
123ProcessProperties::ProcessProperties (bool is_global) :
124 Properties ()
125{
126 if (is_global)
127 {
128 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
129 m_collection_sp->Initialize(g_properties);
130 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000131 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000132 true,
133 Thread::GetGlobalProperties()->GetValueProperties());
134 }
135 else
136 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
137}
138
139ProcessProperties::~ProcessProperties()
140{
141}
142
143bool
144ProcessProperties::GetDisableMemoryCache() const
145{
146 const uint32_t idx = ePropertyDisableMemCache;
147 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
148}
149
150Args
151ProcessProperties::GetExtraStartupCommands () const
152{
153 Args args;
154 const uint32_t idx = ePropertyExtraStartCommand;
155 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
156 return args;
157}
158
159void
160ProcessProperties::SetExtraStartupCommands (const Args &args)
161{
162 const uint32_t idx = ePropertyExtraStartCommand;
163 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
164}
165
Greg Claytonc9d645d2012-10-18 22:40:37 +0000166FileSpec
167ProcessProperties::GetPythonOSPluginPath () const
168{
169 const uint32_t idx = ePropertyPythonOSPluginPath;
170 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
171}
172
173void
174ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
175{
176 const uint32_t idx = ePropertyPythonOSPluginPath;
177 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
178}
179
Jim Ingham184e9812013-01-15 02:47:48 +0000180
181bool
182ProcessProperties::GetIgnoreBreakpointsInExpressions () const
183{
184 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
185 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
186}
187
188void
189ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
190{
191 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
192 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
193}
194
195bool
196ProcessProperties::GetUnwindOnErrorInExpressions () const
197{
198 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
199 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
200}
201
202void
203ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
204{
205 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
206 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
207}
208
Jim Ingham29950772013-01-26 02:19:28 +0000209bool
210ProcessProperties::GetStopOnSharedLibraryEvents () const
211{
212 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
213 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
214}
215
216void
217ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
218{
219 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
220 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
221}
222
Jim Inghamacff8952013-05-02 00:27:30 +0000223bool
224ProcessProperties::GetDetachKeepsStopped () const
225{
226 const uint32_t idx = ePropertyDetachKeepsStopped;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
228}
229
230void
231ProcessProperties::SetDetachKeepsStopped (bool stop)
232{
233 const uint32_t idx = ePropertyDetachKeepsStopped;
234 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
235}
236
Greg Clayton32e0a752011-03-30 18:16:51 +0000237void
Greg Clayton8b82f082011-04-12 05:54:46 +0000238ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000239{
240 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000241 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000242 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000243
244 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000245 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000246
247 if (m_executable)
248 {
249 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
250 s.PutCString (" file = ");
251 m_executable.Dump(&s);
252 s.EOL();
253 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000254 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000255 if (argc > 0)
256 {
257 for (uint32_t i=0; i<argc; i++)
258 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000259 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000260 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000261 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000262 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000263 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000264 }
265 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000266
267 const uint32_t envc = m_environment.GetArgumentCount();
268 if (envc > 0)
269 {
270 for (uint32_t i=0; i<envc; i++)
271 {
272 const char *env = m_environment.GetArgumentAtIndex(i);
273 if (i < 10)
274 s.Printf (" env[%u] = %s\n", i, env);
275 else
276 s.Printf ("env[%u] = %s\n", i, env);
277 }
278 }
279
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000280 if (m_arch.IsValid())
281 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
282
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000284 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000285 cstr = platform->GetUserName (m_uid);
286 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000287 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000289 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 cstr = platform->GetGroupName (m_gid);
291 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000292 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000294 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000295 cstr = platform->GetUserName (m_euid);
296 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000297 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000299 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 cstr = platform->GetGroupName (m_egid);
301 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000302 }
303}
304
305void
Greg Clayton8b82f082011-04-12 05:54:46 +0000306ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000307{
Greg Clayton8b82f082011-04-12 05:54:46 +0000308 const char *label;
309 if (show_args || verbose)
310 label = "ARGUMENTS";
311 else
312 label = "NAME";
313
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000314 if (verbose)
315 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000316 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000317 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
318 }
319 else
320 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000322 s.PutCString ("====== ====== ========== ======= ============================\n");
323 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000324}
325
326void
Greg Clayton8b82f082011-04-12 05:54:46 +0000327ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000328{
329 if (m_pid != LLDB_INVALID_PROCESS_ID)
330 {
331 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000332 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000333
Greg Clayton32e0a752011-03-30 18:16:51 +0000334
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000335 if (verbose)
336 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000338 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
339 s.Printf ("%-10s ", cstr);
340 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000341 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000342
Greg Clayton8b82f082011-04-12 05:54:46 +0000343 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000344 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
345 s.Printf ("%-10s ", cstr);
346 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000348
Greg Clayton8b82f082011-04-12 05:54:46 +0000349 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000350 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
351 s.Printf ("%-10s ", cstr);
352 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000353 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000354
Greg Clayton8b82f082011-04-12 05:54:46 +0000355 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000356 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
357 s.Printf ("%-10s ", cstr);
358 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000359 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000360 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
361 }
362 else
363 {
Jason Molendafd54b362011-09-20 21:44:10 +0000364 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000365 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000366 (int)m_arch.GetTriple().getArchName().size(),
367 m_arch.GetTriple().getArchName().data());
368 }
369
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000371 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 if (argc > 0)
374 {
375 for (uint32_t i=0; i<argc; i++)
376 {
377 if (i > 0)
378 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000379 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000380 }
381 }
382 }
383 else
384 {
385 s.PutCString (GetName());
386 }
387
388 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000389 }
390}
391
Greg Clayton8b82f082011-04-12 05:54:46 +0000392
393void
Greg Clayton45392552012-10-17 22:57:12 +0000394ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000395{
396 m_arguments.SetArguments (argv);
397
398 // Is the first argument the executable?
399 if (first_arg_is_executable)
400 {
401 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
402 if (first_arg)
403 {
404 // Yes the first argument is an executable, set it as the executable
405 // in the launch options. Don't resolve the file path as the path
406 // could be a remote platform path
407 const bool resolve = false;
408 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000409 }
410 }
411}
412void
Greg Clayton45392552012-10-17 22:57:12 +0000413ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000414{
415 // Copy all arguments
416 m_arguments = args;
417
418 // Is the first argument the executable?
419 if (first_arg_is_executable)
420 {
Greg Clayton982c9762011-11-03 21:22:33 +0000421 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000422 if (first_arg)
423 {
424 // Yes the first argument is an executable, set it as the executable
425 // in the launch options. Don't resolve the file path as the path
426 // could be a remote platform path
427 const bool resolve = false;
428 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 }
430 }
431}
432
Greg Clayton1d885962011-11-08 02:43:13 +0000433void
Greg Claytonee95ed52011-11-17 22:14:31 +0000434ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000435{
436 // If notthing was specified, then check the process for any default
437 // settings that were set with "settings set"
438 if (m_file_actions.empty())
439 {
Greg Clayton1d885962011-11-08 02:43:13 +0000440 if (m_flags.Test(eLaunchFlagDisableSTDIO))
441 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000442 AppendSuppressFileAction (STDIN_FILENO , true, false);
443 AppendSuppressFileAction (STDOUT_FILENO, false, true);
444 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000445 }
446 else
447 {
448 // Check for any values that might have gotten set with any of:
449 // (lldb) settings set target.input-path
450 // (lldb) settings set target.output-path
451 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000452 FileSpec in_path;
453 FileSpec out_path;
454 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000455 if (target)
456 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000457 in_path = target->GetStandardInputPath();
458 out_path = target->GetStandardOutputPath();
459 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000460 }
461
Greg Clayton67cc0632012-08-22 17:17:09 +0000462 if (in_path || out_path || err_path)
463 {
464 char path[PATH_MAX];
465 if (in_path && in_path.GetPath(path, sizeof(path)))
466 AppendOpenFileAction(STDIN_FILENO, path, true, false);
467
468 if (out_path && out_path.GetPath(path, sizeof(path)))
469 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
470
471 if (err_path && err_path.GetPath(path, sizeof(path)))
472 AppendOpenFileAction(STDERR_FILENO, path, false, true);
473 }
474 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000475 {
476 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000477 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000478 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
479 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
480 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
481 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000482 }
483 }
Greg Clayton1d885962011-11-08 02:43:13 +0000484 }
485 }
486}
487
Greg Clayton144f3a92011-11-15 03:53:30 +0000488
489bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000490ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
491 bool localhost,
492 bool will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000493 bool first_arg_is_full_shell_command,
494 int32_t num_resumes)
Greg Clayton144f3a92011-11-15 03:53:30 +0000495{
496 error.Clear();
497
498 if (GetFlags().Test (eLaunchFlagLaunchInShell))
499 {
500 const char *shell_executable = GetShell();
501 if (shell_executable)
502 {
503 char shell_resolved_path[PATH_MAX];
504
505 if (localhost)
506 {
507 FileSpec shell_filespec (shell_executable, true);
508
509 if (!shell_filespec.Exists())
510 {
511 // Resolve the path in case we just got "bash", "sh" or "tcsh"
512 if (!shell_filespec.ResolveExecutableLocation ())
513 {
514 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
515 return false;
516 }
517 }
518 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
519 shell_executable = shell_resolved_path;
520 }
521
Greg Clayton45392552012-10-17 22:57:12 +0000522 const char **argv = GetArguments().GetConstArgumentVector ();
523 if (argv == NULL || argv[0] == NULL)
524 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000525 Args shell_arguments;
526 std::string safe_arg;
527 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000528 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000529 StreamString shell_command;
530 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000531 {
Greg Clayton45392552012-10-17 22:57:12 +0000532 // Add a modified PATH environment variable in case argv[0]
533 // is a relative path
534 const char *argv0 = argv[0];
535 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
536 {
537 // We have a relative path to our executable which may not work if
538 // we just try to run "a.out" (without it being converted to "./a.out")
539 const char *working_dir = GetWorkingDirectory();
Greg Clayton8938f8d2013-02-14 03:54:39 +0000540 // Be sure to put quotes around PATH's value in case any paths have spaces...
541 std::string new_path("PATH=\"");
Greg Clayton45392552012-10-17 22:57:12 +0000542 const size_t empty_path_len = new_path.size();
543
544 if (working_dir && working_dir[0])
545 {
546 new_path += working_dir;
547 }
548 else
549 {
550 char current_working_dir[PATH_MAX];
551 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
552 if (cwd && cwd[0])
553 new_path += cwd;
554 }
555 const char *curr_path = getenv("PATH");
556 if (curr_path)
557 {
558 if (new_path.size() > empty_path_len)
559 new_path += ':';
560 new_path += curr_path;
561 }
Greg Clayton8938f8d2013-02-14 03:54:39 +0000562 new_path += "\" ";
Greg Clayton45392552012-10-17 22:57:12 +0000563 shell_command.PutCString(new_path.c_str());
564 }
565
Greg Claytond1cf11a2012-04-14 01:42:46 +0000566 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000567
Greg Clayton45392552012-10-17 22:57:12 +0000568 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000569 if (GetArchitecture().IsValid())
570 {
571 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000572 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000573 // 1 - stop in shell
574 // 2 - stop in /usr/bin/arch
575 // 3 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000576 SetResumeCount(num_resumes + 1);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000577 }
578 else
579 {
Greg Clayton45392552012-10-17 22:57:12 +0000580 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000581 // 1 - stop in shell
582 // 2 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000583 SetResumeCount(num_resumes);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000584 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000585 }
Greg Clayton45392552012-10-17 22:57:12 +0000586
587 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000588 {
Greg Clayton45392552012-10-17 22:57:12 +0000589 // There should only be one argument that is the shell command itself to be used as is
590 if (argv[0] && !argv[1])
591 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000592 else
Greg Clayton45392552012-10-17 22:57:12 +0000593 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000594 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000595 else
596 {
Greg Clayton45392552012-10-17 22:57:12 +0000597 for (size_t i=0; argv[i] != NULL; ++i)
598 {
599 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
600 shell_command.Printf(" %s", arg);
601 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000602 }
Greg Clayton45392552012-10-17 22:57:12 +0000603 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000604 m_executable.SetFile(shell_executable, false);
605 m_arguments = shell_arguments;
606 return true;
607 }
608 else
609 {
610 error.SetErrorString ("invalid shell path");
611 }
612 }
613 else
614 {
615 error.SetErrorString ("not launching in shell");
616 }
617 return false;
618}
619
620
Greg Clayton32e0a752011-03-30 18:16:51 +0000621bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000622ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
623{
624 if ((read || write) && fd >= 0 && path && path[0])
625 {
626 m_action = eFileActionOpen;
627 m_fd = fd;
628 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000629 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000630 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000631 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000632 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000633 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000634 m_path.assign (path);
635 return true;
636 }
637 else
638 {
639 Clear();
640 }
641 return false;
642}
643
644bool
645ProcessLaunchInfo::FileAction::Close (int fd)
646{
647 Clear();
648 if (fd >= 0)
649 {
650 m_action = eFileActionClose;
651 m_fd = fd;
652 }
653 return m_fd >= 0;
654}
655
656
657bool
658ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
659{
660 Clear();
661 if (fd >= 0 && dup_fd >= 0)
662 {
663 m_action = eFileActionDuplicate;
664 m_fd = fd;
665 m_arg = dup_fd;
666 }
667 return m_fd >= 0;
668}
669
670
671
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000672#ifndef LLDB_DISABLE_POSIX
Greg Clayton8b82f082011-04-12 05:54:46 +0000673bool
Charles Davis510938e2013-08-27 05:04:57 +0000674ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions,
Greg Clayton8b82f082011-04-12 05:54:46 +0000675 const FileAction *info,
676 Log *log,
677 Error& error)
678{
679 if (info == NULL)
680 return false;
681
Charles Davis510938e2013-08-27 05:04:57 +0000682 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
683
Greg Clayton8b82f082011-04-12 05:54:46 +0000684 switch (info->m_action)
685 {
686 case eFileActionNone:
687 error.Clear();
688 break;
689
690 case eFileActionClose:
691 if (info->m_fd == -1)
692 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
693 else
694 {
695 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
696 eErrorTypePOSIX);
697 if (log && (error.Fail() || log))
698 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
699 file_actions, info->m_fd);
700 }
701 break;
702
703 case eFileActionDuplicate:
704 if (info->m_fd == -1)
705 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
706 else if (info->m_arg == -1)
707 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
708 else
709 {
710 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
711 eErrorTypePOSIX);
712 if (log && (error.Fail() || log))
713 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
714 file_actions, info->m_fd, info->m_arg);
715 }
716 break;
717
718 case eFileActionOpen:
719 if (info->m_fd == -1)
720 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
721 else
722 {
723 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000724
Greg Clayton8b82f082011-04-12 05:54:46 +0000725 mode_t mode = 0;
726
Greg Clayton144f3a92011-11-15 03:53:30 +0000727 if (oflag & O_CREAT)
728 mode = 0640;
729
Greg Clayton8b82f082011-04-12 05:54:46 +0000730 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
731 info->m_fd,
732 info->m_path.c_str(),
733 oflag,
734 mode),
735 eErrorTypePOSIX);
736 if (error.Fail() || log)
737 error.PutToLog(log,
738 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
739 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
740 }
741 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000742 }
743 return error.Success();
744}
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000745#endif
Greg Clayton8b82f082011-04-12 05:54:46 +0000746
747Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000748ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000749{
750 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000751 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000752
753 switch (short_option)
754 {
755 case 's': // Stop at program entry point
756 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
757 break;
758
Greg Clayton8b82f082011-04-12 05:54:46 +0000759 case 'i': // STDIN for read only
760 {
761 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000762 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000763 launch_info.AppendFileAction (action);
764 }
765 break;
766
767 case 'o': // Open STDOUT for write only
768 {
769 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000770 if (action.Open (STDOUT_FILENO, option_arg, false, true))
771 launch_info.AppendFileAction (action);
772 }
773 break;
774
775 case 'e': // STDERR for write only
776 {
777 ProcessLaunchInfo::FileAction action;
778 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000779 launch_info.AppendFileAction (action);
780 }
781 break;
782
Greg Clayton9845a8d2012-03-06 04:01:04 +0000783
Greg Clayton8b82f082011-04-12 05:54:46 +0000784 case 'p': // Process plug-in name
785 launch_info.SetProcessPluginName (option_arg);
786 break;
787
788 case 'n': // Disable STDIO
789 {
790 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000791 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000792 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000793 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000794 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000795 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000796 launch_info.AppendFileAction (action);
797 }
798 break;
799
800 case 'w':
801 launch_info.SetWorkingDirectory (option_arg);
802 break;
803
804 case 't': // Open process in new terminal window
805 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
806 break;
807
808 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000809 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
810 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000811 break;
812
813 case 'A':
814 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
815 break;
816
Greg Clayton982c9762011-11-03 21:22:33 +0000817 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000818 if (option_arg && option_arg[0])
819 launch_info.SetShell (option_arg);
820 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000821 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000822 break;
823
Greg Clayton8b82f082011-04-12 05:54:46 +0000824 case 'v':
825 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
826 break;
827
828 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000829 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000830 break;
831
832 }
833 return error;
834}
835
836OptionDefinition
837ProcessLaunchCommandOptions::g_option_table[] =
838{
Virgile Belloe2607b52013-09-05 16:42:23 +0000839{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
840{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
841{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
842{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
843{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
844{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
845{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000846
Virgile Belloe2607b52013-09-05 16:42:23 +0000847{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
848{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
849{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000850
Virgile Belloe2607b52013-09-05 16:42:23 +0000851{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000852
Virgile Belloe2607b52013-09-05 16:42:23 +0000853{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000854
855{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
856};
857
858
859
860bool
861ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000862{
863 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
864 return true;
865 const char *match_name = m_match_info.GetName();
866 if (!match_name)
867 return true;
868
869 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
870}
871
872bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000873ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000874{
875 if (!NameMatches (proc_info.GetName()))
876 return false;
877
878 if (m_match_info.ProcessIDIsValid() &&
879 m_match_info.GetProcessID() != proc_info.GetProcessID())
880 return false;
881
882 if (m_match_info.ParentProcessIDIsValid() &&
883 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
884 return false;
885
Greg Clayton8b82f082011-04-12 05:54:46 +0000886 if (m_match_info.UserIDIsValid () &&
887 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000888 return false;
889
Greg Clayton8b82f082011-04-12 05:54:46 +0000890 if (m_match_info.GroupIDIsValid () &&
891 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000892 return false;
893
894 if (m_match_info.EffectiveUserIDIsValid () &&
895 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
896 return false;
897
898 if (m_match_info.EffectiveGroupIDIsValid () &&
899 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
900 return false;
901
902 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000903 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000904 return false;
905 return true;
906}
907
908bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000909ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000910{
911 if (m_name_match_type != eNameMatchIgnore)
912 return false;
913
914 if (m_match_info.ProcessIDIsValid())
915 return false;
916
917 if (m_match_info.ParentProcessIDIsValid())
918 return false;
919
Greg Clayton8b82f082011-04-12 05:54:46 +0000920 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000921 return false;
922
Greg Clayton8b82f082011-04-12 05:54:46 +0000923 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000924 return false;
925
926 if (m_match_info.EffectiveUserIDIsValid ())
927 return false;
928
929 if (m_match_info.EffectiveGroupIDIsValid ())
930 return false;
931
932 if (m_match_info.GetArchitecture().IsValid())
933 return false;
934
935 if (m_match_all_users)
936 return false;
937
938 return true;
939
940}
941
942void
Greg Clayton8b82f082011-04-12 05:54:46 +0000943ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000944{
945 m_match_info.Clear();
946 m_name_match_type = eNameMatchIgnore;
947 m_match_all_users = false;
948}
Greg Clayton58be07b2011-01-07 06:08:19 +0000949
Greg Claytonc3776bf2012-02-09 06:16:32 +0000950ProcessSP
951Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952{
Greg Clayton949e8222013-01-16 17:29:04 +0000953 static uint32_t g_process_unique_id = 0;
954
Greg Claytonc3776bf2012-02-09 06:16:32 +0000955 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000956 ProcessCreateInstance create_callback = NULL;
957 if (plugin_name)
958 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000959 ConstString const_plugin_name(plugin_name);
960 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 if (create_callback)
962 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000963 process_sp = create_callback(target, listener, crash_file_path);
964 if (process_sp)
965 {
Greg Clayton949e8222013-01-16 17:29:04 +0000966 if (process_sp->CanDebug(target, true))
967 {
968 process_sp->m_process_unique_id = ++g_process_unique_id;
969 }
970 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000971 process_sp.reset();
972 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973 }
974 }
975 else
976 {
Greg Claytonc982c762010-07-09 20:39:50 +0000977 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000979 process_sp = create_callback(target, listener, crash_file_path);
980 if (process_sp)
981 {
Greg Clayton949e8222013-01-16 17:29:04 +0000982 if (process_sp->CanDebug(target, false))
983 {
984 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000985 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000986 }
987 else
988 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000989 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990 }
991 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000992 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993}
994
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000995ConstString &
996Process::GetStaticBroadcasterClass ()
997{
998 static ConstString class_name ("lldb.process");
999 return class_name;
1000}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
1002//----------------------------------------------------------------------
1003// Process constructor
1004//----------------------------------------------------------------------
1005Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +00001006 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001008 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010 m_public_state (eStateUnloaded),
1011 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001012 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1013 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014 m_private_state_listener ("lldb.process.internal_state_listener"),
1015 m_private_state_control_wait(),
1016 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001017 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001018 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001020 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 m_exit_status (-1),
1022 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001023 m_thread_mutex (Mutex::eMutexTypeRecursive),
1024 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +00001026 m_extended_thread_list (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001028 m_image_tokens (),
1029 m_listener (listener),
1030 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001031 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001032 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001033 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001034 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001035 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001036 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001037 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001038 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001039 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1040 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001041 m_memory_cache (*this),
1042 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001043 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001044 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001045 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001046 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001047 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001048 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001049 m_clear_thread_plans_on_stop (false),
Jim Ingham0161b492013-02-09 01:29:05 +00001050 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001051 m_destroy_in_process (false),
1052 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001054 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001055
Greg Clayton5160ce52013-03-27 23:08:40 +00001056 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057 if (log)
1058 log->Printf ("%p Process::Process()", this);
1059
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001060 SetEventName (eBroadcastBitStateChanged, "state-changed");
1061 SetEventName (eBroadcastBitInterrupt, "interrupt");
1062 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1063 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001064 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001065
Greg Clayton35a4cc52012-10-29 20:52:08 +00001066 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1067 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1068 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1069
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 listener.StartListeningForEvents (this,
1071 eBroadcastBitStateChanged |
1072 eBroadcastBitInterrupt |
1073 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001074 eBroadcastBitSTDERR |
1075 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076
1077 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001078 eBroadcastBitStateChanged |
1079 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080
1081 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1082 eBroadcastInternalStateControlStop |
1083 eBroadcastInternalStateControlPause |
1084 eBroadcastInternalStateControlResume);
1085}
1086
1087//----------------------------------------------------------------------
1088// Destructor
1089//----------------------------------------------------------------------
1090Process::~Process()
1091{
Greg Clayton5160ce52013-03-27 23:08:40 +00001092 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093 if (log)
1094 log->Printf ("%p Process::~Process()", this);
1095 StopPrivateStateThread();
1096}
1097
Greg Clayton67cc0632012-08-22 17:17:09 +00001098const ProcessPropertiesSP &
1099Process::GetGlobalProperties()
1100{
1101 static ProcessPropertiesSP g_settings_sp;
1102 if (!g_settings_sp)
1103 g_settings_sp.reset (new ProcessProperties (true));
1104 return g_settings_sp;
1105}
1106
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107void
1108Process::Finalize()
1109{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001110 switch (GetPrivateState())
1111 {
1112 case eStateConnected:
1113 case eStateAttaching:
1114 case eStateLaunching:
1115 case eStateStopped:
1116 case eStateRunning:
1117 case eStateStepping:
1118 case eStateCrashed:
1119 case eStateSuspended:
1120 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001121 {
1122 // FIXME: This will have to be a process setting:
1123 bool keep_stopped = false;
1124 Detach(keep_stopped);
1125 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001126 else
1127 Destroy();
1128 break;
1129
1130 case eStateInvalid:
1131 case eStateUnloaded:
1132 case eStateDetached:
1133 case eStateExited:
1134 break;
1135 }
1136
Greg Clayton1ed54f52011-10-01 00:45:15 +00001137 // Clear our broadcaster before we proceed with destroying
1138 Broadcaster::Clear();
1139
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140 // Do any cleanup needed prior to being destructed... Subclasses
1141 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001142
1143 // We need to destroy the loader before the derived Process class gets destroyed
1144 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001145 m_dynamic_checkers_ap.reset();
1146 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001147 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00001148 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001149 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001150 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001151 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +00001152 m_extended_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001153 std::vector<Notifications> empty_notifications;
1154 m_notifications.swap(empty_notifications);
1155 m_image_tokens.clear();
1156 m_memory_cache.Clear();
1157 m_allocated_memory_cache.Clear();
1158 m_language_runtimes.clear();
1159 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001160//#ifdef LLDB_CONFIGURATION_DEBUG
1161// StreamFile s(stdout, false);
1162// EventSP event_sp;
1163// while (m_private_state_listener.GetNextEvent(event_sp))
1164// {
1165// event_sp->Dump (&s);
1166// s.EOL();
1167// }
1168//#endif
1169 // We have to be very careful here as the m_private_state_listener might
1170 // contain events that have ProcessSP values in them which can keep this
1171 // process around forever. These events need to be cleared out.
1172 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001173 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1174 m_public_run_lock.SetStopped();
1175 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1176 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001177 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178}
1179
1180void
1181Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1182{
1183 m_notifications.push_back(callbacks);
1184 if (callbacks.initialize != NULL)
1185 callbacks.initialize (callbacks.baton, this);
1186}
1187
1188bool
1189Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1190{
1191 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1192 for (pos = m_notifications.begin(); pos != end; ++pos)
1193 {
1194 if (pos->baton == callbacks.baton &&
1195 pos->initialize == callbacks.initialize &&
1196 pos->process_state_changed == callbacks.process_state_changed)
1197 {
1198 m_notifications.erase(pos);
1199 return true;
1200 }
1201 }
1202 return false;
1203}
1204
1205void
1206Process::SynchronouslyNotifyStateChanged (StateType state)
1207{
1208 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1209 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1210 {
1211 if (notification_pos->process_state_changed)
1212 notification_pos->process_state_changed (notification_pos->baton, this, state);
1213 }
1214}
1215
1216// FIXME: We need to do some work on events before the general Listener sees them.
1217// For instance if we are continuing from a breakpoint, we need to ensure that we do
1218// the little "insert real insn, step & stop" trick. But we can't do that when the
1219// event is delivered by the broadcaster - since that is done on the thread that is
1220// waiting for new events, so if we needed more than one event for our handling, we would
1221// stall. So instead we do it when we fetch the event off of the queue.
1222//
1223
1224StateType
1225Process::GetNextEvent (EventSP &event_sp)
1226{
1227 StateType state = eStateInvalid;
1228
1229 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1230 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1231
1232 return state;
1233}
1234
1235
1236StateType
Daniel Malea9e9919f2013-10-09 16:56:28 +00001237Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001238{
Jim Ingham4b536182011-08-09 02:12:22 +00001239 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1240 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1241 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001242 if (event_sp_ptr)
1243 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001244 StateType state = GetState();
1245 // If we are exited or detached, we won't ever get back to any
1246 // other valid state...
1247 if (state == eStateDetached || state == eStateExited)
1248 return state;
1249
Daniel Malea9e9919f2013-10-09 16:56:28 +00001250 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1251 if (log)
1252 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1253
1254 if (!wait_always &&
1255 StateIsStoppedState(state, true) &&
1256 StateIsStoppedState(GetPrivateState(), true)) {
1257 if (log)
1258 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1259 __FUNCTION__);
1260 return state;
1261 }
1262
Jim Ingham4b536182011-08-09 02:12:22 +00001263 while (state != eStateInvalid)
1264 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001265 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001266 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001267 if (event_sp_ptr && event_sp)
1268 *event_sp_ptr = event_sp;
1269
Jim Ingham4b536182011-08-09 02:12:22 +00001270 switch (state)
1271 {
1272 case eStateCrashed:
1273 case eStateDetached:
1274 case eStateExited:
1275 case eStateUnloaded:
1276 return state;
1277 case eStateStopped:
1278 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1279 continue;
1280 else
1281 return state;
1282 default:
1283 continue;
1284 }
1285 }
1286 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001287}
1288
1289
1290StateType
1291Process::WaitForState
1292(
1293 const TimeValue *timeout,
1294 const StateType *match_states, const uint32_t num_match_states
1295)
1296{
1297 EventSP event_sp;
1298 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001299 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300 while (state != eStateInvalid)
1301 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001302 // If we are exited or detached, we won't ever get back to any
1303 // other valid state...
1304 if (state == eStateDetached || state == eStateExited)
1305 return state;
1306
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 state = WaitForStateChangedEvents (timeout, event_sp);
1308
1309 for (i=0; i<num_match_states; ++i)
1310 {
1311 if (match_states[i] == state)
1312 return state;
1313 }
1314 }
1315 return state;
1316}
1317
Jim Ingham30f9b212010-10-11 23:53:14 +00001318bool
1319Process::HijackProcessEvents (Listener *listener)
1320{
1321 if (listener != NULL)
1322 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001323 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001324 }
1325 else
1326 return false;
1327}
1328
1329void
1330Process::RestoreProcessEvents ()
1331{
1332 RestoreBroadcaster();
1333}
1334
Jim Ingham0f16e732011-02-08 05:20:59 +00001335bool
1336Process::HijackPrivateProcessEvents (Listener *listener)
1337{
1338 if (listener != NULL)
1339 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001340 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001341 }
1342 else
1343 return false;
1344}
1345
1346void
1347Process::RestorePrivateProcessEvents ()
1348{
1349 m_private_state_broadcaster.RestoreBroadcaster();
1350}
1351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352StateType
1353Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1354{
Greg Clayton5160ce52013-03-27 23:08:40 +00001355 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356
1357 if (log)
1358 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1359
1360 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001361 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1362 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001363 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001364 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001365 {
1366 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1367 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1368 else if (log)
1369 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1370 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371
1372 if (log)
1373 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1374 __FUNCTION__,
1375 timeout,
1376 StateAsCString(state));
1377 return state;
1378}
1379
1380Event *
1381Process::PeekAtStateChangedEvents ()
1382{
Greg Clayton5160ce52013-03-27 23:08:40 +00001383 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384
1385 if (log)
1386 log->Printf ("Process::%s...", __FUNCTION__);
1387
1388 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001389 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1390 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391 if (log)
1392 {
1393 if (event_ptr)
1394 {
1395 log->Printf ("Process::%s (event_ptr) => %s",
1396 __FUNCTION__,
1397 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1398 }
1399 else
1400 {
1401 log->Printf ("Process::%s no events found",
1402 __FUNCTION__);
1403 }
1404 }
1405 return event_ptr;
1406}
1407
1408StateType
1409Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1410{
Greg Clayton5160ce52013-03-27 23:08:40 +00001411 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001412
1413 if (log)
1414 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1415
1416 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001417 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1418 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001419 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001420 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001421 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1422 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423
1424 // This is a bit of a hack, but when we wait here we could very well return
1425 // to the command-line, and that could disable the log, which would render the
1426 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001428 {
1429 if (state == eStateInvalid)
1430 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1431 else
1432 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1433 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434 return state;
1435}
1436
1437bool
1438Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1439{
Greg Clayton5160ce52013-03-27 23:08:40 +00001440 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441
1442 if (log)
1443 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1444
1445 if (control_only)
1446 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1447 else
1448 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1449}
1450
1451bool
1452Process::IsRunning () const
1453{
1454 return StateIsRunningState (m_public_state.GetValue());
1455}
1456
1457int
1458Process::GetExitStatus ()
1459{
1460 if (m_public_state.GetValue() == eStateExited)
1461 return m_exit_status;
1462 return -1;
1463}
1464
Greg Clayton85851dd2010-12-04 00:10:17 +00001465
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001466const char *
1467Process::GetExitDescription ()
1468{
1469 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1470 return m_exit_string.c_str();
1471 return NULL;
1472}
1473
Greg Clayton6779606a2011-01-22 23:43:18 +00001474bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001475Process::SetExitStatus (int status, const char *cstr)
1476{
Greg Clayton5160ce52013-03-27 23:08:40 +00001477 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001478 if (log)
1479 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1480 status, status,
1481 cstr ? "\"" : "",
1482 cstr ? cstr : "NULL",
1483 cstr ? "\"" : "");
1484
Greg Clayton6779606a2011-01-22 23:43:18 +00001485 // We were already in the exited state
1486 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001487 {
Greg Clayton385d6032011-01-26 23:47:29 +00001488 if (log)
1489 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001490 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001491 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001492
1493 m_exit_status = status;
1494 if (cstr)
1495 m_exit_string = cstr;
1496 else
1497 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498
Greg Clayton6779606a2011-01-22 23:43:18 +00001499 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001500
Greg Clayton6779606a2011-01-22 23:43:18 +00001501 SetPrivateState (eStateExited);
1502 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001503}
1504
1505// This static callback can be used to watch for local child processes on
1506// the current host. The the child process exits, the process will be
1507// found in the global target list (we want to be completely sure that the
1508// lldb_private::Process doesn't go away before we can deliver the signal.
1509bool
Greg Claytone4e45922011-11-16 05:37:56 +00001510Process::SetProcessExitStatus (void *callback_baton,
1511 lldb::pid_t pid,
1512 bool exited,
1513 int signo, // Zero for no signal
1514 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001515)
1516{
Greg Clayton5160ce52013-03-27 23:08:40 +00001517 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001518 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001519 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001520 callback_baton,
1521 pid,
1522 exited,
1523 signo,
1524 exit_status);
1525
1526 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527 {
Greg Clayton66111032010-06-23 01:19:29 +00001528 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001529 if (target_sp)
1530 {
1531 ProcessSP process_sp (target_sp->GetProcessSP());
1532 if (process_sp)
1533 {
1534 const char *signal_cstr = NULL;
1535 if (signo)
1536 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1537
1538 process_sp->SetExitStatus (exit_status, signal_cstr);
1539 }
1540 }
1541 return true;
1542 }
1543 return false;
1544}
1545
1546
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001547void
1548Process::UpdateThreadListIfNeeded ()
1549{
1550 const uint32_t stop_id = GetStopID();
1551 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1552 {
Greg Clayton2637f822011-11-17 01:23:07 +00001553 const StateType state = GetPrivateState();
1554 if (StateIsStoppedState (state, true))
1555 {
1556 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001557 // m_thread_list does have its own mutex, but we need to
1558 // hold onto the mutex between the call to UpdateThreadList(...)
1559 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001560 ThreadList &old_thread_list = m_thread_list;
1561 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001562 ThreadList new_thread_list(this);
1563 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001564 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001565 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001566 {
Jim Ingham09437922013-03-01 20:04:25 +00001567 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1568 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1569 // shutting us down, causing a deadlock.
1570 if (!m_destroy_in_process)
1571 {
1572 OperatingSystem *os = GetOperatingSystem ();
1573 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001574 {
1575 // Clear any old backing threads where memory threads might have been
1576 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001577 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001578 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001579 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001580
1581 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001582 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1583 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1584 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 +00001585 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001586 else
1587 {
1588 // No OS plug-in, the new thread list is the same as the real thread list
1589 new_thread_list = real_thread_list;
1590 }
Jim Ingham09437922013-03-01 20:04:25 +00001591 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001592
1593 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001594 m_thread_list.Update (new_thread_list);
1595 m_thread_list.SetStopID (stop_id);
Greg Clayton9fc13552012-04-10 00:18:59 +00001596 }
Jason Molenda864f1cc2013-11-11 05:20:44 +00001597 // Clear any extended threads that we may have accumulated previously
1598 m_extended_thread_list.Clear();
Greg Clayton2637f822011-11-17 01:23:07 +00001599 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001600 }
1601}
1602
Greg Claytona4d87472013-01-18 23:41:08 +00001603ThreadSP
1604Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1605{
1606 OperatingSystem *os = GetOperatingSystem ();
1607 if (os)
1608 return os->CreateThread(tid, context);
1609 return ThreadSP();
1610}
1611
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001612uint32_t
1613Process::GetNextThreadIndexID (uint64_t thread_id)
1614{
1615 return AssignIndexIDToThread(thread_id);
1616}
1617
1618bool
1619Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1620{
1621 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1622 if (iterator == m_thread_id_to_index_id_map.end())
1623 {
1624 return false;
1625 }
1626 else
1627 {
1628 return true;
1629 }
1630}
1631
1632uint32_t
1633Process::AssignIndexIDToThread(uint64_t thread_id)
1634{
1635 uint32_t result = 0;
1636 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1637 if (iterator == m_thread_id_to_index_id_map.end())
1638 {
1639 result = ++m_thread_index_id;
1640 m_thread_id_to_index_id_map[thread_id] = result;
1641 }
1642 else
1643 {
1644 result = iterator->second;
1645 }
1646
1647 return result;
1648}
1649
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001650StateType
1651Process::GetState()
1652{
1653 // If any other threads access this we will need a mutex for it
1654 return m_public_state.GetValue ();
1655}
1656
1657void
Jim Ingham221d51c2013-05-08 00:35:16 +00001658Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659{
Greg Clayton5160ce52013-03-27 23:08:40 +00001660 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001662 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001663 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001665
1666 // On the transition from Run to Stopped, we unlock the writer end of the
1667 // run lock. The lock gets locked in Resume, which is the public API
1668 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001669 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1670 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001671 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001672 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001673 if (log)
1674 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001675 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001676 }
1677 else
1678 {
1679 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1680 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001681 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001682 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001683 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001684 {
1685 if (log)
1686 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001687 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001688 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001689 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001690 }
1691 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001692}
1693
Jim Ingham3b8285d2012-04-19 01:40:33 +00001694Error
1695Process::Resume ()
1696{
Greg Clayton5160ce52013-03-27 23:08:40 +00001697 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001698 if (log)
1699 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001700 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001701 {
1702 Error error("Resume request failed - process still running.");
1703 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001704 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001705 return error;
1706 }
1707 return PrivateResume();
1708}
1709
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710StateType
1711Process::GetPrivateState ()
1712{
1713 return m_private_state.GetValue();
1714}
1715
1716void
1717Process::SetPrivateState (StateType new_state)
1718{
Greg Clayton5160ce52013-03-27 23:08:40 +00001719 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001720 bool state_changed = false;
1721
1722 if (log)
1723 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1724
Andrew Kaylor29d65742013-05-10 17:19:04 +00001725 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001726 Mutex::Locker locker(m_private_state.GetMutex());
1727
1728 const StateType old_state = m_private_state.GetValueNoLock ();
1729 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001730
Greg Claytonaa49c832013-05-03 22:25:56 +00001731 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1732 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1733 if (old_state_is_stopped != new_state_is_stopped)
1734 {
1735 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001736 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001737 else
Ed Maste64fad602013-07-29 20:58:06 +00001738 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001739 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001740
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741 if (state_changed)
1742 {
1743 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001744 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001746 // Note, this currently assumes that all threads in the list
1747 // stop when the process stops. In the future we will want to
1748 // support a debugging model where some threads continue to run
1749 // while others are stopped. When that happens we will either need
1750 // a way for the thread list to identify which threads are stopping
1751 // or create a special thread list containing only threads which
1752 // actually stopped.
1753 //
1754 // The process plugin is responsible for managing the actual
1755 // behavior of the threads and should have stopped any threads
1756 // that are going to stop before we get here.
1757 m_thread_list.DidStop();
1758
Jim Ingham4b536182011-08-09 02:12:22 +00001759 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001760 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001761 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001762 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001763 }
1764 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001765 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1766 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1767 else
1768 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769 }
1770 else
1771 {
1772 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001773 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001774 }
1775}
1776
Jim Ingham0faa43f2011-11-08 03:00:11 +00001777void
1778Process::SetRunningUserExpression (bool on)
1779{
1780 m_mod_id.SetRunningUserExpression (on);
1781}
1782
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001783addr_t
1784Process::GetImageInfoAddress()
1785{
1786 return LLDB_INVALID_ADDRESS;
1787}
1788
Greg Clayton8f343b02010-11-04 01:54:29 +00001789//----------------------------------------------------------------------
1790// LoadImage
1791//
1792// This function provides a default implementation that works for most
1793// unix variants. Any Process subclasses that need to do shared library
1794// loading differently should override LoadImage and UnloadImage and
1795// do what is needed.
1796//----------------------------------------------------------------------
1797uint32_t
1798Process::LoadImage (const FileSpec &image_spec, Error &error)
1799{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001800 char path[PATH_MAX];
1801 image_spec.GetPath(path, sizeof(path));
1802
Greg Clayton8f343b02010-11-04 01:54:29 +00001803 DynamicLoader *loader = GetDynamicLoader();
1804 if (loader)
1805 {
1806 error = loader->CanLoadImage();
1807 if (error.Fail())
1808 return LLDB_INVALID_IMAGE_TOKEN;
1809 }
1810
1811 if (error.Success())
1812 {
1813 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001814
1815 if (thread_sp)
1816 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001817 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001818
1819 if (frame_sp)
1820 {
1821 ExecutionContext exe_ctx;
1822 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001823 EvaluateExpressionOptions expr_options;
1824 expr_options.SetUnwindOnError(true);
1825 expr_options.SetIgnoreBreakpoints(true);
1826 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001827 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001828 expr.Printf("dlopen (\"%s\", 2)", path);
1829 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001830 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001831 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001832 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001833 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001834 expr.GetData(),
1835 prefix,
1836 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001837 expr_error);
1838 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001839 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001840 error = result_valobj_sp->GetError();
1841 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001842 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001843 Scalar scalar;
1844 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001845 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001846 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1847 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1848 {
1849 uint32_t image_token = m_image_tokens.size();
1850 m_image_tokens.push_back (image_ptr);
1851 return image_token;
1852 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001853 }
1854 }
1855 }
1856 }
1857 }
1858 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001859 if (!error.AsCString())
1860 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001861 return LLDB_INVALID_IMAGE_TOKEN;
1862}
1863
1864//----------------------------------------------------------------------
1865// UnloadImage
1866//
1867// This function provides a default implementation that works for most
1868// unix variants. Any Process subclasses that need to do shared library
1869// loading differently should override LoadImage and UnloadImage and
1870// do what is needed.
1871//----------------------------------------------------------------------
1872Error
1873Process::UnloadImage (uint32_t image_token)
1874{
1875 Error error;
1876 if (image_token < m_image_tokens.size())
1877 {
1878 const addr_t image_addr = m_image_tokens[image_token];
1879 if (image_addr == LLDB_INVALID_ADDRESS)
1880 {
1881 error.SetErrorString("image already unloaded");
1882 }
1883 else
1884 {
1885 DynamicLoader *loader = GetDynamicLoader();
1886 if (loader)
1887 error = loader->CanLoadImage();
1888
1889 if (error.Success())
1890 {
1891 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001892
1893 if (thread_sp)
1894 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001895 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001896
1897 if (frame_sp)
1898 {
1899 ExecutionContext exe_ctx;
1900 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001901 EvaluateExpressionOptions expr_options;
1902 expr_options.SetUnwindOnError(true);
1903 expr_options.SetIgnoreBreakpoints(true);
1904 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001905 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001906 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001907 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001908 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001909 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001910 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001911 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001912 expr.GetData(),
1913 prefix,
1914 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001915 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001916 if (result_valobj_sp->GetError().Success())
1917 {
1918 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001919 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001920 {
1921 if (scalar.UInt(1))
1922 {
1923 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1924 }
1925 else
1926 {
1927 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1928 }
1929 }
1930 }
1931 else
1932 {
1933 error = result_valobj_sp->GetError();
1934 }
1935 }
1936 }
1937 }
1938 }
1939 }
1940 else
1941 {
1942 error.SetErrorString("invalid image token");
1943 }
1944 return error;
1945}
1946
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001947const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948Process::GetABI()
1949{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001950 if (!m_abi_sp)
1951 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1952 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001953}
1954
Jim Ingham22777012010-09-23 02:01:19 +00001955LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001956Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001957{
1958 LanguageRuntimeCollection::iterator pos;
1959 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001960 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001961 {
Jim Inghamab175242012-03-10 00:22:19 +00001962 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001963
Jim Inghamab175242012-03-10 00:22:19 +00001964 m_language_runtimes[language] = runtime_sp;
1965 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001966 }
1967 else
1968 return (*pos).second.get();
1969}
1970
1971CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001972Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001973{
Jim Inghamab175242012-03-10 00:22:19 +00001974 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001975 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1976 return static_cast<CPPLanguageRuntime *> (runtime);
1977 return NULL;
1978}
1979
1980ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001981Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001982{
Jim Inghamab175242012-03-10 00:22:19 +00001983 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001984 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1985 return static_cast<ObjCLanguageRuntime *> (runtime);
1986 return NULL;
1987}
1988
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001989bool
1990Process::IsPossibleDynamicValue (ValueObject& in_value)
1991{
1992 if (in_value.IsDynamic())
1993 return false;
1994 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1995
1996 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1997 {
1998 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1999 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2000 }
2001
2002 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2003 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2004 return true;
2005
2006 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2007 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2008}
2009
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002010BreakpointSiteList &
2011Process::GetBreakpointSiteList()
2012{
2013 return m_breakpoint_site_list;
2014}
2015
2016const BreakpointSiteList &
2017Process::GetBreakpointSiteList() const
2018{
2019 return m_breakpoint_site_list;
2020}
2021
2022
2023void
2024Process::DisableAllBreakpointSites ()
2025{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002026 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2027// bp_site->SetEnabled(true);
2028 DisableBreakpointSite(bp_site);
2029 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002030}
2031
2032Error
2033Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2034{
2035 Error error (DisableBreakpointSiteByID (break_id));
2036
2037 if (error.Success())
2038 m_breakpoint_site_list.Remove(break_id);
2039
2040 return error;
2041}
2042
2043Error
2044Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2045{
2046 Error error;
2047 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2048 if (bp_site_sp)
2049 {
2050 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002051 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002052 }
2053 else
2054 {
Daniel Malead01b2952012-11-29 21:49:15 +00002055 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002056 }
2057
2058 return error;
2059}
2060
2061Error
2062Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2063{
2064 Error error;
2065 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2066 if (bp_site_sp)
2067 {
2068 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002069 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002070 }
2071 else
2072 {
Daniel Malead01b2952012-11-29 21:49:15 +00002073 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 }
2075 return error;
2076}
2077
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002078lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002079Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080{
Greg Clayton92bb12c2011-05-19 18:17:41 +00002081 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002082 if (load_addr != LLDB_INVALID_ADDRESS)
2083 {
2084 BreakpointSiteSP bp_site_sp;
2085
2086 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2087 // create a new breakpoint site and add it.
2088
2089 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2090
2091 if (bp_site_sp)
2092 {
2093 bp_site_sp->AddOwner (owner);
2094 owner->SetBreakpointSite (bp_site_sp);
2095 return bp_site_sp->GetID();
2096 }
2097 else
2098 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002099 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100 if (bp_site_sp)
2101 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002102 Error error = EnableBreakpointSite (bp_site_sp.get());
2103 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104 {
2105 owner->SetBreakpointSite (bp_site_sp);
2106 return m_breakpoint_site_list.Add (bp_site_sp);
2107 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002108 else
2109 {
2110 // Report error for setting breakpoint...
2111 m_target.GetDebugger().GetErrorFile().Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2112 load_addr,
2113 owner->GetBreakpoint().GetID(),
2114 owner->GetID(),
2115 error.AsCString() ? error.AsCString() : "unkown error");
2116 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002117 }
2118 }
2119 }
2120 // We failed to enable the breakpoint
2121 return LLDB_INVALID_BREAK_ID;
2122
2123}
2124
2125void
2126Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2127{
2128 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2129 if (num_owners == 0)
2130 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002131 // Don't try to disable the site if we don't have a live process anymore.
2132 if (IsAlive())
2133 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2135 }
2136}
2137
2138
2139size_t
2140Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2141{
2142 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002143 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144
Jim Ingham20c77192011-06-29 19:42:28 +00002145 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002147 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2148 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002150 addr_t intersect_addr;
2151 size_t intersect_size;
2152 size_t opcode_offset;
2153 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002154 {
2155 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2156 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002157 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002158 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002159 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002160 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002162 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002163 }
2164 return bytes_removed;
2165}
2166
2167
Greg Claytonded470d2011-03-19 01:12:21 +00002168
2169size_t
2170Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2171{
2172 PlatformSP platform_sp (m_target.GetPlatform());
2173 if (platform_sp)
2174 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2175 return 0;
2176}
2177
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002178Error
2179Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2180{
2181 Error error;
2182 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002183 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184 const addr_t bp_addr = bp_site->GetLoadAddress();
2185 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002186 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002187 if (bp_site->IsEnabled())
2188 {
2189 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002190 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 +00002191 return error;
2192 }
2193
2194 if (bp_addr == LLDB_INVALID_ADDRESS)
2195 {
2196 error.SetErrorString("BreakpointSite contains an invalid load address.");
2197 return error;
2198 }
2199 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2200 // trap for the breakpoint site
2201 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2202
2203 if (bp_opcode_size == 0)
2204 {
Daniel Malead01b2952012-11-29 21:49:15 +00002205 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002206 }
2207 else
2208 {
2209 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2210
2211 if (bp_opcode_bytes == NULL)
2212 {
2213 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2214 return error;
2215 }
2216
2217 // Save the original opcode by reading it
2218 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2219 {
2220 // Write a software breakpoint in place of the original opcode
2221 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2222 {
2223 uint8_t verify_bp_opcode_bytes[64];
2224 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2225 {
2226 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2227 {
2228 bp_site->SetEnabled(true);
2229 bp_site->SetType (BreakpointSite::eSoftware);
2230 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002231 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232 bp_site->GetID(),
2233 (uint64_t)bp_addr);
2234 }
2235 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002236 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237 }
2238 else
2239 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2240 }
2241 else
2242 error.SetErrorString("Unable to write breakpoint trap to memory.");
2243 }
2244 else
2245 error.SetErrorString("Unable to read memory at breakpoint address.");
2246 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002247 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002248 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 bp_site->GetID(),
2250 (uint64_t)bp_addr,
2251 error.AsCString());
2252 return error;
2253}
2254
2255Error
2256Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2257{
2258 Error error;
2259 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002260 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002261 addr_t bp_addr = bp_site->GetLoadAddress();
2262 lldb::user_id_t breakID = bp_site->GetID();
2263 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002264 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002265
2266 if (bp_site->IsHardware())
2267 {
2268 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2269 }
2270 else if (bp_site->IsEnabled())
2271 {
2272 const size_t break_op_size = bp_site->GetByteSize();
2273 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2274 if (break_op_size > 0)
2275 {
2276 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002277 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002278 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 bool break_op_found = false;
2280
2281 // Read the breakpoint opcode
2282 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2283 {
2284 bool verify = false;
2285 // Make sure we have the a breakpoint opcode exists at this address
2286 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2287 {
2288 break_op_found = true;
2289 // We found a valid breakpoint opcode at this address, now restore
2290 // the saved opcode.
2291 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2292 {
2293 verify = true;
2294 }
2295 else
2296 error.SetErrorString("Memory write failed when restoring original opcode.");
2297 }
2298 else
2299 {
2300 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2301 // Set verify to true and so we can check if the original opcode has already been restored
2302 verify = true;
2303 }
2304
2305 if (verify)
2306 {
Greg Claytonc982c762010-07-09 20:39:50 +00002307 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002308 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 // Verify that our original opcode made it back to the inferior
2310 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2311 {
2312 // compare the memory we just read with the original opcode
2313 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2314 {
2315 // SUCCESS
2316 bp_site->SetEnabled(false);
2317 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002318 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 +00002319 return error;
2320 }
2321 else
2322 {
2323 if (break_op_found)
2324 error.SetErrorString("Failed to restore original opcode.");
2325 }
2326 }
2327 else
2328 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2329 }
2330 }
2331 else
2332 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2333 }
2334 }
2335 else
2336 {
2337 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002338 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 +00002339 return error;
2340 }
2341
2342 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002343 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 bp_site->GetID(),
2345 (uint64_t)bp_addr,
2346 error.AsCString());
2347 return error;
2348
2349}
2350
Greg Clayton58be07b2011-01-07 06:08:19 +00002351// Uncomment to verify memory caching works after making changes to caching code
2352//#define VERIFY_MEMORY_READS
2353
Sean Callanan64c0cf22012-06-07 22:26:42 +00002354size_t
2355Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2356{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002357 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002358 if (!GetDisableMemoryCache())
2359 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002360#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002361 // Memory caching is enabled, with debug verification
2362
2363 if (buf && size)
2364 {
2365 // Uncomment the line below to make sure memory caching is working.
2366 // I ran this through the test suite and got no assertions, so I am
2367 // pretty confident this is working well. If any changes are made to
2368 // memory caching, uncomment the line below and test your changes!
2369
2370 // Verify all memory reads by using the cache first, then redundantly
2371 // reading the same memory from the inferior and comparing to make sure
2372 // everything is exactly the same.
2373 std::string verify_buf (size, '\0');
2374 assert (verify_buf.size() == size);
2375 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2376 Error verify_error;
2377 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2378 assert (cache_bytes_read == verify_bytes_read);
2379 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2380 assert (verify_error.Success() == error.Success());
2381 return cache_bytes_read;
2382 }
2383 return 0;
2384#else // !defined(VERIFY_MEMORY_READS)
2385 // Memory caching is enabled, without debug verification
2386
2387 return m_memory_cache.Read (addr, buf, size, error);
2388#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002389 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002390 else
2391 {
2392 // Memory caching is disabled
2393
2394 return ReadMemoryFromInferior (addr, buf, size, error);
2395 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002396}
Greg Clayton58be07b2011-01-07 06:08:19 +00002397
Greg Clayton4c82d422012-05-18 23:20:01 +00002398size_t
2399Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2400{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002401 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002402 out_str.clear();
2403 addr_t curr_addr = addr;
2404 while (1)
2405 {
2406 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2407 if (length == 0)
2408 break;
2409 out_str.append(buf, length);
2410 // If we got "length - 1" bytes, we didn't get the whole C string, we
2411 // need to read some more characters
2412 if (length == sizeof(buf) - 1)
2413 curr_addr += length;
2414 else
2415 break;
2416 }
2417 return out_str.size();
2418}
2419
Greg Clayton58be07b2011-01-07 06:08:19 +00002420
2421size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002422Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2423 size_t type_width)
2424{
2425 size_t total_bytes_read = 0;
2426 if (dst && max_bytes && type_width && max_bytes >= type_width)
2427 {
2428 // Ensure a null terminator independent of the number of bytes that is read.
2429 memset (dst, 0, max_bytes);
2430 size_t bytes_left = max_bytes - type_width;
2431
2432 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2433 assert(sizeof(terminator) >= type_width &&
2434 "Attempting to validate a string with more than 4 bytes per character!");
2435
2436 addr_t curr_addr = addr;
2437 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2438 char *curr_dst = dst;
2439
2440 error.Clear();
2441 while (bytes_left > 0 && error.Success())
2442 {
2443 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2444 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2445 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2446
2447 if (bytes_read == 0)
2448 break;
2449
2450 // Search for a null terminator of correct size and alignment in bytes_read
2451 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2452 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2453 if (::strncmp(&dst[i], terminator, type_width) == 0)
2454 {
2455 error.Clear();
2456 return i;
2457 }
2458
2459 total_bytes_read += bytes_read;
2460 curr_dst += bytes_read;
2461 curr_addr += bytes_read;
2462 bytes_left -= bytes_read;
2463 }
2464 }
2465 else
2466 {
2467 if (max_bytes)
2468 error.SetErrorString("invalid arguments");
2469 }
2470 return total_bytes_read;
2471}
2472
2473// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2474// null terminators.
2475size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002476Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002477{
2478 size_t total_cstr_len = 0;
2479 if (dst && dst_max_len)
2480 {
Greg Claytone91b7952011-12-15 03:14:23 +00002481 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002482 // NULL out everything just to be safe
2483 memset (dst, 0, dst_max_len);
2484 Error error;
2485 addr_t curr_addr = addr;
2486 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2487 size_t bytes_left = dst_max_len - 1;
2488 char *curr_dst = dst;
2489
2490 while (bytes_left > 0)
2491 {
2492 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2493 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2494 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2495
2496 if (bytes_read == 0)
2497 {
Greg Claytone91b7952011-12-15 03:14:23 +00002498 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002499 dst[total_cstr_len] = '\0';
2500 break;
2501 }
2502 const size_t len = strlen(curr_dst);
2503
2504 total_cstr_len += len;
2505
2506 if (len < bytes_to_read)
2507 break;
2508
2509 curr_dst += bytes_read;
2510 curr_addr += bytes_read;
2511 bytes_left -= bytes_read;
2512 }
2513 }
Greg Claytone91b7952011-12-15 03:14:23 +00002514 else
2515 {
2516 if (dst == NULL)
2517 result_error.SetErrorString("invalid arguments");
2518 else
2519 result_error.Clear();
2520 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002521 return total_cstr_len;
2522}
2523
2524size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002525Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2526{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527 if (buf == NULL || size == 0)
2528 return 0;
2529
2530 size_t bytes_read = 0;
2531 uint8_t *bytes = (uint8_t *)buf;
2532
2533 while (bytes_read < size)
2534 {
2535 const size_t curr_size = size - bytes_read;
2536 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2537 bytes + bytes_read,
2538 curr_size,
2539 error);
2540 bytes_read += curr_bytes_read;
2541 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2542 break;
2543 }
2544
2545 // Replace any software breakpoint opcodes that fall into this range back
2546 // into "buf" before we return
2547 if (bytes_read > 0)
2548 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2549 return bytes_read;
2550}
2551
Greg Clayton58a4c462010-12-16 20:01:20 +00002552uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002553Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002554{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002555 Scalar scalar;
2556 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2557 return scalar.ULongLong(fail_value);
2558 return fail_value;
2559}
2560
2561addr_t
2562Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2563{
2564 Scalar scalar;
2565 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2566 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2567 return LLDB_INVALID_ADDRESS;
2568}
2569
2570
2571bool
2572Process::WritePointerToMemory (lldb::addr_t vm_addr,
2573 lldb::addr_t ptr_value,
2574 Error &error)
2575{
2576 Scalar scalar;
2577 const uint32_t addr_byte_size = GetAddressByteSize();
2578 if (addr_byte_size <= 4)
2579 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002580 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002581 scalar = ptr_value;
2582 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002583}
2584
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585size_t
2586Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2587{
2588 size_t bytes_written = 0;
2589 const uint8_t *bytes = (const uint8_t *)buf;
2590
2591 while (bytes_written < size)
2592 {
2593 const size_t curr_size = size - bytes_written;
2594 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2595 bytes + bytes_written,
2596 curr_size,
2597 error);
2598 bytes_written += curr_bytes_written;
2599 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2600 break;
2601 }
2602 return bytes_written;
2603}
2604
2605size_t
2606Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2607{
Greg Clayton58be07b2011-01-07 06:08:19 +00002608#if defined (ENABLE_MEMORY_CACHING)
2609 m_memory_cache.Flush (addr, size);
2610#endif
2611
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002612 if (buf == NULL || size == 0)
2613 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002614
Jim Ingham4b536182011-08-09 02:12:22 +00002615 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002616
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 // We need to write any data that would go where any current software traps
2618 // (enabled software breakpoints) any software traps (breakpoints) that we
2619 // may have placed in our tasks memory.
2620
Greg Claytond8cf1a12013-06-12 00:46:38 +00002621 BreakpointSiteList bp_sites_in_range;
2622
2623 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002625 // No breakpoint sites overlap
2626 if (bp_sites_in_range.IsEmpty())
2627 return WriteMemoryPrivate (addr, buf, size, error);
2628 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002629 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002630 const uint8_t *ubuf = (const uint8_t *)buf;
2631 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632
Greg Claytond8cf1a12013-06-12 00:46:38 +00002633 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2634
2635 if (error.Success())
2636 {
2637 addr_t intersect_addr;
2638 size_t intersect_size;
2639 size_t opcode_offset;
2640 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2641 assert(intersects);
2642 assert(addr <= intersect_addr && intersect_addr < addr + size);
2643 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2644 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2645
2646 // Check for bytes before this breakpoint
2647 const addr_t curr_addr = addr + bytes_written;
2648 if (intersect_addr > curr_addr)
2649 {
2650 // There are some bytes before this breakpoint that we need to
2651 // just write to memory
2652 size_t curr_size = intersect_addr - curr_addr;
2653 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2654 ubuf + bytes_written,
2655 curr_size,
2656 error);
2657 bytes_written += curr_bytes_written;
2658 if (curr_bytes_written != curr_size)
2659 {
2660 // We weren't able to write all of the requested bytes, we
2661 // are done looping and will return the number of bytes that
2662 // we have written so far.
2663 if (error.Success())
2664 error.SetErrorToGenericError();
2665 }
2666 }
2667 // Now write any bytes that would cover up any software breakpoints
2668 // directly into the breakpoint opcode buffer
2669 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2670 bytes_written += intersect_size;
2671 }
2672 });
2673
2674 if (bytes_written < size)
2675 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2676 ubuf + bytes_written,
2677 size - bytes_written,
2678 error);
2679 }
2680 }
2681 else
2682 {
2683 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684 }
2685
2686 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002687 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002689
2690size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002691Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002692{
2693 if (byte_size == UINT32_MAX)
2694 byte_size = scalar.GetByteSize();
2695 if (byte_size > 0)
2696 {
2697 uint8_t buf[32];
2698 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2699 if (mem_size > 0)
2700 return WriteMemory(addr, buf, mem_size, error);
2701 else
2702 error.SetErrorString ("failed to get scalar as memory data");
2703 }
2704 else
2705 {
2706 error.SetErrorString ("invalid scalar value");
2707 }
2708 return 0;
2709}
2710
2711size_t
2712Process::ReadScalarIntegerFromMemory (addr_t addr,
2713 uint32_t byte_size,
2714 bool is_signed,
2715 Scalar &scalar,
2716 Error &error)
2717{
Greg Clayton7060f892013-05-01 23:41:30 +00002718 uint64_t uval = 0;
2719 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002720 {
Greg Clayton7060f892013-05-01 23:41:30 +00002721 error.SetErrorString ("byte size is zero");
2722 }
2723 else if (byte_size & (byte_size - 1))
2724 {
2725 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2726 }
2727 else if (byte_size <= sizeof(uval))
2728 {
2729 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002730 if (bytes_read == byte_size)
2731 {
2732 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002733 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002734 if (byte_size <= 4)
2735 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002736 else
Greg Clayton7060f892013-05-01 23:41:30 +00002737 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002738 if (is_signed)
2739 scalar.SignExtend(byte_size * 8);
2740 return bytes_read;
2741 }
2742 }
2743 else
2744 {
2745 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2746 }
2747 return 0;
2748}
2749
Greg Claytond495c532011-05-17 03:37:42 +00002750#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002751addr_t
2752Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2753{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002754 if (GetPrivateState() != eStateStopped)
2755 return LLDB_INVALID_ADDRESS;
2756
Greg Claytond495c532011-05-17 03:37:42 +00002757#if defined (USE_ALLOCATE_MEMORY_CACHE)
2758 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2759#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002760 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002761 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002762 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002763 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 +00002764 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002765 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002766 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002767 m_mod_id.GetStopID(),
2768 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002769 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002770#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002771}
2772
Sean Callanan90539452011-09-20 23:01:51 +00002773bool
2774Process::CanJIT ()
2775{
Sean Callanana7b443a2012-02-14 22:50:38 +00002776 if (m_can_jit == eCanJITDontKnow)
2777 {
2778 Error err;
2779
2780 uint64_t allocated_memory = AllocateMemory(8,
2781 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2782 err);
2783
2784 if (err.Success())
2785 m_can_jit = eCanJITYes;
2786 else
2787 m_can_jit = eCanJITNo;
2788
2789 DeallocateMemory (allocated_memory);
2790 }
2791
Sean Callanan90539452011-09-20 23:01:51 +00002792 return m_can_jit == eCanJITYes;
2793}
2794
2795void
2796Process::SetCanJIT (bool can_jit)
2797{
2798 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2799}
2800
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002801Error
2802Process::DeallocateMemory (addr_t ptr)
2803{
Greg Claytond495c532011-05-17 03:37:42 +00002804 Error error;
2805#if defined (USE_ALLOCATE_MEMORY_CACHE)
2806 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2807 {
Daniel Malead01b2952012-11-29 21:49:15 +00002808 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002809 }
2810#else
2811 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002812
Greg Clayton5160ce52013-03-27 23:08:40 +00002813 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002814 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002815 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 +00002816 ptr,
2817 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002818 m_mod_id.GetStopID(),
2819 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002820#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002821 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002822}
2823
Han Ming Ongc811d382012-11-17 00:33:14 +00002824
Greg Claytonc9660542012-02-05 02:38:54 +00002825ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002826Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002827 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002828{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002829 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002830 if (module_sp)
2831 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002832 Error error;
2833 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2834 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002835 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002836 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002837 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002838}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839
2840Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002841Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842{
2843 Error error;
2844 error.SetErrorString("watchpoints are not supported");
2845 return error;
2846}
2847
2848Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002849Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850{
2851 Error error;
2852 error.SetErrorString("watchpoints are not supported");
2853 return error;
2854}
2855
2856StateType
2857Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2858{
2859 StateType state;
2860 // Now wait for the process to launch and return control to us, and then
2861 // call DidLaunch:
2862 while (1)
2863 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002864 event_sp.reset();
2865 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2866
Greg Clayton2637f822011-11-17 01:23:07 +00002867 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002869
2870 // If state is invalid, then we timed out
2871 if (state == eStateInvalid)
2872 break;
2873
2874 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875 HandlePrivateEvent (event_sp);
2876 }
2877 return state;
2878}
2879
2880Error
Greg Clayton982c9762011-11-03 21:22:33 +00002881Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002882{
2883 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002885 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002886 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002887 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002888 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889
Greg Claytonaa149cb2011-08-11 02:48:45 +00002890 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891 if (exe_module)
2892 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002893 char local_exec_file_path[PATH_MAX];
2894 char platform_exec_file_path[PATH_MAX];
2895 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2896 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897 if (exe_module->GetFileSpec().Exists())
2898 {
Greg Clayton71337622011-02-24 22:24:29 +00002899 if (PrivateStateThreadIsValid ())
2900 PausePrivateStateThread ();
2901
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002902 error = WillLaunch (exe_module);
2903 if (error.Success())
2904 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002905 const bool restarted = false;
2906 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002907 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908
Ed Maste64fad602013-07-29 20:58:06 +00002909 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002910 {
2911 // Now launch using these arguments.
2912 error = DoLaunch (exe_module, launch_info);
2913 }
2914 else
2915 {
2916 // This shouldn't happen
2917 error.SetErrorString("failed to acquire process run lock");
2918 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919
2920 if (error.Fail())
2921 {
2922 if (GetID() != LLDB_INVALID_PROCESS_ID)
2923 {
2924 SetID (LLDB_INVALID_PROCESS_ID);
2925 const char *error_string = error.AsCString();
2926 if (error_string == NULL)
2927 error_string = "launch failed";
2928 SetExitStatus (-1, error_string);
2929 }
2930 }
2931 else
2932 {
2933 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002934 TimeValue timeout_time;
2935 timeout_time = TimeValue::Now();
2936 timeout_time.OffsetWithSeconds(10);
2937 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002938
Greg Clayton1a38ea72011-06-22 01:42:17 +00002939 if (state == eStateInvalid || event_sp.get() == NULL)
2940 {
2941 // We were able to launch the process, but we failed to
2942 // catch the initial stop.
2943 SetExitStatus (0, "failed to catch stop after launch");
2944 Destroy();
2945 }
2946 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002947 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002948
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002949 DidLaunch ();
2950
Greg Claytonc859e2d2012-02-13 23:10:39 +00002951 DynamicLoader *dyld = GetDynamicLoader ();
2952 if (dyld)
2953 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002954
Jason Molendaeef51062013-11-05 03:57:19 +00002955 SystemRuntime *system_runtime = GetSystemRuntime ();
2956 if (system_runtime)
2957 system_runtime->DidLaunch();
2958
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002959 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960 // This delays passing the stopped event to listeners till DidLaunch gets
2961 // a chance to complete...
2962 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002963
2964 if (PrivateStateThreadIsValid ())
2965 ResumePrivateStateThread ();
2966 else
2967 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968 }
2969 else if (state == eStateExited)
2970 {
2971 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2972 // not likely to work, and return an invalid pid.
2973 HandlePrivateEvent (event_sp);
2974 }
2975 }
2976 }
2977 }
2978 else
2979 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002980 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002981 }
2982 }
2983 return error;
2984}
2985
Greg Claytonc3776bf2012-02-09 06:16:32 +00002986
2987Error
2988Process::LoadCore ()
2989{
2990 Error error = DoLoadCore();
2991 if (error.Success())
2992 {
2993 if (PrivateStateThreadIsValid ())
2994 ResumePrivateStateThread ();
2995 else
2996 StartPrivateStateThread ();
2997
Greg Claytonc859e2d2012-02-13 23:10:39 +00002998 DynamicLoader *dyld = GetDynamicLoader ();
2999 if (dyld)
3000 dyld->DidAttach();
3001
Jason Molendaeef51062013-11-05 03:57:19 +00003002 SystemRuntime *system_runtime = GetSystemRuntime ();
3003 if (system_runtime)
3004 system_runtime->DidAttach();
3005
Greg Claytonc859e2d2012-02-13 23:10:39 +00003006 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003007 // We successfully loaded a core file, now pretend we stopped so we can
3008 // show all of the threads in the core file and explore the crashed
3009 // state.
3010 SetPrivateState (eStateStopped);
3011
3012 }
3013 return error;
3014}
3015
Greg Claytonc859e2d2012-02-13 23:10:39 +00003016DynamicLoader *
3017Process::GetDynamicLoader ()
3018{
3019 if (m_dyld_ap.get() == NULL)
3020 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3021 return m_dyld_ap.get();
3022}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003023
Jason Molendaeef51062013-11-05 03:57:19 +00003024SystemRuntime *
3025Process::GetSystemRuntime ()
3026{
3027 if (m_system_runtime_ap.get() == NULL)
3028 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3029 return m_system_runtime_ap.get();
3030}
3031
Greg Claytonc3776bf2012-02-09 06:16:32 +00003032
Jim Inghambb3a2832011-01-29 01:49:25 +00003033Process::NextEventAction::EventActionResult
3034Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035{
Jim Inghambb3a2832011-01-29 01:49:25 +00003036 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3037 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003038 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003039 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003040 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003041 return eEventActionRetry;
3042
3043 case eStateStopped:
3044 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003045 {
3046 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003047 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003048 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003049 // We don't want these events to be reported, so go set the ShouldReportStop here:
3050 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3051
Greg Claytonc9ed4782011-11-12 02:10:56 +00003052 if (m_exec_count > 0)
3053 {
3054 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003055 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003056 return eEventActionRetry;
3057 }
3058 else
3059 {
3060 m_process->CompleteAttach ();
3061 return eEventActionSuccess;
3062 }
3063 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003064 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003065
Greg Clayton513c26c2011-01-29 07:10:55 +00003066 default:
3067 case eStateExited:
3068 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003069 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003070 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003071
3072 m_exit_string.assign ("No valid Process");
3073 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003074}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075
Jim Inghambb3a2832011-01-29 01:49:25 +00003076Process::NextEventAction::EventActionResult
3077Process::AttachCompletionHandler::HandleBeingInterrupted()
3078{
3079 return eEventActionSuccess;
3080}
3081
3082const char *
3083Process::AttachCompletionHandler::GetExitString ()
3084{
3085 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086}
3087
3088Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003089Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003090{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003092 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003093 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003094 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003095 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003096
Greg Clayton144f3a92011-11-15 03:53:30 +00003097 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003098 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003099 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003100 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003101 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003102
Greg Clayton144f3a92011-11-15 03:53:30 +00003103 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003104 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003105 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3106
3107 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003109 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3110 if (error.Success())
3111 {
Ed Maste64fad602013-07-29 20:58:06 +00003112 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003113 {
3114 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003115 const bool restarted = false;
3116 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003117 // Now attach using these arguments.
3118 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3119 }
3120 else
3121 {
3122 // This shouldn't happen
3123 error.SetErrorString("failed to acquire process run lock");
3124 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003125
Greg Clayton144f3a92011-11-15 03:53:30 +00003126 if (error.Fail())
3127 {
3128 if (GetID() != LLDB_INVALID_PROCESS_ID)
3129 {
3130 SetID (LLDB_INVALID_PROCESS_ID);
3131 if (error.AsCString() == NULL)
3132 error.SetErrorString("attach failed");
3133
3134 SetExitStatus(-1, error.AsCString());
3135 }
3136 }
3137 else
3138 {
3139 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3140 StartPrivateStateThread();
3141 }
3142 return error;
3143 }
Greg Claytone996fd32011-03-08 22:40:15 +00003144 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003145 else
Greg Claytone996fd32011-03-08 22:40:15 +00003146 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003147 ProcessInstanceInfoList process_infos;
3148 PlatformSP platform_sp (m_target.GetPlatform ());
3149
3150 if (platform_sp)
3151 {
3152 ProcessInstanceInfoMatch match_info;
3153 match_info.GetProcessInfo() = attach_info;
3154 match_info.SetNameMatchType (eNameMatchEquals);
3155 platform_sp->FindProcesses (match_info, process_infos);
3156 const uint32_t num_matches = process_infos.GetSize();
3157 if (num_matches == 1)
3158 {
3159 attach_pid = process_infos.GetProcessIDAtIndex(0);
3160 // Fall through and attach using the above process ID
3161 }
3162 else
3163 {
3164 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3165 if (num_matches > 1)
3166 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3167 else
3168 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3169 }
3170 }
3171 else
3172 {
3173 error.SetErrorString ("invalid platform, can't find processes by name");
3174 return error;
3175 }
Greg Claytone996fd32011-03-08 22:40:15 +00003176 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003177 }
3178 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003179 {
3180 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003181 }
3182 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003183
3184 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003185 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003186 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003187 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003188 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003189
Ed Maste64fad602013-07-29 20:58:06 +00003190 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003191 {
3192 // Now attach using these arguments.
3193 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003194 const bool restarted = false;
3195 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003196 error = DoAttachToProcessWithID (attach_pid, attach_info);
3197 }
3198 else
3199 {
3200 // This shouldn't happen
3201 error.SetErrorString("failed to acquire process run lock");
3202 }
3203
Greg Clayton144f3a92011-11-15 03:53:30 +00003204 if (error.Success())
3205 {
3206
3207 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3208 StartPrivateStateThread();
3209 }
3210 else
Greg Claytone996fd32011-03-08 22:40:15 +00003211 {
3212 if (GetID() != LLDB_INVALID_PROCESS_ID)
3213 {
3214 SetID (LLDB_INVALID_PROCESS_ID);
3215 const char *error_string = error.AsCString();
3216 if (error_string == NULL)
3217 error_string = "attach failed";
3218
3219 SetExitStatus(-1, error_string);
3220 }
3221 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 }
3223 }
3224 return error;
3225}
3226
Greg Clayton93d3c8332011-02-16 04:46:07 +00003227void
3228Process::CompleteAttach ()
3229{
3230 // Let the process subclass figure out at much as it can about the process
3231 // before we go looking for a dynamic loader plug-in.
3232 DidAttach();
3233
Jim Ingham4299fdb2011-09-15 01:10:17 +00003234 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3235 // the same as the one we've already set, switch architectures.
3236 PlatformSP platform_sp (m_target.GetPlatform ());
3237 assert (platform_sp.get());
3238 if (platform_sp)
3239 {
Greg Clayton70512312012-05-08 01:45:38 +00003240 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003241 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003242 {
3243 ArchSpec platform_arch;
3244 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3245 if (platform_sp)
3246 {
3247 m_target.SetPlatform (platform_sp);
3248 m_target.SetArchitecture(platform_arch);
3249 }
3250 }
3251 else
3252 {
3253 ProcessInstanceInfo process_info;
3254 platform_sp->GetProcessInfo (GetID(), process_info);
3255 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003256 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003257 m_target.SetArchitecture (process_arch);
3258 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003259 }
3260
3261 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003262 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003263 DynamicLoader *dyld = GetDynamicLoader ();
3264 if (dyld)
3265 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003266
Jason Molendaeef51062013-11-05 03:57:19 +00003267 SystemRuntime *system_runtime = GetSystemRuntime ();
3268 if (system_runtime)
3269 system_runtime->DidAttach();
3270
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003271 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003272 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003273 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003274 Mutex::Locker modules_locker(target_modules.GetMutex());
3275 size_t num_modules = target_modules.GetSize();
3276 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003277
Andy Gibbsa297a972013-06-19 19:04:53 +00003278 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003279 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003280 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003281 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003282 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003283 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003284 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003285 break;
3286 }
3287 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003288 if (new_executable_module_sp)
3289 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003290}
3291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003293Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003294{
Greg Claytonb766a732011-02-04 01:58:07 +00003295 m_abi_sp.reset();
3296 m_process_input_reader.reset();
3297
3298 // Find the process and its architecture. Make sure it matches the architecture
3299 // of the current Target, and if not adjust it.
3300
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003301 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003302 if (error.Success())
3303 {
Greg Clayton71337622011-02-24 22:24:29 +00003304 if (GetID() != LLDB_INVALID_PROCESS_ID)
3305 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003306 EventSP event_sp;
3307 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3308
3309 if (state == eStateStopped || state == eStateCrashed)
3310 {
3311 // If we attached and actually have a process on the other end, then
3312 // this ended up being the equivalent of an attach.
3313 CompleteAttach ();
3314
3315 // This delays passing the stopped event to listeners till
3316 // CompleteAttach gets a chance to complete...
3317 HandlePrivateEvent (event_sp);
3318
3319 }
Greg Clayton71337622011-02-24 22:24:29 +00003320 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003321
3322 if (PrivateStateThreadIsValid ())
3323 ResumePrivateStateThread ();
3324 else
3325 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003326 }
3327 return error;
3328}
3329
3330
3331Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003332Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003333{
Greg Clayton5160ce52013-03-27 23:08:40 +00003334 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003336 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003337 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003338 StateAsCString(m_public_state.GetValue()),
3339 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003340
3341 Error error (WillResume());
3342 // Tell the process it is about to resume before the thread list
3343 if (error.Success())
3344 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003345 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003346 // can let all of our threads know that they are about to be
3347 // resumed. Threads will each be called with
3348 // Thread::WillResume(StateType) where StateType contains the state
3349 // that they are supposed to have when the process is resumed
3350 // (suspended/running/stepping). Threads should also check
3351 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003352 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003353 if (m_thread_list.WillResume())
3354 {
Jim Ingham372787f2012-04-07 00:00:41 +00003355 // Last thing, do the PreResumeActions.
3356 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357 {
Jim Ingham0161b492013-02-09 01:29:05 +00003358 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003359 }
3360 else
3361 {
3362 m_mod_id.BumpResumeID();
3363 error = DoResume();
3364 if (error.Success())
3365 {
3366 DidResume();
3367 m_thread_list.DidResume();
3368 if (log)
3369 log->Printf ("Process thinks the process has resumed.");
3370 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003371 }
3372 }
3373 else
3374 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003375 // Somebody wanted to run without running. So generate a continue & a stopped event,
3376 // and let the world handle them.
3377 if (log)
3378 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3379
3380 SetPrivateState(eStateRunning);
3381 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003382 }
3383 }
Jim Ingham444586b2011-01-24 06:34:17 +00003384 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003385 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003386 return error;
3387}
3388
3389Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003390Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003391{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003392 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3393 // in case it was already set and some thread plan logic calls halt on its
3394 // own.
3395 m_clear_thread_plans_on_stop |= clear_thread_plans;
3396
Jim Inghamaacc3182012-06-06 00:29:30 +00003397 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3398 // we could just straightaway get another event. It just narrows the window...
3399 m_currently_handling_event.WaitForValueEqualTo(false);
3400
3401
Jim Inghambb3a2832011-01-29 01:49:25 +00003402 // Pause our private state thread so we can ensure no one else eats
3403 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003404 Listener halt_listener ("lldb.process.halt_listener");
3405 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003406
Jim Inghambb3a2832011-01-29 01:49:25 +00003407 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003408 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003409
Greg Clayton513c26c2011-01-29 07:10:55 +00003410 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003411 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003412
Greg Clayton513c26c2011-01-29 07:10:55 +00003413 bool caused_stop = false;
3414
3415 // Ask the process subclass to actually halt our process
3416 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003417 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003418 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003419 if (m_public_state.GetValue() == eStateAttaching)
3420 {
3421 SetExitStatus(SIGKILL, "Cancelled async attach.");
3422 Destroy ();
3423 }
3424 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003425 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003426 // If "caused_stop" is true, then DoHalt stopped the process. If
3427 // "caused_stop" is false, the process was already stopped.
3428 // If the DoHalt caused the process to stop, then we want to catch
3429 // this event and set the interrupted bool to true before we pass
3430 // this along so clients know that the process was interrupted by
3431 // a halt command.
3432 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003433 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003434 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003435 TimeValue timeout_time;
3436 timeout_time = TimeValue::Now();
3437 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003438 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3439 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003440
Jim Ingham0f16e732011-02-08 05:20:59 +00003441 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003442 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003443 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003444 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003445 }
3446 else
3447 {
Greg Clayton2637f822011-11-17 01:23:07 +00003448 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003449 {
3450 // We caused the process to interrupt itself, so mark this
3451 // as such in the stop event so clients can tell an interrupted
3452 // process from a natural stop
3453 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3454 }
3455 else
3456 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003457 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003458 if (log)
3459 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3460 error.SetErrorString ("Did not get stopped event after halt.");
3461 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003462 }
3463 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003464 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003465 }
3466 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003467 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003468 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003469 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003470
3471 // Post any event we might have consumed. If all goes well, we will have
3472 // stopped the process, intercepted the event and set the interrupted
3473 // bool in the event. Post it to the private event queue and that will end up
3474 // correctly setting the state.
3475 if (event_sp)
3476 m_private_state_broadcaster.BroadcastEvent(event_sp);
3477
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003478 return error;
3479}
3480
3481Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003482Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3483{
3484 Error error;
3485 if (m_public_state.GetValue() == eStateRunning)
3486 {
3487 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3488 if (log)
3489 log->Printf("Process::Destroy() About to halt.");
3490 error = Halt();
3491 if (error.Success())
3492 {
3493 // Consume the halt event.
3494 TimeValue timeout (TimeValue::Now());
3495 timeout.OffsetWithSeconds(1);
3496 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3497
3498 // If the process exited while we were waiting for it to stop, put the exited event into
3499 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3500 // they don't have a process anymore...
3501
3502 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3503 {
3504 if (log)
3505 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3506 return error;
3507 }
3508 else
3509 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3510
3511 if (state != eStateStopped)
3512 {
3513 if (log)
3514 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3515 // If we really couldn't stop the process then we should just error out here, but if the
3516 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3517 StateType private_state = m_private_state.GetValue();
3518 if (private_state != eStateStopped)
3519 {
3520 return error;
3521 }
3522 }
3523 }
3524 else
3525 {
3526 if (log)
3527 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3528 }
3529 }
3530 return error;
3531}
3532
3533Error
Jim Inghamacff8952013-05-02 00:27:30 +00003534Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003535{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003536 EventSP exit_event_sp;
3537 Error error;
3538 m_destroy_in_process = true;
3539
3540 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541
3542 if (error.Success())
3543 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003544 if (DetachRequiresHalt())
3545 {
3546 error = HaltForDestroyOrDetach (exit_event_sp);
3547 if (!error.Success())
3548 {
3549 m_destroy_in_process = false;
3550 return error;
3551 }
3552 else if (exit_event_sp)
3553 {
3554 // We shouldn't need to do anything else here. There's no process left to detach from...
3555 StopPrivateStateThread();
3556 m_destroy_in_process = false;
3557 return error;
3558 }
3559 }
3560
Jim Inghamacff8952013-05-02 00:27:30 +00003561 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003562 if (error.Success())
3563 {
3564 DidDetach();
3565 StopPrivateStateThread();
3566 }
Jim Inghamacff8952013-05-02 00:27:30 +00003567 else
3568 {
3569 return error;
3570 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003571 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003572 m_destroy_in_process = false;
3573
3574 // If we exited when we were waiting for a process to stop, then
3575 // forward the event here so we don't lose the event
3576 if (exit_event_sp)
3577 {
3578 // Directly broadcast our exited event because we shut down our
3579 // private state thread above
3580 BroadcastEvent(exit_event_sp);
3581 }
3582
3583 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3584 // the last events through the event system, in which case we might strand the write lock. Unlock
3585 // it here so when we do to tear down the process we don't get an error destroying the lock.
3586
Ed Maste64fad602013-07-29 20:58:06 +00003587 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588 return error;
3589}
3590
3591Error
3592Process::Destroy ()
3593{
Jim Ingham09437922013-03-01 20:04:25 +00003594
3595 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3596 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3597 // failed and the process stays around for some reason it won't be in a confused state.
3598
3599 m_destroy_in_process = true;
3600
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003601 Error error (WillDestroy());
3602 if (error.Success())
3603 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003604 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003605 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003606 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003607 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003608 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003609
Jim Inghamaacc3182012-06-06 00:29:30 +00003610 if (m_public_state.GetValue() != eStateRunning)
3611 {
3612 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3613 // kill it, we don't want it hitting a breakpoint...
3614 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3615 // we're not going to have much luck doing this now.
3616 m_thread_list.DiscardThreadPlans();
3617 DisableAllBreakpointSites();
3618 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003619
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003620 error = DoDestroy();
3621 if (error.Success())
3622 {
3623 DidDestroy();
3624 StopPrivateStateThread();
3625 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003626 m_stdio_communication.StopReadThread();
3627 m_stdio_communication.Disconnect();
3628 if (m_process_input_reader && m_process_input_reader->IsActive())
3629 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3630 if (m_process_input_reader)
3631 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003632
3633 // If we exited when we were waiting for a process to stop, then
3634 // forward the event here so we don't lose the event
3635 if (exit_event_sp)
3636 {
3637 // Directly broadcast our exited event because we shut down our
3638 // private state thread above
3639 BroadcastEvent(exit_event_sp);
3640 }
3641
Jim Inghamb1e2e842012-04-12 18:49:31 +00003642 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3643 // the last events through the event system, in which case we might strand the write lock. Unlock
3644 // 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 +00003645 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646 }
Jim Ingham09437922013-03-01 20:04:25 +00003647
3648 m_destroy_in_process = false;
3649
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650 return error;
3651}
3652
3653Error
3654Process::Signal (int signal)
3655{
3656 Error error (WillSignal());
3657 if (error.Success())
3658 {
3659 error = DoSignal(signal);
3660 if (error.Success())
3661 DidSignal();
3662 }
3663 return error;
3664}
3665
Greg Clayton514487e2011-02-15 21:59:32 +00003666lldb::ByteOrder
3667Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003668{
Greg Clayton514487e2011-02-15 21:59:32 +00003669 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003670}
3671
3672uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003673Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003674{
Greg Clayton514487e2011-02-15 21:59:32 +00003675 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676}
3677
Greg Clayton514487e2011-02-15 21:59:32 +00003678
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679bool
3680Process::ShouldBroadcastEvent (Event *event_ptr)
3681{
3682 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3683 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003684 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003685
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003686 switch (state)
3687 {
Greg Claytonb766a732011-02-04 01:58:07 +00003688 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003689 case eStateAttaching:
3690 case eStateLaunching:
3691 case eStateDetached:
3692 case eStateExited:
3693 case eStateUnloaded:
3694 // These events indicate changes in the state of the debugging session, always report them.
3695 return_value = true;
3696 break;
3697 case eStateInvalid:
3698 // We stopped for no apparent reason, don't report it.
3699 return_value = false;
3700 break;
3701 case eStateRunning:
3702 case eStateStepping:
3703 // If we've started the target running, we handle the cases where we
3704 // are already running and where there is a transition from stopped to
3705 // running differently.
3706 // running -> running: Automatically suppress extra running events
3707 // stopped -> running: Report except when there is one or more no votes
3708 // and no yes votes.
3709 SynchronouslyNotifyStateChanged (state);
Jim Ingham0161b492013-02-09 01:29:05 +00003710 switch (m_last_broadcast_state)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003711 {
3712 case eStateRunning:
3713 case eStateStepping:
3714 // We always suppress multiple runnings with no PUBLIC stop in between.
3715 return_value = false;
3716 break;
3717 default:
3718 // TODO: make this work correctly. For now always report
3719 // run if we aren't running so we don't miss any runnning
3720 // events. If I run the lldb/test/thread/a.out file and
3721 // break at main.cpp:58, run and hit the breakpoints on
3722 // multiple threads, then somehow during the stepping over
3723 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003724
3725 // This is a transition from stop to run.
3726 switch (m_thread_list.ShouldReportRun (event_ptr))
3727 {
3728 case eVoteYes:
3729 case eVoteNoOpinion:
3730 return_value = true;
3731 break;
3732 case eVoteNo:
3733 return_value = false;
3734 break;
3735 }
3736 break;
3737 }
3738 break;
3739 case eStateStopped:
3740 case eStateCrashed:
3741 case eStateSuspended:
3742 {
3743 // We've stopped. First see if we're going to restart the target.
3744 // If we are going to stop, then we always broadcast the event.
3745 // 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 +00003746 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003747
Jim Inghamcb4ca112012-05-16 01:32:14 +00003748 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003749 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003750 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003751 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003752 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3753 event_ptr,
3754 StateAsCString(state));
3755 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003756 }
3757 else
3758 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003759 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3760 bool should_resume = false;
3761
Jim Ingham0161b492013-02-09 01:29:05 +00003762 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3763 // Asking the thread list is also not likely to go well, since we are running again.
3764 // So in that case just report the event.
3765
Jim Ingham0161b492013-02-09 01:29:05 +00003766 if (!was_restarted)
3767 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003768
3769 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770 {
Jim Ingham0161b492013-02-09 01:29:05 +00003771 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3772 if (log)
3773 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3774 should_resume,
3775 StateAsCString(state),
3776 was_restarted,
3777 stop_vote);
3778
3779 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780 {
3781 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003782 return_value = true;
3783 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003784 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785 case eVoteNo:
3786 return_value = false;
3787 break;
3788 }
Jim Ingham0161b492013-02-09 01:29:05 +00003789
Jim Inghamcb95f342012-09-05 21:13:56 +00003790 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003791 {
3792 if (log)
3793 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3794 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003795 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003796 }
3797
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003798 }
3799 else
3800 {
3801 return_value = true;
3802 SynchronouslyNotifyStateChanged (state);
3803 }
3804 }
3805 }
Jim Ingham0161b492013-02-09 01:29:05 +00003806 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003807 }
Jim Ingham0161b492013-02-09 01:29:05 +00003808
3809 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3810 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3811 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3812 // because the PublicState reflects the last event pulled off the queue, and there may be several
3813 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3814 // yet. m_last_broadcast_state gets updated here.
3815
3816 if (return_value)
3817 m_last_broadcast_state = state;
3818
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003819 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003820 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3821 event_ptr,
3822 StateAsCString(state),
3823 StateAsCString(m_last_broadcast_state),
3824 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825 return return_value;
3826}
3827
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828
3829bool
Jim Ingham372787f2012-04-07 00:00:41 +00003830Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003831{
Greg Clayton5160ce52013-03-27 23:08:40 +00003832 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003833
Greg Clayton8b82f082011-04-12 05:54:46 +00003834 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003835 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003836 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3837
Jim Ingham372787f2012-04-07 00:00:41 +00003838 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003839 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840
3841 // Create a thread that watches our internal state and controls which
3842 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003843 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003844 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003845 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003846 else
Daniel Malead01b2952012-11-29 21:49:15 +00003847 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003848
3849 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003850 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003851 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3852 if (success)
3853 {
3854 ResumePrivateStateThread();
3855 return true;
3856 }
3857 else
3858 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003859}
3860
3861void
3862Process::PausePrivateStateThread ()
3863{
3864 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3865}
3866
3867void
3868Process::ResumePrivateStateThread ()
3869{
3870 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3871}
3872
3873void
3874Process::StopPrivateStateThread ()
3875{
Greg Clayton8b82f082011-04-12 05:54:46 +00003876 if (PrivateStateThreadIsValid ())
3877 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003878 else
3879 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003880 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003881 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003882 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003883 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003884}
3885
3886void
3887Process::ControlPrivateStateThread (uint32_t signal)
3888{
Greg Clayton5160ce52013-03-27 23:08:40 +00003889 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003890
3891 assert (signal == eBroadcastInternalStateControlStop ||
3892 signal == eBroadcastInternalStateControlPause ||
3893 signal == eBroadcastInternalStateControlResume);
3894
3895 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003896 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003897
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003898 // Signal the private state thread. First we should copy this is case the
3899 // thread starts exiting since the private state thread will NULL this out
3900 // when it exits
3901 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003902 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003903 {
3904 TimeValue timeout_time;
3905 bool timed_out;
3906
3907 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3908
3909 timeout_time = TimeValue::Now();
3910 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003911 if (log)
3912 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003913 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3914 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3915
3916 if (signal == eBroadcastInternalStateControlStop)
3917 {
3918 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003919 {
3920 Error error;
3921 Host::ThreadCancel (private_state_thread, &error);
3922 if (log)
3923 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3924 }
3925 else
3926 {
3927 if (log)
3928 log->Printf ("The control event killed the private state thread without having to cancel.");
3929 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930
3931 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003932 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003933 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003934 }
3935 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003936 else
3937 {
3938 if (log)
3939 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3940 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003941}
3942
3943void
Jim Inghamcfc09352012-07-27 23:57:19 +00003944Process::SendAsyncInterrupt ()
3945{
3946 if (PrivateStateThreadIsValid())
3947 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3948 else
3949 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3950}
3951
3952void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003953Process::HandlePrivateEvent (EventSP &event_sp)
3954{
Greg Clayton5160ce52013-03-27 23:08:40 +00003955 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003956 m_resume_requested = false;
3957
Jim Inghamaacc3182012-06-06 00:29:30 +00003958 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003959
Greg Clayton414f5d32011-01-25 02:58:48 +00003960 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003961
3962 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003963 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003964 {
Jim Ingham754ab982011-01-29 04:05:41 +00003965 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003966 if (log)
3967 log->Printf ("Ran next event action, result was %d.", action_result);
3968
Jim Inghambb3a2832011-01-29 01:49:25 +00003969 switch (action_result)
3970 {
3971 case NextEventAction::eEventActionSuccess:
3972 SetNextEventAction(NULL);
3973 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003974
Jim Inghambb3a2832011-01-29 01:49:25 +00003975 case NextEventAction::eEventActionRetry:
3976 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003977
Jim Inghambb3a2832011-01-29 01:49:25 +00003978 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003979 // Handle Exiting Here. If we already got an exited event,
3980 // we should just propagate it. Otherwise, swallow this event,
3981 // and set our state to exit so the next event will kill us.
3982 if (new_state != eStateExited)
3983 {
3984 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003985 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003986 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003987 SetNextEventAction(NULL);
3988 return;
3989 }
3990 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003991 break;
3992 }
3993 }
3994
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003995 // See if we should broadcast this state to external clients?
3996 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003997
3998 if (should_broadcast)
3999 {
4000 if (log)
4001 {
Daniel Malead01b2952012-11-29 21:49:15 +00004002 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004003 __FUNCTION__,
4004 GetID(),
4005 StateAsCString(new_state),
4006 StateAsCString (GetState ()),
4007 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004008 }
Jim Ingham9575d842011-03-11 03:53:59 +00004009 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004010 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004011 PushProcessInputReader ();
Jim Inghamb78d73f2013-05-15 01:21:48 +00004012 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004013 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00004014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004015 BroadcastEvent (event_sp);
4016 }
4017 else
4018 {
4019 if (log)
4020 {
Daniel Malead01b2952012-11-29 21:49:15 +00004021 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004022 __FUNCTION__,
4023 GetID(),
4024 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004025 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004026 }
4027 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004028 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004029}
4030
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004031thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004032Process::PrivateStateThread (void *arg)
4033{
4034 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004035 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004036 return result;
4037}
4038
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004039thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004040Process::RunPrivateStateThread ()
4041{
Jim Ingham076b3042012-04-10 01:21:57 +00004042 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004043 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004044
Greg Clayton5160ce52013-03-27 23:08:40 +00004045 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004046 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004047 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004048
4049 bool exit_now = false;
4050 while (!exit_now)
4051 {
4052 EventSP event_sp;
4053 WaitForEventsPrivate (NULL, event_sp, control_only);
4054 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4055 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004056 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004057 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 +00004058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004059 switch (event_sp->GetType())
4060 {
4061 case eBroadcastInternalStateControlStop:
4062 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004063 break; // doing any internal state managment below
4064
4065 case eBroadcastInternalStateControlPause:
4066 control_only = true;
4067 break;
4068
4069 case eBroadcastInternalStateControlResume:
4070 control_only = false;
4071 break;
4072 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004075 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004076 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004077 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4078 {
4079 if (m_public_state.GetValue() == eStateAttaching)
4080 {
4081 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004082 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 +00004083 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4084 }
4085 else
4086 {
4087 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004088 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004089 Halt();
4090 }
4091 continue;
4092 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004093
4094 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4095
4096 if (internal_state != eStateInvalid)
4097 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004098 if (m_clear_thread_plans_on_stop &&
4099 StateIsStoppedState(internal_state, true))
4100 {
4101 m_clear_thread_plans_on_stop = false;
4102 m_thread_list.DiscardThreadPlans();
4103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104 HandlePrivateEvent (event_sp);
4105 }
4106
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004107 if (internal_state == eStateInvalid ||
4108 internal_state == eStateExited ||
4109 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004110 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004111 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004112 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 +00004113
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004114 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004116 }
4117
Caroline Tice20ad3c42010-10-29 21:48:37 +00004118 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004119 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004120 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121
Ed Maste64fad602013-07-29 20:58:06 +00004122 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004123 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4124 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004125 return NULL;
4126}
4127
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128//------------------------------------------------------------------
4129// Process Event Data
4130//------------------------------------------------------------------
4131
4132Process::ProcessEventData::ProcessEventData () :
4133 EventData (),
4134 m_process_sp (),
4135 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004136 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004137 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004138 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004139{
4140}
4141
4142Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4143 EventData (),
4144 m_process_sp (process_sp),
4145 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004146 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004147 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004148 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149{
4150}
4151
4152Process::ProcessEventData::~ProcessEventData()
4153{
4154}
4155
4156const ConstString &
4157Process::ProcessEventData::GetFlavorString ()
4158{
4159 static ConstString g_flavor ("Process::ProcessEventData");
4160 return g_flavor;
4161}
4162
4163const ConstString &
4164Process::ProcessEventData::GetFlavor () const
4165{
4166 return ProcessEventData::GetFlavorString ();
4167}
4168
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004169void
4170Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4171{
4172 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004173 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4174 // the public event queue, then other times when we're pretending that this is where we stopped at the
4175 // end of expression evaluation. m_update_state is used to distinguish these
4176 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004177 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004178 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004179 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004180
Jim Ingham221d51c2013-05-08 00:35:16 +00004181 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004182
4183 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4184 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004185 {
4186 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004187 uint32_t num_threads = curr_thread_list.GetSize();
4188 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004189
Jim Ingham4b536182011-08-09 02:12:22 +00004190 // The actions might change one of the thread's stop_info's opinions about whether we should
4191 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004192
4193 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4194 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4195 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4196 // 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
4197 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004198 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004199 for (idx = 0; idx < num_threads; ++idx)
4200 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4201
Jim Inghamc7078c22012-12-13 22:24:15 +00004202 // Use this to track whether we should continue from here. We will only continue the target running if
4203 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4204 // then it doesn't matter what the other threads say...
4205
4206 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004207
Jim Ingham0ad7e052013-04-25 02:04:59 +00004208 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4209 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4210 // thing to do is, and it's better to let the user decide than continue behind their backs.
4211
4212 bool does_anybody_have_an_opinion = false;
4213
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004214 for (idx = 0; idx < num_threads; ++idx)
4215 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004216 curr_thread_list = m_process_sp->GetThreadList();
4217 if (curr_thread_list.GetSize() != num_threads)
4218 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004219 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004220 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004221 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 +00004222 break;
4223 }
4224
4225 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4226
4227 if (thread_sp->GetIndexID() != thread_index_array[idx])
4228 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004229 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004230 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004231 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004232 idx,
4233 thread_index_array[idx],
4234 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004235 break;
4236 }
4237
Jim Inghamb15bfc72010-10-20 00:39:53 +00004238 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004239 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004240 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004241 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004242 bool this_thread_wants_to_stop;
4243 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004244 {
Jim Ingham0161b492013-02-09 01:29:05 +00004245 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4246 }
4247 else
4248 {
4249 stop_info_sp->PerformAction(event_ptr);
4250 // The stop action might restart the target. If it does, then we want to mark that in the
4251 // event so that whoever is receiving it will know to wait for the running event and reflect
4252 // that state appropriately.
4253 // We also need to stop processing actions, since they aren't expecting the target to be running.
4254
4255 // FIXME: we might have run.
4256 if (stop_info_sp->HasTargetRunSinceMe())
4257 {
4258 SetRestarted (true);
4259 break;
4260 }
4261
4262 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004263 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004264
Jim Inghamc7078c22012-12-13 22:24:15 +00004265 if (still_should_stop == false)
4266 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004267 }
4268 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004269
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004270
Jim Inghama8ca6e22013-05-03 23:04:37 +00004271 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004272 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004273 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004274 {
4275 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004276 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004277 // Use the public resume method here, since this is just
4278 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004279 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004280 }
4281 else
4282 {
4283 // If we didn't restart, run the Stop Hooks here:
4284 // They might also restart the target, so watch for that.
4285 m_process_sp->GetTarget().RunStopHooks();
4286 if (m_process_sp->GetPrivateState() == eStateRunning)
4287 SetRestarted(true);
4288 }
Jim Ingham9575d842011-03-11 03:53:59 +00004289 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004290 }
4291}
4292
4293void
4294Process::ProcessEventData::Dump (Stream *s) const
4295{
4296 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004297 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004298
Greg Clayton8b82f082011-04-12 05:54:46 +00004299 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004300}
4301
4302const Process::ProcessEventData *
4303Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4304{
4305 if (event_ptr)
4306 {
4307 const EventData *event_data = event_ptr->GetData();
4308 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4309 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4310 }
4311 return NULL;
4312}
4313
4314ProcessSP
4315Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4316{
4317 ProcessSP process_sp;
4318 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4319 if (data)
4320 process_sp = data->GetProcessSP();
4321 return process_sp;
4322}
4323
4324StateType
4325Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4326{
4327 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4328 if (data == NULL)
4329 return eStateInvalid;
4330 else
4331 return data->GetState();
4332}
4333
4334bool
4335Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4336{
4337 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4338 if (data == NULL)
4339 return false;
4340 else
4341 return data->GetRestarted();
4342}
4343
4344void
4345Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4346{
4347 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4348 if (data != NULL)
4349 data->SetRestarted(new_value);
4350}
4351
Jim Ingham0161b492013-02-09 01:29:05 +00004352size_t
4353Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4354{
4355 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4356 if (data != NULL)
4357 return data->GetNumRestartedReasons();
4358 else
4359 return 0;
4360}
4361
4362const char *
4363Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4364{
4365 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4366 if (data != NULL)
4367 return data->GetRestartedReasonAtIndex(idx);
4368 else
4369 return NULL;
4370}
4371
4372void
4373Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4374{
4375 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4376 if (data != NULL)
4377 data->AddRestartedReason(reason);
4378}
4379
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004380bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004381Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4382{
4383 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4384 if (data == NULL)
4385 return false;
4386 else
4387 return data->GetInterrupted ();
4388}
4389
4390void
4391Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4392{
4393 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4394 if (data != NULL)
4395 data->SetInterrupted(new_value);
4396}
4397
4398bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004399Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4400{
4401 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4402 if (data)
4403 {
4404 data->SetUpdateStateOnRemoval();
4405 return true;
4406 }
4407 return false;
4408}
4409
Greg Claytond9e416c2012-02-18 05:35:26 +00004410lldb::TargetSP
4411Process::CalculateTarget ()
4412{
4413 return m_target.shared_from_this();
4414}
4415
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004416void
Greg Clayton0603aa92010-10-04 01:05:56 +00004417Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004418{
Greg Claytonc14ee322011-09-22 04:58:26 +00004419 exe_ctx.SetTargetPtr (&m_target);
4420 exe_ctx.SetProcessPtr (this);
4421 exe_ctx.SetThreadPtr(NULL);
4422 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004423}
4424
Greg Claytone996fd32011-03-08 22:40:15 +00004425//uint32_t
4426//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4427//{
4428// return 0;
4429//}
4430//
4431//ArchSpec
4432//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4433//{
4434// return Host::GetArchSpecForExistingProcess (pid);
4435//}
4436//
4437//ArchSpec
4438//Process::GetArchSpecForExistingProcess (const char *process_name)
4439//{
4440// return Host::GetArchSpecForExistingProcess (process_name);
4441//}
4442//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004443void
4444Process::AppendSTDOUT (const char * s, size_t len)
4445{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004446 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004447 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004448 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004449}
4450
4451void
Greg Clayton93e86192011-11-13 04:45:22 +00004452Process::AppendSTDERR (const char * s, size_t len)
4453{
4454 Mutex::Locker locker (m_stdio_communication_mutex);
4455 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004456 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004457}
4458
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004459void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004460Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004461{
4462 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004463 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004464 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4465}
4466
4467size_t
4468Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4469{
4470 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004471 if (m_profile_data.empty())
4472 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004473
4474 std::string &one_profile_data = m_profile_data.front();
4475 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004476 if (bytes_available > 0)
4477 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004478 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004479 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004480 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004481 if (bytes_available > buf_size)
4482 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004483 memcpy(buf, one_profile_data.c_str(), buf_size);
4484 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004485 bytes_available = buf_size;
4486 }
4487 else
4488 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004489 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004490 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004491 }
4492 }
4493 return bytes_available;
4494}
4495
4496
Greg Clayton93e86192011-11-13 04:45:22 +00004497//------------------------------------------------------------------
4498// Process STDIO
4499//------------------------------------------------------------------
4500
4501size_t
4502Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4503{
4504 Mutex::Locker locker(m_stdio_communication_mutex);
4505 size_t bytes_available = m_stdout_data.size();
4506 if (bytes_available > 0)
4507 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004508 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004509 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004510 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004511 if (bytes_available > buf_size)
4512 {
4513 memcpy(buf, m_stdout_data.c_str(), buf_size);
4514 m_stdout_data.erase(0, buf_size);
4515 bytes_available = buf_size;
4516 }
4517 else
4518 {
4519 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4520 m_stdout_data.clear();
4521 }
4522 }
4523 return bytes_available;
4524}
4525
4526
4527size_t
4528Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4529{
4530 Mutex::Locker locker(m_stdio_communication_mutex);
4531 size_t bytes_available = m_stderr_data.size();
4532 if (bytes_available > 0)
4533 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004534 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004535 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004536 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004537 if (bytes_available > buf_size)
4538 {
4539 memcpy(buf, m_stderr_data.c_str(), buf_size);
4540 m_stderr_data.erase(0, buf_size);
4541 bytes_available = buf_size;
4542 }
4543 else
4544 {
4545 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4546 m_stderr_data.clear();
4547 }
4548 }
4549 return bytes_available;
4550}
4551
4552void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004553Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4554{
4555 Process *process = (Process *) baton;
4556 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4557}
4558
4559size_t
4560Process::ProcessInputReaderCallback (void *baton,
4561 InputReader &reader,
4562 lldb::InputReaderAction notification,
4563 const char *bytes,
4564 size_t bytes_len)
4565{
4566 Process *process = (Process *) baton;
4567
4568 switch (notification)
4569 {
4570 case eInputReaderActivate:
4571 break;
4572
4573 case eInputReaderDeactivate:
4574 break;
4575
4576 case eInputReaderReactivate:
4577 break;
4578
Caroline Tice969ed3d2011-05-02 20:41:46 +00004579 case eInputReaderAsynchronousOutputWritten:
4580 break;
4581
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004582 case eInputReaderGotToken:
4583 {
4584 Error error;
4585 process->PutSTDIN (bytes, bytes_len, error);
4586 }
4587 break;
4588
Caroline Ticeefed6132010-11-19 20:47:54 +00004589 case eInputReaderInterrupt:
Jim Inghamfc65a502013-06-19 00:56:17 +00004590 process->SendAsyncInterrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +00004591 break;
4592
4593 case eInputReaderEndOfFile:
4594 process->AppendSTDOUT ("^D", 2);
4595 break;
4596
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004597 case eInputReaderDone:
4598 break;
4599
4600 }
4601
4602 return bytes_len;
4603}
4604
4605void
4606Process::ResetProcessInputReader ()
4607{
4608 m_process_input_reader.reset();
4609}
4610
4611void
Greg Claytonee95ed52011-11-17 22:14:31 +00004612Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004613{
4614 // First set up the Read Thread for reading/handling process I/O
4615
Greg Clayton7b0992d2013-04-18 22:45:39 +00004616 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004617
4618 if (conn_ap.get())
4619 {
4620 m_stdio_communication.SetConnection (conn_ap.release());
4621 if (m_stdio_communication.IsConnected())
4622 {
4623 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4624 m_stdio_communication.StartReadThread();
4625
4626 // Now read thread is set up, set up input reader.
4627
4628 if (!m_process_input_reader.get())
4629 {
4630 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4631 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4632 this,
4633 eInputReaderGranularityByte,
4634 NULL,
4635 NULL,
4636 false));
4637
4638 if (err.Fail())
4639 m_process_input_reader.reset();
4640 }
4641 }
4642 }
4643}
4644
4645void
4646Process::PushProcessInputReader ()
4647{
4648 if (m_process_input_reader && !m_process_input_reader->IsActive())
4649 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4650}
4651
4652void
4653Process::PopProcessInputReader ()
4654{
4655 if (m_process_input_reader && m_process_input_reader->IsActive())
4656 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4657}
4658
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004659// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004660void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004661Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004662{
Greg Clayton67cc0632012-08-22 17:17:09 +00004663// static std::vector<OptionEnumValueElement> g_plugins;
4664//
4665// int i=0;
4666// const char *name;
4667// OptionEnumValueElement option_enum;
4668// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4669// {
4670// if (name)
4671// {
4672// option_enum.value = i;
4673// option_enum.string_value = name;
4674// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4675// g_plugins.push_back (option_enum);
4676// }
4677// ++i;
4678// }
4679// option_enum.value = 0;
4680// option_enum.string_value = NULL;
4681// option_enum.usage = NULL;
4682// g_plugins.push_back (option_enum);
4683//
4684// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4685// {
4686// if (::strcmp (name, "plugin") == 0)
4687// {
4688// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4689// break;
4690// }
4691// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004692//
Greg Clayton6920b522012-08-22 18:39:03 +00004693 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004694}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004695
Greg Clayton99d0faf2010-11-18 23:32:35 +00004696void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004697Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004698{
Greg Clayton6920b522012-08-22 18:39:03 +00004699 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004700}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004701
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004702ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004703Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004704 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004705 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004706 Stream &errors)
4707{
4708 ExecutionResults return_value = eExecutionSetupError;
4709
Jim Ingham77787032011-01-20 02:03:18 +00004710 if (thread_plan_sp.get() == NULL)
4711 {
4712 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004713 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004714 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004715
4716 if (!thread_plan_sp->ValidatePlan(NULL))
4717 {
4718 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4719 return eExecutionSetupError;
4720 }
4721
Greg Claytonc14ee322011-09-22 04:58:26 +00004722 if (exe_ctx.GetProcessPtr() != this)
4723 {
4724 errors.Printf("RunThreadPlan called on wrong process.");
4725 return eExecutionSetupError;
4726 }
4727
4728 Thread *thread = exe_ctx.GetThreadPtr();
4729 if (thread == NULL)
4730 {
4731 errors.Printf("RunThreadPlan called with invalid thread.");
4732 return eExecutionSetupError;
4733 }
Jim Ingham77787032011-01-20 02:03:18 +00004734
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004735 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4736 // For that to be true the plan can't be private - since private plans suppress themselves in the
4737 // GetCompletedPlan call.
4738
4739 bool orig_plan_private = thread_plan_sp->GetPrivate();
4740 thread_plan_sp->SetPrivate(false);
4741
Jim Ingham444586b2011-01-24 06:34:17 +00004742 if (m_private_state.GetValue() != eStateStopped)
4743 {
4744 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004745 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004746 }
4747
Jim Ingham66243842011-08-13 00:56:10 +00004748 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004749 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004750 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004751 if (!selected_frame_sp)
4752 {
4753 thread->SetSelectedFrame(0);
4754 selected_frame_sp = thread->GetSelectedFrame();
4755 if (!selected_frame_sp)
4756 {
4757 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4758 return eExecutionSetupError;
4759 }
4760 }
4761
4762 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004763
4764 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4765 // so we should arrange to reset them as well.
4766
Greg Claytonc14ee322011-09-22 04:58:26 +00004767 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004768
Jim Ingham66243842011-08-13 00:56:10 +00004769 uint32_t selected_tid;
4770 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004771 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004772 {
4773 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004774 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004775 }
4776 else
4777 {
4778 selected_tid = LLDB_INVALID_THREAD_ID;
4779 }
4780
Jim Ingham372787f2012-04-07 00:00:41 +00004781 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004782 lldb::StateType old_state;
4783 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004784
Greg Clayton5160ce52013-03-27 23:08:40 +00004785 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004786 if (Host::GetCurrentThread() == m_private_state_thread)
4787 {
Jim Ingham076b3042012-04-10 01:21:57 +00004788 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4789 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004790 // 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 +00004791 // we are fielding public events here.
4792 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004793 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 +00004794
4795
Jim Ingham372787f2012-04-07 00:00:41 +00004796 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004797
4798 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4799 // returning control here.
4800 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4801 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4802 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4803 // do just what we want.
4804 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4805 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4806 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4807 old_state = m_public_state.GetValue();
4808 m_public_state.SetValueNoLock(eStateStopped);
4809
4810 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004811 StartPrivateStateThread(true);
4812 }
4813
4814 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004815
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004816 if (options.GetDebug())
4817 {
4818 // In this case, we aren't actually going to run, we just want to stop right away.
4819 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4820 // FIXME: To make this prettier we should invent some stop reason for this, but that
4821 // is only cosmetic, and this functionality is only of use to lldb developers who can
4822 // live with not pretty...
4823 thread->Flush();
4824 return eExecutionStoppedForDebug;
4825 }
4826
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004827 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004828
Sean Callanana46ec452012-07-11 21:31:24 +00004829 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004830
Jim Ingham77787032011-01-20 02:03:18 +00004831 {
Sean Callanana46ec452012-07-11 21:31:24 +00004832 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4833 // restored on exit to the function.
4834 //
4835 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4836 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004837
Sean Callanana46ec452012-07-11 21:31:24 +00004838 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004839
Jim Inghamf48169b2010-11-30 02:22:11 +00004840 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004841 {
4842 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004843 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004844 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004845 thread->GetIndexID(),
4846 thread->GetID(),
4847 s.GetData());
4848 }
4849
4850 bool got_event;
4851 lldb::EventSP event_sp;
4852 lldb::StateType stop_state = lldb::eStateInvalid;
4853
4854 TimeValue* timeout_ptr = NULL;
4855 TimeValue real_timeout;
4856
Jim Ingham0161b492013-02-09 01:29:05 +00004857 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 +00004858 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004859 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004860 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00004861
Jim Ingham0161b492013-02-09 01:29:05 +00004862 // This is just for accounting:
4863 uint32_t num_resumes = 0;
4864
4865 TimeValue one_thread_timeout = TimeValue::Now();
4866 TimeValue final_timeout = one_thread_timeout;
4867
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004868 uint32_t timeout_usec = options.GetTimeoutUsec();
4869 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00004870 {
4871 // If we are running all threads then we take half the time to run all threads, bounded by
4872 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004873 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00004874 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4875 else
4876 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00004877 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00004878 if (computed_timeout > default_one_thread_timeout_usec)
4879 computed_timeout = default_one_thread_timeout_usec;
4880 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4881 }
4882 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4883 }
4884 else
4885 {
4886 if (timeout_usec != 0)
4887 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4888 }
4889
Jim Ingham8559a352012-11-26 23:52:18 +00004890 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4891 // So don't call return anywhere within it.
4892
Sean Callanana46ec452012-07-11 21:31:24 +00004893 while (1)
4894 {
4895 // We usually want to resume the process if we get to the top of the loop.
4896 // The only exception is if we get two running events with no intervening
4897 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004898 if (log)
4899 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4900 do_resume,
4901 handle_running_event,
4902 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004903
Jim Ingham184e9812013-01-15 02:47:48 +00004904 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00004905 {
4906 // Do the initial resume and wait for the running event before going further.
4907
Jim Ingham184e9812013-01-15 02:47:48 +00004908 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00004909 {
Jim Ingham0161b492013-02-09 01:29:05 +00004910 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00004911 Error resume_error = PrivateResume ();
4912 if (!resume_error.Success())
4913 {
Jim Ingham0161b492013-02-09 01:29:05 +00004914 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4915 num_resumes,
4916 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00004917 return_value = eExecutionSetupError;
4918 break;
4919 }
Sean Callanana46ec452012-07-11 21:31:24 +00004920 }
Sean Callanana46ec452012-07-11 21:31:24 +00004921
Jim Ingham0161b492013-02-09 01:29:05 +00004922 TimeValue resume_timeout = TimeValue::Now();
4923 resume_timeout.OffsetWithMicroSeconds(500000);
4924
4925 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00004926 if (!got_event)
4927 {
4928 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004929 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4930 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004931
Jim Ingham0161b492013-02-09 01:29:05 +00004932 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004933 return_value = eExecutionSetupError;
4934 break;
4935 }
4936
4937 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00004938
Sean Callanana46ec452012-07-11 21:31:24 +00004939 if (stop_state != eStateRunning)
4940 {
Jim Ingham0161b492013-02-09 01:29:05 +00004941 bool restarted = false;
4942
4943 if (stop_state == eStateStopped)
4944 {
4945 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4946 if (log)
4947 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4948 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4949 num_resumes,
4950 StateAsCString(stop_state),
4951 restarted,
4952 do_resume,
4953 handle_running_event);
4954 }
4955
4956 if (restarted)
4957 {
4958 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4959 // event here. But if I do, the best thing is to Halt and then get out of here.
4960 Halt();
4961 }
4962
Jim Ingham35e1bda2012-10-16 21:41:58 +00004963 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4964 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004965 return_value = eExecutionSetupError;
4966 break;
4967 }
4968
4969 if (log)
4970 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4971 // We need to call the function synchronously, so spin waiting for it to return.
4972 // If we get interrupted while executing, we're going to lose our context, and
4973 // won't be able to gather the result at this point.
4974 // We set the timeout AFTER the resume, since the resume takes some time and we
4975 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00004976 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004977 else
4978 {
Sean Callanana46ec452012-07-11 21:31:24 +00004979 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004980 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004981 }
Jim Ingham0161b492013-02-09 01:29:05 +00004982
4983 if (before_first_timeout)
4984 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004985 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00004986 timeout_ptr = &one_thread_timeout;
4987 else
4988 {
4989 if (timeout_usec == 0)
4990 timeout_ptr = NULL;
4991 else
4992 timeout_ptr = &final_timeout;
4993 }
4994 }
4995 else
4996 {
4997 if (timeout_usec == 0)
4998 timeout_ptr = NULL;
4999 else
5000 timeout_ptr = &final_timeout;
5001 }
5002
5003 do_resume = true;
5004 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005005
Sean Callanana46ec452012-07-11 21:31:24 +00005006 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005007 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005008
Jim Ingham0f16e732011-02-08 05:20:59 +00005009 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005010 {
Sean Callanana46ec452012-07-11 21:31:24 +00005011 if (timeout_ptr)
5012 {
Matt Kopec676a4872013-02-21 23:55:31 +00005013 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005014 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5015 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005016 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005017 else
Sean Callanana46ec452012-07-11 21:31:24 +00005018 {
5019 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5020 }
5021 }
5022
5023 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5024
5025 if (got_event)
5026 {
5027 if (event_sp.get())
5028 {
5029 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005030 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005031 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005032 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005033 return_value = eExecutionInterrupted;
5034 errors.Printf ("Execution halted by user interrupt.");
5035 if (log)
5036 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005037 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005038 }
5039 else
5040 {
5041 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5042 if (log)
5043 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5044
5045 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005046 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005047 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005048 {
Jim Ingham0161b492013-02-09 01:29:05 +00005049 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005050 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5051 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005052 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005053 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005054 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005055 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5056 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005057 }
5058 else
5059 {
Jim Ingham0161b492013-02-09 01:29:05 +00005060 // If we were restarted, we just need to go back up to fetch another event.
5061 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005062 {
5063 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005064 {
5065 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5066 }
5067 keep_going = true;
5068 do_resume = false;
5069 handle_running_event = true;
5070
Jim Inghamcfc09352012-07-27 23:57:19 +00005071 }
5072 else
5073 {
Jim Ingham0161b492013-02-09 01:29:05 +00005074
5075 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5076 StopReason stop_reason = eStopReasonInvalid;
5077 if (stop_info_sp)
5078 stop_reason = stop_info_sp->GetStopReason();
5079
5080
5081 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5082 // it is OUR plan that is complete?
5083 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005084 {
5085 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005086 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5087 // Now mark this plan as private so it doesn't get reported as the stop reason
5088 // after this point.
5089 if (thread_plan_sp)
5090 thread_plan_sp->SetPrivate (orig_plan_private);
5091 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005092 }
5093 else
5094 {
Jim Ingham0161b492013-02-09 01:29:05 +00005095 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005096 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005097 {
5098 if (log)
5099 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005100 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005101 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005102 {
5103 event_to_broadcast_sp = event_sp;
5104 }
Jim Ingham0161b492013-02-09 01:29:05 +00005105 }
Jim Ingham184e9812013-01-15 02:47:48 +00005106 else
Jim Ingham0161b492013-02-09 01:29:05 +00005107 {
5108 if (log)
5109 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005110 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005111 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005112 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005113 }
Jim Ingham184e9812013-01-15 02:47:48 +00005114 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005115 }
Sean Callanana46ec452012-07-11 21:31:24 +00005116 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005117 }
5118 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005119
Jim Inghamcfc09352012-07-27 23:57:19 +00005120 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005121 // This shouldn't really happen, but sometimes we do get two running events without an
5122 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005123 do_resume = false;
5124 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005125 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005126 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005127
Jim Inghamcfc09352012-07-27 23:57:19 +00005128 default:
5129 if (log)
5130 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5131
5132 if (stop_state == eStateExited)
5133 event_to_broadcast_sp = event_sp;
5134
Sean Callananbf154da2012-08-08 17:35:10 +00005135 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005136 return_value = eExecutionInterrupted;
5137 break;
5138 }
Sean Callanana46ec452012-07-11 21:31:24 +00005139 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005140
Sean Callanana46ec452012-07-11 21:31:24 +00005141 if (keep_going)
5142 continue;
5143 else
5144 break;
5145 }
5146 else
5147 {
5148 if (log)
5149 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5150 return_value = eExecutionInterrupted;
5151 break;
5152 }
5153 }
5154 else
5155 {
5156 // If we didn't get an event that means we've timed out...
5157 // We will interrupt the process here. Depending on what we were asked to do we will
5158 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005159
5160 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005161 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005162 {
Jim Ingham0161b492013-02-09 01:29:05 +00005163 uint64_t remaining_time = final_timeout - TimeValue::Now();
5164 if (before_first_timeout)
5165 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005166 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005167 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005168 else
5169 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005170 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005171 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005172 }
5173 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005174 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005175 "abandoning execution.",
5176 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005177 }
5178
Jim Ingham0161b492013-02-09 01:29:05 +00005179 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5180 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5181 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5182 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5183 // stopped event. That's what this while loop does.
5184
5185 bool back_to_top = true;
5186 uint32_t try_halt_again = 0;
5187 bool do_halt = true;
5188 const uint32_t num_retries = 5;
5189 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005190 {
Jim Ingham0161b492013-02-09 01:29:05 +00005191 Error halt_error;
5192 if (do_halt)
5193 {
5194 if (log)
5195 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5196 halt_error = Halt();
5197 }
5198 if (halt_error.Success())
5199 {
5200 if (log)
5201 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5202
5203 real_timeout = TimeValue::Now();
5204 real_timeout.OffsetWithMicroSeconds(500000);
5205
5206 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005207
Jim Ingham0161b492013-02-09 01:29:05 +00005208 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005209 {
Jim Ingham0161b492013-02-09 01:29:05 +00005210 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5211 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005212 {
Jim Ingham0161b492013-02-09 01:29:05 +00005213 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5214 if (stop_state == lldb::eStateStopped
5215 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5216 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005217 }
5218
Jim Ingham0161b492013-02-09 01:29:05 +00005219 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005220 {
Jim Ingham0161b492013-02-09 01:29:05 +00005221 // Between the time we initiated the Halt and the time we delivered it, the process could have
5222 // already finished its job. Check that here:
5223
5224 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5225 {
5226 if (log)
5227 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5228 "Exiting wait loop.");
5229 return_value = eExecutionCompleted;
5230 back_to_top = false;
5231 break;
5232 }
5233
5234 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5235 {
5236 if (log)
5237 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5238 "Exiting wait loop.");
5239 try_halt_again++;
5240 do_halt = false;
5241 continue;
5242 }
Sean Callanana46ec452012-07-11 21:31:24 +00005243
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005244 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005245 {
5246 if (log)
5247 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5248 return_value = eExecutionInterrupted;
5249 back_to_top = false;
5250 break;
5251 }
5252
5253 if (before_first_timeout)
5254 {
5255 // Set all the other threads to run, and return to the top of the loop, which will continue;
5256 before_first_timeout = false;
5257 thread_plan_sp->SetStopOthers (false);
5258 if (log)
5259 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005260
Jim Ingham0161b492013-02-09 01:29:05 +00005261 back_to_top = true;
5262 break;
5263 }
5264 else
5265 {
5266 // Running all threads failed, so return Interrupted.
5267 if (log)
5268 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5269 return_value = eExecutionInterrupted;
5270 back_to_top = false;
5271 break;
5272 }
Sean Callanana46ec452012-07-11 21:31:24 +00005273 }
5274 }
5275 else
Jim Ingham0161b492013-02-09 01:29:05 +00005276 { if (log)
5277 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5278 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005279 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005280 back_to_top = false;
5281 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005282 }
5283 }
Jim Ingham0161b492013-02-09 01:29:05 +00005284 else
5285 {
5286 try_halt_again++;
5287 continue;
5288 }
Sean Callanana46ec452012-07-11 21:31:24 +00005289 }
Jim Ingham0161b492013-02-09 01:29:05 +00005290
5291 if (!back_to_top || try_halt_again > num_retries)
5292 break;
5293 else
5294 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005295 }
Sean Callanana46ec452012-07-11 21:31:24 +00005296 } // END WAIT LOOP
5297
5298 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5299 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5300 {
5301 StopPrivateStateThread();
5302 Error error;
5303 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005304 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005305 {
5306 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5307 }
5308 m_public_state.SetValueNoLock(old_state);
5309
5310 }
5311
Jim Ingham184e9812013-01-15 02:47:48 +00005312 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5313 // could happen:
5314 // 1) The execution successfully completed
5315 // 2) We hit a breakpoint, and ignore_breakpoints was true
5316 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005317 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5318 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005319
Jim Ingham184e9812013-01-15 02:47:48 +00005320 if (return_value == eExecutionCompleted
5321 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005322 {
5323 thread_plan_sp->RestoreThreadState();
5324 }
Sean Callanana46ec452012-07-11 21:31:24 +00005325
5326 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005327 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005328 {
5329 if (log)
5330 {
5331 StreamString s;
5332 if (event_sp)
5333 event_sp->Dump (&s);
5334 else
5335 {
5336 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5337 }
5338
5339 StreamString ts;
5340
5341 const char *event_explanation = NULL;
5342
5343 do
5344 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005345 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005346 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005347 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005348 break;
5349 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005350 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005351 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005352 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005353 break;
5354 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005355 else
Sean Callanana46ec452012-07-11 21:31:24 +00005356 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005357 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5358
5359 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005360 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005361 event_explanation = "<no event data>";
5362 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005363 }
5364
Jim Inghamcfc09352012-07-27 23:57:19 +00005365 Process *process = event_data->GetProcessSP().get();
5366
5367 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005368 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005369 event_explanation = "<no process>";
5370 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005371 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005372
5373 ThreadList &thread_list = process->GetThreadList();
5374
5375 uint32_t num_threads = thread_list.GetSize();
5376 uint32_t thread_index;
5377
5378 ts.Printf("<%u threads> ", num_threads);
5379
5380 for (thread_index = 0;
5381 thread_index < num_threads;
5382 ++thread_index)
5383 {
5384 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5385
5386 if (!thread)
5387 {
5388 ts.Printf("<?> ");
5389 continue;
5390 }
5391
Daniel Malead01b2952012-11-29 21:49:15 +00005392 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005393 RegisterContext *register_context = thread->GetRegisterContext().get();
5394
5395 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005396 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005397 else
5398 ts.Printf("[ip unknown] ");
5399
5400 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5401 if (stop_info_sp)
5402 {
5403 const char *stop_desc = stop_info_sp->GetDescription();
5404 if (stop_desc)
5405 ts.PutCString (stop_desc);
5406 }
5407 ts.Printf(">");
5408 }
5409
5410 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005411 }
Sean Callanana46ec452012-07-11 21:31:24 +00005412 } while (0);
5413
Jim Inghamcfc09352012-07-27 23:57:19 +00005414 if (event_explanation)
5415 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005416 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005417 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5418 }
5419
Jim Inghame4483cf2013-09-27 01:13:01 +00005420 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005421 {
5422 if (log)
5423 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5424 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5425 thread_plan_sp->SetPrivate (orig_plan_private);
5426 }
5427 else
5428 {
5429 if (log)
5430 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005431 }
5432 }
5433 else if (return_value == eExecutionSetupError)
5434 {
5435 if (log)
5436 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005437
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005438 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005439 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005440 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005441 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005442 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005443 }
5444 else
5445 {
Sean Callanana46ec452012-07-11 21:31:24 +00005446 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005447 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005448 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005449 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5450 return_value = eExecutionCompleted;
5451 }
5452 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5453 {
5454 if (log)
5455 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5456 return_value = eExecutionDiscarded;
5457 }
5458 else
5459 {
5460 if (log)
5461 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005462 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005463 {
5464 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005465 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005466 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5467 thread_plan_sp->SetPrivate (orig_plan_private);
5468 }
5469 }
5470 }
5471
5472 // Thread we ran the function in may have gone away because we ran the target
5473 // Check that it's still there, and if it is put it back in the context. Also restore the
5474 // frame in the context if it is still present.
5475 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5476 if (thread)
5477 {
5478 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5479 }
5480
5481 // Also restore the current process'es selected frame & thread, since this function calling may
5482 // be done behind the user's back.
5483
5484 if (selected_tid != LLDB_INVALID_THREAD_ID)
5485 {
5486 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5487 {
5488 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005489 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005490 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005491 if (old_frame_sp)
5492 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005493 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005494 }
5495 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005496
Sean Callanana46ec452012-07-11 21:31:24 +00005497 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005498
Sean Callanana46ec452012-07-11 21:31:24 +00005499 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005500 {
Sean Callanana46ec452012-07-11 21:31:24 +00005501 if (log)
5502 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5503 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005504 }
5505
5506 return return_value;
5507}
5508
5509const char *
5510Process::ExecutionResultAsCString (ExecutionResults result)
5511{
5512 const char *result_name;
5513
5514 switch (result)
5515 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005516 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005517 result_name = "eExecutionCompleted";
5518 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005519 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005520 result_name = "eExecutionDiscarded";
5521 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005522 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005523 result_name = "eExecutionInterrupted";
5524 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005525 case eExecutionHitBreakpoint:
5526 result_name = "eExecutionHitBreakpoint";
5527 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005528 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005529 result_name = "eExecutionSetupError";
5530 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005531 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005532 result_name = "eExecutionTimedOut";
5533 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005534 case eExecutionStoppedForDebug:
5535 result_name = "eExecutionStoppedForDebug";
5536 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005537 }
5538 return result_name;
5539}
5540
Greg Clayton7260f622011-04-18 08:33:37 +00005541void
5542Process::GetStatus (Stream &strm)
5543{
5544 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005545 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005546 {
5547 if (state == eStateExited)
5548 {
5549 int exit_status = GetExitStatus();
5550 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005551 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005552 GetID(),
5553 exit_status,
5554 exit_status,
5555 exit_description ? exit_description : "");
5556 }
5557 else
5558 {
5559 if (state == eStateConnected)
5560 strm.Printf ("Connected to remote target.\n");
5561 else
Daniel Malead01b2952012-11-29 21:49:15 +00005562 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005563 }
5564 }
5565 else
5566 {
Daniel Malead01b2952012-11-29 21:49:15 +00005567 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005568 }
5569}
5570
5571size_t
5572Process::GetThreadStatus (Stream &strm,
5573 bool only_threads_with_stop_reason,
5574 uint32_t start_frame,
5575 uint32_t num_frames,
5576 uint32_t num_frames_with_source)
5577{
5578 size_t num_thread_infos_dumped = 0;
5579
Jim Ingham41f2b942012-09-10 20:50:15 +00005580 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005581 const size_t num_threads = GetThreadList().GetSize();
5582 for (uint32_t i = 0; i < num_threads; i++)
5583 {
5584 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5585 if (thread)
5586 {
5587 if (only_threads_with_stop_reason)
5588 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005589 StopInfoSP stop_info_sp = thread->GetStopInfo();
5590 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005591 continue;
5592 }
5593 thread->GetStatus (strm,
5594 start_frame,
5595 num_frames,
5596 num_frames_with_source);
5597 ++num_thread_infos_dumped;
5598 }
5599 }
5600 return num_thread_infos_dumped;
5601}
5602
Greg Claytona9f40ad2012-02-22 04:37:26 +00005603void
5604Process::AddInvalidMemoryRegion (const LoadRange &region)
5605{
5606 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5607}
5608
5609bool
5610Process::RemoveInvalidMemoryRange (const LoadRange &region)
5611{
5612 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5613}
5614
Jim Ingham372787f2012-04-07 00:00:41 +00005615void
5616Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5617{
5618 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5619}
5620
5621bool
5622Process::RunPreResumeActions ()
5623{
5624 bool result = true;
5625 while (!m_pre_resume_actions.empty())
5626 {
5627 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5628 m_pre_resume_actions.pop_back();
5629 bool this_result = action.callback (action.baton);
5630 if (result == true) result = this_result;
5631 }
5632 return result;
5633}
5634
5635void
5636Process::ClearPreResumeActions ()
5637{
5638 m_pre_resume_actions.clear();
5639}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005640
Greg Claytonfa559e52012-05-18 02:38:05 +00005641void
5642Process::Flush ()
5643{
5644 m_thread_list.Flush();
5645}
Greg Clayton90ba8112012-12-05 00:16:59 +00005646
5647void
5648Process::DidExec ()
5649{
5650 Target &target = GetTarget();
5651 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005652 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005653 m_dynamic_checkers_ap.reset();
5654 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005655 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005656 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005657 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005658 m_image_tokens.clear();
5659 m_allocated_memory_cache.Clear();
5660 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005661 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005662 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005663 DoDidExec();
5664 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005665 // Flush the process (threads and all stack frames) after running CompleteAttach()
5666 // in case the dynamic loader loaded things in new locations.
5667 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005668
5669 // After we figure out what was loaded/unloaded in CompleteAttach,
5670 // we need to let the target know so it can do any cleanup it needs to.
5671 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005672}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005673