blob: 3a8866c3fd063eb2dca0d7f7764921d624800996 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
21#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000022#include "lldb/Core/Module.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000023#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000026#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000027#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Host/Host.h"
Greg Clayton100eb932014-07-02 21:10:39 +000030#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000031#include "lldb/Host/Terminal.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000033#include "lldb/Target/DynamicLoader.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000034#include "lldb/Target/JITLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000035#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000036#include "lldb/Target/LanguageRuntime.h"
37#include "lldb/Target/CPPLanguageRuntime.h"
38#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000039#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000041#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000042#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/Target.h"
44#include "lldb/Target/TargetList.h"
45#include "lldb/Target/Thread.h"
46#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000047#include "lldb/Target/ThreadPlanBase.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000048#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049
Charles Davis510938e2013-08-27 05:04:57 +000050#ifndef LLDB_DISABLE_POSIX
51#include <spawn.h>
52#endif
53
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054using namespace lldb;
55using namespace lldb_private;
56
Greg Clayton67cc0632012-08-22 17:17:09 +000057
58// Comment out line below to disable memory caching, overriding the process setting
59// target.process.disable-memory-cache
60#define ENABLE_MEMORY_CACHING
61
62#ifdef ENABLE_MEMORY_CACHING
63#define DISABLE_MEM_CACHE_DEFAULT false
64#else
65#define DISABLE_MEM_CACHE_DEFAULT true
66#endif
67
68class ProcessOptionValueProperties : public OptionValueProperties
69{
70public:
71 ProcessOptionValueProperties (const ConstString &name) :
72 OptionValueProperties (name)
73 {
74 }
75
76 // This constructor is used when creating ProcessOptionValueProperties when it
77 // is part of a new lldb_private::Process instance. It will copy all current
78 // global property values as needed
79 ProcessOptionValueProperties (ProcessProperties *global_properties) :
80 OptionValueProperties(*global_properties->GetValueProperties())
81 {
82 }
83
84 virtual const Property *
85 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
86 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000087 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000088 // try and grab the setting from the current process if there is one. Else we just
89 // use the one from this instance.
90 if (exe_ctx)
91 {
92 Process *process = exe_ctx->GetProcessPtr();
93 if (process)
94 {
95 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
96 if (this != instance_properties)
97 return instance_properties->ProtectedGetPropertyAtIndex (idx);
98 }
99 }
100 return ProtectedGetPropertyAtIndex (idx);
101 }
102};
103
104static PropertyDefinition
105g_properties[] =
106{
107 { "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 +0000108 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
109 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000110 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
111 { "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 +0000112 { "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 +0000113 { "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 +0000114 { "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 +0000115 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
116};
117
118enum {
119 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000120 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000121 ePropertyIgnoreBreakpointsInExpressions,
122 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000123 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000124 ePropertyStopOnSharedLibraryEvents,
125 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000126};
127
128ProcessProperties::ProcessProperties (bool is_global) :
129 Properties ()
130{
131 if (is_global)
132 {
133 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
134 m_collection_sp->Initialize(g_properties);
135 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000136 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000137 true,
138 Thread::GetGlobalProperties()->GetValueProperties());
139 }
140 else
141 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
142}
143
144ProcessProperties::~ProcessProperties()
145{
146}
147
148bool
149ProcessProperties::GetDisableMemoryCache() const
150{
151 const uint32_t idx = ePropertyDisableMemCache;
152 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
153}
154
155Args
156ProcessProperties::GetExtraStartupCommands () const
157{
158 Args args;
159 const uint32_t idx = ePropertyExtraStartCommand;
160 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
161 return args;
162}
163
164void
165ProcessProperties::SetExtraStartupCommands (const Args &args)
166{
167 const uint32_t idx = ePropertyExtraStartCommand;
168 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
169}
170
Greg Claytonc9d645d2012-10-18 22:40:37 +0000171FileSpec
172ProcessProperties::GetPythonOSPluginPath () const
173{
174 const uint32_t idx = ePropertyPythonOSPluginPath;
175 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
176}
177
178void
179ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
180{
181 const uint32_t idx = ePropertyPythonOSPluginPath;
182 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
183}
184
Jim Ingham184e9812013-01-15 02:47:48 +0000185
186bool
187ProcessProperties::GetIgnoreBreakpointsInExpressions () const
188{
189 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
190 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
191}
192
193void
194ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
195{
196 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
197 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
198}
199
200bool
201ProcessProperties::GetUnwindOnErrorInExpressions () const
202{
203 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
204 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
205}
206
207void
208ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
209{
210 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
211 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
212}
213
Jim Ingham29950772013-01-26 02:19:28 +0000214bool
215ProcessProperties::GetStopOnSharedLibraryEvents () const
216{
217 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
218 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
219}
220
221void
222ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
223{
224 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
225 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
226}
227
Jim Inghamacff8952013-05-02 00:27:30 +0000228bool
229ProcessProperties::GetDetachKeepsStopped () const
230{
231 const uint32_t idx = ePropertyDetachKeepsStopped;
232 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
233}
234
235void
236ProcessProperties::SetDetachKeepsStopped (bool stop)
237{
238 const uint32_t idx = ePropertyDetachKeepsStopped;
239 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
240}
241
Greg Clayton32e0a752011-03-30 18:16:51 +0000242void
Greg Clayton8b82f082011-04-12 05:54:46 +0000243ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000244{
245 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000246 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000247 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000248
249 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000250 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000251
252 if (m_executable)
253 {
254 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
255 s.PutCString (" file = ");
256 m_executable.Dump(&s);
257 s.EOL();
258 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000259 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000260 if (argc > 0)
261 {
262 for (uint32_t i=0; i<argc; i++)
263 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000264 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000265 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000266 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000267 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000268 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000269 }
270 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000271
272 const uint32_t envc = m_environment.GetArgumentCount();
273 if (envc > 0)
274 {
275 for (uint32_t i=0; i<envc; i++)
276 {
277 const char *env = m_environment.GetArgumentAtIndex(i);
278 if (i < 10)
279 s.Printf (" env[%u] = %s\n", i, env);
280 else
281 s.Printf ("env[%u] = %s\n", i, env);
282 }
283 }
284
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000285 if (m_arch.IsValid())
286 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
287
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000289 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 cstr = platform->GetUserName (m_uid);
291 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000292 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000294 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000295 cstr = platform->GetGroupName (m_gid);
296 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000297 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000299 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 cstr = platform->GetUserName (m_euid);
301 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000302 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000303 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000304 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000305 cstr = platform->GetGroupName (m_egid);
306 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000307 }
308}
309
310void
Greg Clayton8b82f082011-04-12 05:54:46 +0000311ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000312{
Greg Clayton8b82f082011-04-12 05:54:46 +0000313 const char *label;
314 if (show_args || verbose)
315 label = "ARGUMENTS";
316 else
317 label = "NAME";
318
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000319 if (verbose)
320 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000322 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
323 }
324 else
325 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000326 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000327 s.PutCString ("====== ====== ========== ======= ============================\n");
328 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000329}
330
331void
Greg Clayton8b82f082011-04-12 05:54:46 +0000332ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000333{
334 if (m_pid != LLDB_INVALID_PROCESS_ID)
335 {
336 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000337 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000338
Greg Clayton32e0a752011-03-30 18:16:51 +0000339
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000340 if (verbose)
341 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000343 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
344 s.Printf ("%-10s ", cstr);
345 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000346 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000347
Greg Clayton8b82f082011-04-12 05:54:46 +0000348 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000349 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
350 s.Printf ("%-10s ", cstr);
351 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000352 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000353
Greg Clayton8b82f082011-04-12 05:54:46 +0000354 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000355 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
356 s.Printf ("%-10s ", cstr);
357 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000358 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000359
Greg Clayton8b82f082011-04-12 05:54:46 +0000360 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
362 s.Printf ("%-10s ", cstr);
363 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000364 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000365 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
366 }
367 else
368 {
Jason Molendafd54b362011-09-20 21:44:10 +0000369 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000371 (int)m_arch.GetTriple().getArchName().size(),
372 m_arch.GetTriple().getArchName().data());
373 }
374
Greg Clayton8b82f082011-04-12 05:54:46 +0000375 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000376 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000377 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000378 if (argc > 0)
379 {
380 for (uint32_t i=0; i<argc; i++)
381 {
382 if (i > 0)
383 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000384 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000385 }
386 }
387 }
388 else
389 {
390 s.PutCString (GetName());
391 }
392
393 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000394 }
395}
396
Greg Clayton8b82f082011-04-12 05:54:46 +0000397Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000398ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000399{
400 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000401 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000402
403 switch (short_option)
404 {
405 case 's': // Stop at program entry point
406 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
407 break;
408
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 case 'i': // STDIN for read only
410 {
411 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000412 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000413 launch_info.AppendFileAction (action);
414 }
415 break;
416
417 case 'o': // Open STDOUT for write only
418 {
419 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000420 if (action.Open (STDOUT_FILENO, option_arg, false, true))
421 launch_info.AppendFileAction (action);
422 }
423 break;
424
425 case 'e': // STDERR for write only
426 {
427 ProcessLaunchInfo::FileAction action;
428 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 launch_info.AppendFileAction (action);
430 }
431 break;
432
Greg Clayton9845a8d2012-03-06 04:01:04 +0000433
Greg Clayton8b82f082011-04-12 05:54:46 +0000434 case 'p': // Process plug-in name
435 launch_info.SetProcessPluginName (option_arg);
436 break;
437
438 case 'n': // Disable STDIO
439 {
440 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000441 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000442 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000443 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000444 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000445 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000446 launch_info.AppendFileAction (action);
447 }
448 break;
449
450 case 'w':
451 launch_info.SetWorkingDirectory (option_arg);
452 break;
453
454 case 't': // Open process in new terminal window
455 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
456 break;
457
458 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000459 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
460 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000461 break;
462
463 case 'A':
464 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
465 break;
466
Greg Clayton982c9762011-11-03 21:22:33 +0000467 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000468 if (option_arg && option_arg[0])
469 launch_info.SetShell (option_arg);
470 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000471 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000472 break;
473
Greg Clayton8b82f082011-04-12 05:54:46 +0000474 case 'v':
475 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
476 break;
477
478 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000479 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000480 break;
481
482 }
483 return error;
484}
485
486OptionDefinition
487ProcessLaunchCommandOptions::g_option_table[] =
488{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000489{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
490{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
491{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
492{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
493{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
494{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
495{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000496
Zachary Turnerd37221d2014-07-09 16:31:49 +0000497{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
498{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
499{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000500
Zachary Turnerd37221d2014-07-09 16:31:49 +0000501{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000502
Zachary Turnerd37221d2014-07-09 16:31:49 +0000503{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000504
Zachary Turnerd37221d2014-07-09 16:31:49 +0000505{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000506};
507
508
509
510bool
511ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000512{
513 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
514 return true;
515 const char *match_name = m_match_info.GetName();
516 if (!match_name)
517 return true;
518
519 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
520}
521
522bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000523ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000524{
525 if (!NameMatches (proc_info.GetName()))
526 return false;
527
528 if (m_match_info.ProcessIDIsValid() &&
529 m_match_info.GetProcessID() != proc_info.GetProcessID())
530 return false;
531
532 if (m_match_info.ParentProcessIDIsValid() &&
533 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
534 return false;
535
Greg Clayton8b82f082011-04-12 05:54:46 +0000536 if (m_match_info.UserIDIsValid () &&
537 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000538 return false;
539
Greg Clayton8b82f082011-04-12 05:54:46 +0000540 if (m_match_info.GroupIDIsValid () &&
541 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000542 return false;
543
544 if (m_match_info.EffectiveUserIDIsValid () &&
545 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
546 return false;
547
548 if (m_match_info.EffectiveGroupIDIsValid () &&
549 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
550 return false;
551
552 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000553 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000554 return false;
555 return true;
556}
557
558bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000559ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000560{
561 if (m_name_match_type != eNameMatchIgnore)
562 return false;
563
564 if (m_match_info.ProcessIDIsValid())
565 return false;
566
567 if (m_match_info.ParentProcessIDIsValid())
568 return false;
569
Greg Clayton8b82f082011-04-12 05:54:46 +0000570 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000571 return false;
572
Greg Clayton8b82f082011-04-12 05:54:46 +0000573 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000574 return false;
575
576 if (m_match_info.EffectiveUserIDIsValid ())
577 return false;
578
579 if (m_match_info.EffectiveGroupIDIsValid ())
580 return false;
581
582 if (m_match_info.GetArchitecture().IsValid())
583 return false;
584
585 if (m_match_all_users)
586 return false;
587
588 return true;
589
590}
591
592void
Greg Clayton8b82f082011-04-12 05:54:46 +0000593ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000594{
595 m_match_info.Clear();
596 m_name_match_type = eNameMatchIgnore;
597 m_match_all_users = false;
598}
Greg Clayton58be07b2011-01-07 06:08:19 +0000599
Greg Claytonc3776bf2012-02-09 06:16:32 +0000600ProcessSP
601Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602{
Greg Clayton949e8222013-01-16 17:29:04 +0000603 static uint32_t g_process_unique_id = 0;
604
Greg Claytonc3776bf2012-02-09 06:16:32 +0000605 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606 ProcessCreateInstance create_callback = NULL;
607 if (plugin_name)
608 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000609 ConstString const_plugin_name(plugin_name);
610 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 if (create_callback)
612 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000613 process_sp = create_callback(target, listener, crash_file_path);
614 if (process_sp)
615 {
Greg Clayton949e8222013-01-16 17:29:04 +0000616 if (process_sp->CanDebug(target, true))
617 {
618 process_sp->m_process_unique_id = ++g_process_unique_id;
619 }
620 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000621 process_sp.reset();
622 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623 }
624 }
625 else
626 {
Greg Claytonc982c762010-07-09 20:39:50 +0000627 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000629 process_sp = create_callback(target, listener, crash_file_path);
630 if (process_sp)
631 {
Greg Clayton949e8222013-01-16 17:29:04 +0000632 if (process_sp->CanDebug(target, false))
633 {
634 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000635 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000636 }
637 else
638 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000639 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 }
641 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000642 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643}
644
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000645ConstString &
646Process::GetStaticBroadcasterClass ()
647{
648 static ConstString class_name ("lldb.process");
649 return class_name;
650}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651
652//----------------------------------------------------------------------
653// Process constructor
654//----------------------------------------------------------------------
655Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000656 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000658 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 m_public_state (eStateUnloaded),
661 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000662 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
663 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 m_private_state_listener ("lldb.process.internal_state_listener"),
665 m_private_state_control_wait(),
666 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000667 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000668 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000670 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671 m_exit_status (-1),
672 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000673 m_thread_mutex (Mutex::eMutexTypeRecursive),
674 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000676 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000677 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000678 m_queue_list (this),
679 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000681 m_image_tokens (),
682 m_listener (listener),
683 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000684 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000685 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000686 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000687 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000688 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000689 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000690 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000691 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000692 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
693 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000694 m_memory_cache (*this),
695 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000696 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000697 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000698 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000699 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000700 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000701 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000702 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000703 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000704 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000705 m_destroy_in_process (false),
706 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000708 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000709
Greg Clayton5160ce52013-03-27 23:08:40 +0000710 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000712 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000714 SetEventName (eBroadcastBitStateChanged, "state-changed");
715 SetEventName (eBroadcastBitInterrupt, "interrupt");
716 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
717 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000718 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000719
Greg Clayton35a4cc52012-10-29 20:52:08 +0000720 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
721 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
722 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
723
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 listener.StartListeningForEvents (this,
725 eBroadcastBitStateChanged |
726 eBroadcastBitInterrupt |
727 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000728 eBroadcastBitSTDERR |
729 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730
731 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000732 eBroadcastBitStateChanged |
733 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734
735 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
736 eBroadcastInternalStateControlStop |
737 eBroadcastInternalStateControlPause |
738 eBroadcastInternalStateControlResume);
739}
740
741//----------------------------------------------------------------------
742// Destructor
743//----------------------------------------------------------------------
744Process::~Process()
745{
Greg Clayton5160ce52013-03-27 23:08:40 +0000746 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000748 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749 StopPrivateStateThread();
750}
751
Greg Clayton67cc0632012-08-22 17:17:09 +0000752const ProcessPropertiesSP &
753Process::GetGlobalProperties()
754{
755 static ProcessPropertiesSP g_settings_sp;
756 if (!g_settings_sp)
757 g_settings_sp.reset (new ProcessProperties (true));
758 return g_settings_sp;
759}
760
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761void
762Process::Finalize()
763{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000764 switch (GetPrivateState())
765 {
766 case eStateConnected:
767 case eStateAttaching:
768 case eStateLaunching:
769 case eStateStopped:
770 case eStateRunning:
771 case eStateStepping:
772 case eStateCrashed:
773 case eStateSuspended:
774 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000775 {
776 // FIXME: This will have to be a process setting:
777 bool keep_stopped = false;
778 Detach(keep_stopped);
779 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000780 else
781 Destroy();
782 break;
783
784 case eStateInvalid:
785 case eStateUnloaded:
786 case eStateDetached:
787 case eStateExited:
788 break;
789 }
790
Greg Clayton1ed54f52011-10-01 00:45:15 +0000791 // Clear our broadcaster before we proceed with destroying
792 Broadcaster::Clear();
793
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794 // Do any cleanup needed prior to being destructed... Subclasses
795 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000796
797 // We need to destroy the loader before the derived Process class gets destroyed
798 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000799 m_dynamic_checkers_ap.reset();
800 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000801 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000802 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000803 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000804 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000805 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000806 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000807 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000808 m_queue_list.Clear();
809 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000810 std::vector<Notifications> empty_notifications;
811 m_notifications.swap(empty_notifications);
812 m_image_tokens.clear();
813 m_memory_cache.Clear();
814 m_allocated_memory_cache.Clear();
815 m_language_runtimes.clear();
816 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000817//#ifdef LLDB_CONFIGURATION_DEBUG
818// StreamFile s(stdout, false);
819// EventSP event_sp;
820// while (m_private_state_listener.GetNextEvent(event_sp))
821// {
822// event_sp->Dump (&s);
823// s.EOL();
824// }
825//#endif
826 // We have to be very careful here as the m_private_state_listener might
827 // contain events that have ProcessSP values in them which can keep this
828 // process around forever. These events need to be cleared out.
829 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000830 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
831 m_public_run_lock.SetStopped();
832 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
833 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000834 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835}
836
837void
838Process::RegisterNotificationCallbacks (const Notifications& callbacks)
839{
840 m_notifications.push_back(callbacks);
841 if (callbacks.initialize != NULL)
842 callbacks.initialize (callbacks.baton, this);
843}
844
845bool
846Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
847{
848 std::vector<Notifications>::iterator pos, end = m_notifications.end();
849 for (pos = m_notifications.begin(); pos != end; ++pos)
850 {
851 if (pos->baton == callbacks.baton &&
852 pos->initialize == callbacks.initialize &&
853 pos->process_state_changed == callbacks.process_state_changed)
854 {
855 m_notifications.erase(pos);
856 return true;
857 }
858 }
859 return false;
860}
861
862void
863Process::SynchronouslyNotifyStateChanged (StateType state)
864{
865 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
866 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
867 {
868 if (notification_pos->process_state_changed)
869 notification_pos->process_state_changed (notification_pos->baton, this, state);
870 }
871}
872
873// FIXME: We need to do some work on events before the general Listener sees them.
874// For instance if we are continuing from a breakpoint, we need to ensure that we do
875// the little "insert real insn, step & stop" trick. But we can't do that when the
876// event is delivered by the broadcaster - since that is done on the thread that is
877// waiting for new events, so if we needed more than one event for our handling, we would
878// stall. So instead we do it when we fetch the event off of the queue.
879//
880
881StateType
882Process::GetNextEvent (EventSP &event_sp)
883{
884 StateType state = eStateInvalid;
885
886 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
887 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
888
889 return state;
890}
891
892
893StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000894Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000895{
Jim Ingham4b536182011-08-09 02:12:22 +0000896 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
897 // We have to actually check each event, and in the case of a stopped event check the restarted flag
898 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000899 if (event_sp_ptr)
900 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000901 StateType state = GetState();
902 // If we are exited or detached, we won't ever get back to any
903 // other valid state...
904 if (state == eStateDetached || state == eStateExited)
905 return state;
906
Daniel Malea9e9919f2013-10-09 16:56:28 +0000907 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
908 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000909 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
910 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000911
912 if (!wait_always &&
913 StateIsStoppedState(state, true) &&
914 StateIsStoppedState(GetPrivateState(), true)) {
915 if (log)
916 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
917 __FUNCTION__);
918 return state;
919 }
920
Jim Ingham4b536182011-08-09 02:12:22 +0000921 while (state != eStateInvalid)
922 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000923 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000924 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000925 if (event_sp_ptr && event_sp)
926 *event_sp_ptr = event_sp;
927
Jim Ingham4b536182011-08-09 02:12:22 +0000928 switch (state)
929 {
930 case eStateCrashed:
931 case eStateDetached:
932 case eStateExited:
933 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000934 // We need to toggle the run lock as this won't get done in
935 // SetPublicState() if the process is hijacked.
936 if (hijack_listener)
937 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000938 return state;
939 case eStateStopped:
940 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
941 continue;
942 else
Greg Clayton44d93782014-01-27 23:43:24 +0000943 {
944 // We need to toggle the run lock as this won't get done in
945 // SetPublicState() if the process is hijacked.
946 if (hijack_listener)
947 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000948 return state;
Greg Clayton44d93782014-01-27 23:43:24 +0000949 }
Jim Ingham4b536182011-08-09 02:12:22 +0000950 default:
951 continue;
952 }
953 }
954 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955}
956
957
958StateType
959Process::WaitForState
960(
961 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +0000962 const StateType *match_states,
963 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964)
965{
966 EventSP event_sp;
967 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000968 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969 while (state != eStateInvalid)
970 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000971 // If we are exited or detached, we won't ever get back to any
972 // other valid state...
973 if (state == eStateDetached || state == eStateExited)
974 return state;
975
Greg Clayton44d93782014-01-27 23:43:24 +0000976 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977
978 for (i=0; i<num_match_states; ++i)
979 {
980 if (match_states[i] == state)
981 return state;
982 }
983 }
984 return state;
985}
986
Jim Ingham30f9b212010-10-11 23:53:14 +0000987bool
988Process::HijackProcessEvents (Listener *listener)
989{
990 if (listener != NULL)
991 {
Jim Inghamcfc09352012-07-27 23:57:19 +0000992 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +0000993 }
994 else
995 return false;
996}
997
998void
999Process::RestoreProcessEvents ()
1000{
1001 RestoreBroadcaster();
1002}
1003
Jim Ingham0f16e732011-02-08 05:20:59 +00001004bool
1005Process::HijackPrivateProcessEvents (Listener *listener)
1006{
1007 if (listener != NULL)
1008 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001009 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001010 }
1011 else
1012 return false;
1013}
1014
1015void
1016Process::RestorePrivateProcessEvents ()
1017{
1018 m_private_state_broadcaster.RestoreBroadcaster();
1019}
1020
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001022Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023{
Greg Clayton5160ce52013-03-27 23:08:40 +00001024 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025
1026 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001027 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1028 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001029
Greg Clayton44d93782014-01-27 23:43:24 +00001030 Listener *listener = hijack_listener;
1031 if (listener == NULL)
1032 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001033
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001035 if (listener->WaitForEventForBroadcasterWithType (timeout,
1036 this,
1037 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1038 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001039 {
1040 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1041 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1042 else if (log)
1043 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1044 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045
1046 if (log)
1047 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001048 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049 StateAsCString(state));
1050 return state;
1051}
1052
1053Event *
1054Process::PeekAtStateChangedEvents ()
1055{
Greg Clayton5160ce52013-03-27 23:08:40 +00001056 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057
1058 if (log)
1059 log->Printf ("Process::%s...", __FUNCTION__);
1060
1061 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001062 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1063 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001064 if (log)
1065 {
1066 if (event_ptr)
1067 {
1068 log->Printf ("Process::%s (event_ptr) => %s",
1069 __FUNCTION__,
1070 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1071 }
1072 else
1073 {
1074 log->Printf ("Process::%s no events found",
1075 __FUNCTION__);
1076 }
1077 }
1078 return event_ptr;
1079}
1080
1081StateType
1082Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1083{
Greg Clayton5160ce52013-03-27 23:08:40 +00001084 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085
1086 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001087 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1088 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089
1090 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001091 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1092 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001093 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001094 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001095 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1096 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001097
1098 // This is a bit of a hack, but when we wait here we could very well return
1099 // to the command-line, and that could disable the log, which would render the
1100 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001102 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1103 __FUNCTION__, static_cast<const void *>(timeout),
1104 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105 return state;
1106}
1107
1108bool
1109Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1110{
Greg Clayton5160ce52013-03-27 23:08:40 +00001111 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112
1113 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001114 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1115 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116
1117 if (control_only)
1118 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1119 else
1120 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1121}
1122
1123bool
1124Process::IsRunning () const
1125{
1126 return StateIsRunningState (m_public_state.GetValue());
1127}
1128
1129int
1130Process::GetExitStatus ()
1131{
1132 if (m_public_state.GetValue() == eStateExited)
1133 return m_exit_status;
1134 return -1;
1135}
1136
Greg Clayton85851dd2010-12-04 00:10:17 +00001137
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138const char *
1139Process::GetExitDescription ()
1140{
1141 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1142 return m_exit_string.c_str();
1143 return NULL;
1144}
1145
Greg Clayton6779606a2011-01-22 23:43:18 +00001146bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147Process::SetExitStatus (int status, const char *cstr)
1148{
Greg Clayton5160ce52013-03-27 23:08:40 +00001149 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001150 if (log)
1151 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1152 status, status,
1153 cstr ? "\"" : "",
1154 cstr ? cstr : "NULL",
1155 cstr ? "\"" : "");
1156
Greg Clayton6779606a2011-01-22 23:43:18 +00001157 // We were already in the exited state
1158 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001159 {
Greg Clayton385d6032011-01-26 23:47:29 +00001160 if (log)
1161 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001162 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001163 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001164
1165 m_exit_status = status;
1166 if (cstr)
1167 m_exit_string = cstr;
1168 else
1169 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170
Greg Clayton6779606a2011-01-22 23:43:18 +00001171 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001172
Greg Clayton6779606a2011-01-22 23:43:18 +00001173 SetPrivateState (eStateExited);
1174 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175}
1176
1177// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001178// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179// found in the global target list (we want to be completely sure that the
1180// lldb_private::Process doesn't go away before we can deliver the signal.
1181bool
Greg Claytone4e45922011-11-16 05:37:56 +00001182Process::SetProcessExitStatus (void *callback_baton,
1183 lldb::pid_t pid,
1184 bool exited,
1185 int signo, // Zero for no signal
1186 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187)
1188{
Greg Clayton5160ce52013-03-27 23:08:40 +00001189 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001190 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001191 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001192 callback_baton,
1193 pid,
1194 exited,
1195 signo,
1196 exit_status);
1197
1198 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199 {
Greg Clayton66111032010-06-23 01:19:29 +00001200 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201 if (target_sp)
1202 {
1203 ProcessSP process_sp (target_sp->GetProcessSP());
1204 if (process_sp)
1205 {
1206 const char *signal_cstr = NULL;
1207 if (signo)
1208 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1209
1210 process_sp->SetExitStatus (exit_status, signal_cstr);
1211 }
1212 }
1213 return true;
1214 }
1215 return false;
1216}
1217
1218
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001219void
1220Process::UpdateThreadListIfNeeded ()
1221{
1222 const uint32_t stop_id = GetStopID();
1223 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1224 {
Greg Clayton2637f822011-11-17 01:23:07 +00001225 const StateType state = GetPrivateState();
1226 if (StateIsStoppedState (state, true))
1227 {
1228 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001229 // m_thread_list does have its own mutex, but we need to
1230 // hold onto the mutex between the call to UpdateThreadList(...)
1231 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001232 ThreadList &old_thread_list = m_thread_list;
1233 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001234 ThreadList new_thread_list(this);
1235 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001236 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001237 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001238 {
Jim Ingham09437922013-03-01 20:04:25 +00001239 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1240 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1241 // shutting us down, causing a deadlock.
1242 if (!m_destroy_in_process)
1243 {
1244 OperatingSystem *os = GetOperatingSystem ();
1245 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001246 {
1247 // Clear any old backing threads where memory threads might have been
1248 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001249 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001250 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001251 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001252
1253 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001254 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1255 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1256 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 +00001257 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001258 else
1259 {
1260 // No OS plug-in, the new thread list is the same as the real thread list
1261 new_thread_list = real_thread_list;
1262 }
Jim Ingham09437922013-03-01 20:04:25 +00001263 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001264
1265 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001266 m_thread_list.Update (new_thread_list);
1267 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001268
Jason Molenda4ff13262013-11-20 00:31:38 +00001269 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1270 {
1271 // Clear any extended threads that we may have accumulated previously
1272 m_extended_thread_list.Clear();
1273 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001274
1275 m_queue_list.Clear();
1276 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001277 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001278 }
Greg Clayton2637f822011-11-17 01:23:07 +00001279 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001280 }
1281}
1282
Jason Molenda5e8dce42013-12-13 00:29:16 +00001283void
1284Process::UpdateQueueListIfNeeded ()
1285{
1286 if (m_system_runtime_ap.get())
1287 {
1288 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1289 {
1290 const StateType state = GetPrivateState();
1291 if (StateIsStoppedState (state, true))
1292 {
1293 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1294 m_queue_list_stop_id = GetLastNaturalStopID();
1295 }
1296 }
1297 }
1298}
1299
Greg Claytona4d87472013-01-18 23:41:08 +00001300ThreadSP
1301Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1302{
1303 OperatingSystem *os = GetOperatingSystem ();
1304 if (os)
1305 return os->CreateThread(tid, context);
1306 return ThreadSP();
1307}
1308
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001309uint32_t
1310Process::GetNextThreadIndexID (uint64_t thread_id)
1311{
1312 return AssignIndexIDToThread(thread_id);
1313}
1314
1315bool
1316Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1317{
1318 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1319 if (iterator == m_thread_id_to_index_id_map.end())
1320 {
1321 return false;
1322 }
1323 else
1324 {
1325 return true;
1326 }
1327}
1328
1329uint32_t
1330Process::AssignIndexIDToThread(uint64_t thread_id)
1331{
1332 uint32_t result = 0;
1333 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1334 if (iterator == m_thread_id_to_index_id_map.end())
1335 {
1336 result = ++m_thread_index_id;
1337 m_thread_id_to_index_id_map[thread_id] = result;
1338 }
1339 else
1340 {
1341 result = iterator->second;
1342 }
1343
1344 return result;
1345}
1346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347StateType
1348Process::GetState()
1349{
1350 // If any other threads access this we will need a mutex for it
1351 return m_public_state.GetValue ();
1352}
1353
1354void
Jim Ingham221d51c2013-05-08 00:35:16 +00001355Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356{
Greg Clayton5160ce52013-03-27 23:08:40 +00001357 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001358 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001359 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001360 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001362
1363 // On the transition from Run to Stopped, we unlock the writer end of the
1364 // run lock. The lock gets locked in Resume, which is the public API
1365 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001366 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1367 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001368 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001369 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001370 if (log)
1371 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001372 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001373 }
1374 else
1375 {
1376 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1377 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001378 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001379 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001380 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001381 {
1382 if (log)
1383 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001384 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001385 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001386 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001387 }
1388 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001389}
1390
Jim Ingham3b8285d2012-04-19 01:40:33 +00001391Error
1392Process::Resume ()
1393{
Greg Clayton5160ce52013-03-27 23:08:40 +00001394 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001395 if (log)
1396 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001397 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001398 {
1399 Error error("Resume request failed - process still running.");
1400 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001401 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001402 return error;
1403 }
1404 return PrivateResume();
1405}
1406
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001407StateType
1408Process::GetPrivateState ()
1409{
1410 return m_private_state.GetValue();
1411}
1412
1413void
1414Process::SetPrivateState (StateType new_state)
1415{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001416 if (m_finalize_called)
1417 return;
1418
Greg Clayton5160ce52013-03-27 23:08:40 +00001419 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420 bool state_changed = false;
1421
1422 if (log)
1423 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1424
Andrew Kaylor29d65742013-05-10 17:19:04 +00001425 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001426 Mutex::Locker locker(m_private_state.GetMutex());
1427
1428 const StateType old_state = m_private_state.GetValueNoLock ();
1429 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001430
Greg Claytonaa49c832013-05-03 22:25:56 +00001431 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1432 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1433 if (old_state_is_stopped != new_state_is_stopped)
1434 {
1435 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001436 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001437 else
Ed Maste64fad602013-07-29 20:58:06 +00001438 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001439 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001440
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441 if (state_changed)
1442 {
1443 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001444 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001445 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001446 // Note, this currently assumes that all threads in the list
1447 // stop when the process stops. In the future we will want to
1448 // support a debugging model where some threads continue to run
1449 // while others are stopped. When that happens we will either need
1450 // a way for the thread list to identify which threads are stopping
1451 // or create a special thread list containing only threads which
1452 // actually stopped.
1453 //
1454 // The process plugin is responsible for managing the actual
1455 // behavior of the threads and should have stopped any threads
1456 // that are going to stop before we get here.
1457 m_thread_list.DidStop();
1458
Jim Ingham4b536182011-08-09 02:12:22 +00001459 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001460 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001461 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001462 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001463 }
1464 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001465 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1466 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1467 else
1468 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469 }
1470 else
1471 {
1472 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001473 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474 }
1475}
1476
Jim Ingham0faa43f2011-11-08 03:00:11 +00001477void
1478Process::SetRunningUserExpression (bool on)
1479{
1480 m_mod_id.SetRunningUserExpression (on);
1481}
1482
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001483addr_t
1484Process::GetImageInfoAddress()
1485{
1486 return LLDB_INVALID_ADDRESS;
1487}
1488
Greg Clayton8f343b02010-11-04 01:54:29 +00001489//----------------------------------------------------------------------
1490// LoadImage
1491//
1492// This function provides a default implementation that works for most
1493// unix variants. Any Process subclasses that need to do shared library
1494// loading differently should override LoadImage and UnloadImage and
1495// do what is needed.
1496//----------------------------------------------------------------------
1497uint32_t
1498Process::LoadImage (const FileSpec &image_spec, Error &error)
1499{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001500 char path[PATH_MAX];
1501 image_spec.GetPath(path, sizeof(path));
1502
Greg Clayton8f343b02010-11-04 01:54:29 +00001503 DynamicLoader *loader = GetDynamicLoader();
1504 if (loader)
1505 {
1506 error = loader->CanLoadImage();
1507 if (error.Fail())
1508 return LLDB_INVALID_IMAGE_TOKEN;
1509 }
1510
1511 if (error.Success())
1512 {
1513 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001514
1515 if (thread_sp)
1516 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001517 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001518
1519 if (frame_sp)
1520 {
1521 ExecutionContext exe_ctx;
1522 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001523 EvaluateExpressionOptions expr_options;
1524 expr_options.SetUnwindOnError(true);
1525 expr_options.SetIgnoreBreakpoints(true);
1526 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001527 expr_options.SetResultIsInternal(true);
1528
Greg Clayton8f343b02010-11-04 01:54:29 +00001529 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001530 expr.Printf(R"(
1531 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1532 the_result.image_ptr = dlopen ("%s", 2);
1533 if (the_result.image_ptr == (void *) 0x0)
1534 {
1535 the_result.error_str = dlerror();
1536 }
1537 else
1538 {
1539 the_result.error_str = (const char *) 0x0;
1540 }
1541 the_result;
1542 )",
1543 path);
1544 const char *prefix = R"(
1545 extern "C" void* dlopen (const char *path, int mode);
1546 extern "C" const char *dlerror (void);
1547 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001548 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001549 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001550 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001551 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001552 expr.GetData(),
1553 prefix,
1554 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001555 expr_error);
1556 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001557 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001558 error = result_valobj_sp->GetError();
1559 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001560 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001561 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001562 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1563 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001564 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001565 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1566 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1567 {
1568 uint32_t image_token = m_image_tokens.size();
1569 m_image_tokens.push_back (image_ptr);
1570 return image_token;
1571 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001572 else if (image_ptr == 0)
1573 {
Jim Ingham6971b862014-07-19 00:37:06 +00001574 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1575 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001576 {
Jim Ingham6971b862014-07-19 00:37:06 +00001577 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001578 {
Jim Inghamcf973792014-07-17 21:53:48 +00001579 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001580 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001581 if (error.Success() && num_chars > 0)
1582 {
1583 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001584 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001585 }
1586 }
1587 }
1588 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001589 }
1590 }
1591 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001592 else
1593 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001594 }
1595 }
1596 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001597 if (!error.AsCString())
1598 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001599 return LLDB_INVALID_IMAGE_TOKEN;
1600}
1601
1602//----------------------------------------------------------------------
1603// UnloadImage
1604//
1605// This function provides a default implementation that works for most
1606// unix variants. Any Process subclasses that need to do shared library
1607// loading differently should override LoadImage and UnloadImage and
1608// do what is needed.
1609//----------------------------------------------------------------------
1610Error
1611Process::UnloadImage (uint32_t image_token)
1612{
1613 Error error;
1614 if (image_token < m_image_tokens.size())
1615 {
1616 const addr_t image_addr = m_image_tokens[image_token];
1617 if (image_addr == LLDB_INVALID_ADDRESS)
1618 {
1619 error.SetErrorString("image already unloaded");
1620 }
1621 else
1622 {
1623 DynamicLoader *loader = GetDynamicLoader();
1624 if (loader)
1625 error = loader->CanLoadImage();
1626
1627 if (error.Success())
1628 {
1629 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001630
1631 if (thread_sp)
1632 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001633 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001634
1635 if (frame_sp)
1636 {
1637 ExecutionContext exe_ctx;
1638 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001639 EvaluateExpressionOptions expr_options;
1640 expr_options.SetUnwindOnError(true);
1641 expr_options.SetIgnoreBreakpoints(true);
1642 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001643 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001644 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001645 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001646 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001647 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001648 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001649 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001650 expr.GetData(),
1651 prefix,
1652 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001653 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001654 if (result_valobj_sp->GetError().Success())
1655 {
1656 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001657 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001658 {
1659 if (scalar.UInt(1))
1660 {
1661 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1662 }
1663 else
1664 {
1665 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1666 }
1667 }
1668 }
1669 else
1670 {
1671 error = result_valobj_sp->GetError();
1672 }
1673 }
1674 }
1675 }
1676 }
1677 }
1678 else
1679 {
1680 error.SetErrorString("invalid image token");
1681 }
1682 return error;
1683}
1684
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001685const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686Process::GetABI()
1687{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001688 if (!m_abi_sp)
1689 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1690 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001691}
1692
Jim Ingham22777012010-09-23 02:01:19 +00001693LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001694Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001695{
1696 LanguageRuntimeCollection::iterator pos;
1697 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001698 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001699 {
Jim Inghamab175242012-03-10 00:22:19 +00001700 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001701
Jim Inghamab175242012-03-10 00:22:19 +00001702 m_language_runtimes[language] = runtime_sp;
1703 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001704 }
1705 else
1706 return (*pos).second.get();
1707}
1708
1709CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001710Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001711{
Jim Inghamab175242012-03-10 00:22:19 +00001712 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001713 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1714 return static_cast<CPPLanguageRuntime *> (runtime);
1715 return NULL;
1716}
1717
1718ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001719Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001720{
Jim Inghamab175242012-03-10 00:22:19 +00001721 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001722 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1723 return static_cast<ObjCLanguageRuntime *> (runtime);
1724 return NULL;
1725}
1726
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001727bool
1728Process::IsPossibleDynamicValue (ValueObject& in_value)
1729{
1730 if (in_value.IsDynamic())
1731 return false;
1732 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1733
1734 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1735 {
1736 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1737 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1738 }
1739
1740 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1741 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1742 return true;
1743
1744 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1745 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1746}
1747
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001748BreakpointSiteList &
1749Process::GetBreakpointSiteList()
1750{
1751 return m_breakpoint_site_list;
1752}
1753
1754const BreakpointSiteList &
1755Process::GetBreakpointSiteList() const
1756{
1757 return m_breakpoint_site_list;
1758}
1759
1760
1761void
1762Process::DisableAllBreakpointSites ()
1763{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001764 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1765// bp_site->SetEnabled(true);
1766 DisableBreakpointSite(bp_site);
1767 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001768}
1769
1770Error
1771Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1772{
1773 Error error (DisableBreakpointSiteByID (break_id));
1774
1775 if (error.Success())
1776 m_breakpoint_site_list.Remove(break_id);
1777
1778 return error;
1779}
1780
1781Error
1782Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1783{
1784 Error error;
1785 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1786 if (bp_site_sp)
1787 {
1788 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001789 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790 }
1791 else
1792 {
Daniel Malead01b2952012-11-29 21:49:15 +00001793 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 }
1795
1796 return error;
1797}
1798
1799Error
1800Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1801{
1802 Error error;
1803 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1804 if (bp_site_sp)
1805 {
1806 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001807 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 }
1809 else
1810 {
Daniel Malead01b2952012-11-29 21:49:15 +00001811 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 }
1813 return error;
1814}
1815
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001816lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001817Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001819 addr_t load_addr = LLDB_INVALID_ADDRESS;
1820
1821 bool show_error = true;
1822 switch (GetState())
1823 {
1824 case eStateInvalid:
1825 case eStateUnloaded:
1826 case eStateConnected:
1827 case eStateAttaching:
1828 case eStateLaunching:
1829 case eStateDetached:
1830 case eStateExited:
1831 show_error = false;
1832 break;
1833
1834 case eStateStopped:
1835 case eStateRunning:
1836 case eStateStepping:
1837 case eStateCrashed:
1838 case eStateSuspended:
1839 show_error = IsAlive();
1840 break;
1841 }
1842
1843 // Reset the IsIndirect flag here, in case the location changes from
1844 // pointing to a indirect symbol to a regular symbol.
1845 owner->SetIsIndirect (false);
1846
1847 if (owner->ShouldResolveIndirectFunctions())
1848 {
1849 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1850 if (symbol && symbol->IsIndirect())
1851 {
1852 Error error;
1853 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1854 if (!error.Success() && show_error)
1855 {
Greg Clayton44d93782014-01-27 23:43:24 +00001856 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1857 symbol->GetAddress().GetLoadAddress(&m_target),
1858 owner->GetBreakpoint().GetID(),
1859 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001860 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001861 return LLDB_INVALID_BREAK_ID;
1862 }
1863 Address resolved_address(load_addr);
1864 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1865 owner->SetIsIndirect(true);
1866 }
1867 else
1868 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1869 }
1870 else
1871 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1872
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873 if (load_addr != LLDB_INVALID_ADDRESS)
1874 {
1875 BreakpointSiteSP bp_site_sp;
1876
1877 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1878 // create a new breakpoint site and add it.
1879
1880 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1881
1882 if (bp_site_sp)
1883 {
1884 bp_site_sp->AddOwner (owner);
1885 owner->SetBreakpointSite (bp_site_sp);
1886 return bp_site_sp->GetID();
1887 }
1888 else
1889 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001890 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001891 if (bp_site_sp)
1892 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001893 Error error = EnableBreakpointSite (bp_site_sp.get());
1894 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001895 {
1896 owner->SetBreakpointSite (bp_site_sp);
1897 return m_breakpoint_site_list.Add (bp_site_sp);
1898 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001899 else
1900 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001901 if (show_error)
1902 {
1903 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001904 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1905 load_addr,
1906 owner->GetBreakpoint().GetID(),
1907 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001908 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001909 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001910 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911 }
1912 }
1913 }
1914 // We failed to enable the breakpoint
1915 return LLDB_INVALID_BREAK_ID;
1916
1917}
1918
1919void
1920Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1921{
1922 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1923 if (num_owners == 0)
1924 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001925 // Don't try to disable the site if we don't have a live process anymore.
1926 if (IsAlive())
1927 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001928 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1929 }
1930}
1931
1932
1933size_t
1934Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1935{
1936 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001937 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938
Jim Ingham20c77192011-06-29 19:42:28 +00001939 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001941 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1942 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001943 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001944 addr_t intersect_addr;
1945 size_t intersect_size;
1946 size_t opcode_offset;
1947 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001948 {
1949 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1950 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00001951 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001952 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00001953 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001954 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00001956 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957 }
1958 return bytes_removed;
1959}
1960
1961
Greg Claytonded470d2011-03-19 01:12:21 +00001962
1963size_t
1964Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1965{
1966 PlatformSP platform_sp (m_target.GetPlatform());
1967 if (platform_sp)
1968 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1969 return 0;
1970}
1971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972Error
1973Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1974{
1975 Error error;
1976 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00001977 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978 const addr_t bp_addr = bp_site->GetLoadAddress();
1979 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001980 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001981 if (bp_site->IsEnabled())
1982 {
1983 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001984 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 +00001985 return error;
1986 }
1987
1988 if (bp_addr == LLDB_INVALID_ADDRESS)
1989 {
1990 error.SetErrorString("BreakpointSite contains an invalid load address.");
1991 return error;
1992 }
1993 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1994 // trap for the breakpoint site
1995 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1996
1997 if (bp_opcode_size == 0)
1998 {
Daniel Malead01b2952012-11-29 21:49:15 +00001999 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000 }
2001 else
2002 {
2003 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2004
2005 if (bp_opcode_bytes == NULL)
2006 {
2007 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2008 return error;
2009 }
2010
2011 // Save the original opcode by reading it
2012 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2013 {
2014 // Write a software breakpoint in place of the original opcode
2015 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2016 {
2017 uint8_t verify_bp_opcode_bytes[64];
2018 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2019 {
2020 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2021 {
2022 bp_site->SetEnabled(true);
2023 bp_site->SetType (BreakpointSite::eSoftware);
2024 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002025 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002026 bp_site->GetID(),
2027 (uint64_t)bp_addr);
2028 }
2029 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002030 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031 }
2032 else
2033 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2034 }
2035 else
2036 error.SetErrorString("Unable to write breakpoint trap to memory.");
2037 }
2038 else
2039 error.SetErrorString("Unable to read memory at breakpoint address.");
2040 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002041 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002042 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043 bp_site->GetID(),
2044 (uint64_t)bp_addr,
2045 error.AsCString());
2046 return error;
2047}
2048
2049Error
2050Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2051{
2052 Error error;
2053 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002054 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055 addr_t bp_addr = bp_site->GetLoadAddress();
2056 lldb::user_id_t breakID = bp_site->GetID();
2057 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002058 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002059
2060 if (bp_site->IsHardware())
2061 {
2062 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2063 }
2064 else if (bp_site->IsEnabled())
2065 {
2066 const size_t break_op_size = bp_site->GetByteSize();
2067 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2068 if (break_op_size > 0)
2069 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002070 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002071 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002072 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073 bool break_op_found = false;
2074
2075 // Read the breakpoint opcode
2076 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2077 {
2078 bool verify = false;
2079 // Make sure we have the a breakpoint opcode exists at this address
2080 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2081 {
2082 break_op_found = true;
2083 // We found a valid breakpoint opcode at this address, now restore
2084 // the saved opcode.
2085 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2086 {
2087 verify = true;
2088 }
2089 else
2090 error.SetErrorString("Memory write failed when restoring original opcode.");
2091 }
2092 else
2093 {
2094 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2095 // Set verify to true and so we can check if the original opcode has already been restored
2096 verify = true;
2097 }
2098
2099 if (verify)
2100 {
Greg Claytonc982c762010-07-09 20:39:50 +00002101 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002102 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103 // Verify that our original opcode made it back to the inferior
2104 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2105 {
2106 // compare the memory we just read with the original opcode
2107 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2108 {
2109 // SUCCESS
2110 bp_site->SetEnabled(false);
2111 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002112 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 +00002113 return error;
2114 }
2115 else
2116 {
2117 if (break_op_found)
2118 error.SetErrorString("Failed to restore original opcode.");
2119 }
2120 }
2121 else
2122 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2123 }
2124 }
2125 else
2126 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2127 }
2128 }
2129 else
2130 {
2131 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002132 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 +00002133 return error;
2134 }
2135
2136 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002137 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 bp_site->GetID(),
2139 (uint64_t)bp_addr,
2140 error.AsCString());
2141 return error;
2142
2143}
2144
Greg Clayton58be07b2011-01-07 06:08:19 +00002145// Uncomment to verify memory caching works after making changes to caching code
2146//#define VERIFY_MEMORY_READS
2147
Sean Callanan64c0cf22012-06-07 22:26:42 +00002148size_t
2149Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2150{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002151 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002152 if (!GetDisableMemoryCache())
2153 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002154#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002155 // Memory caching is enabled, with debug verification
2156
2157 if (buf && size)
2158 {
2159 // Uncomment the line below to make sure memory caching is working.
2160 // I ran this through the test suite and got no assertions, so I am
2161 // pretty confident this is working well. If any changes are made to
2162 // memory caching, uncomment the line below and test your changes!
2163
2164 // Verify all memory reads by using the cache first, then redundantly
2165 // reading the same memory from the inferior and comparing to make sure
2166 // everything is exactly the same.
2167 std::string verify_buf (size, '\0');
2168 assert (verify_buf.size() == size);
2169 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2170 Error verify_error;
2171 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2172 assert (cache_bytes_read == verify_bytes_read);
2173 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2174 assert (verify_error.Success() == error.Success());
2175 return cache_bytes_read;
2176 }
2177 return 0;
2178#else // !defined(VERIFY_MEMORY_READS)
2179 // Memory caching is enabled, without debug verification
2180
2181 return m_memory_cache.Read (addr, buf, size, error);
2182#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002183 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002184 else
2185 {
2186 // Memory caching is disabled
2187
2188 return ReadMemoryFromInferior (addr, buf, size, error);
2189 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002190}
Greg Clayton58be07b2011-01-07 06:08:19 +00002191
Greg Clayton4c82d422012-05-18 23:20:01 +00002192size_t
2193Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2194{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002195 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002196 out_str.clear();
2197 addr_t curr_addr = addr;
2198 while (1)
2199 {
2200 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2201 if (length == 0)
2202 break;
2203 out_str.append(buf, length);
2204 // If we got "length - 1" bytes, we didn't get the whole C string, we
2205 // need to read some more characters
2206 if (length == sizeof(buf) - 1)
2207 curr_addr += length;
2208 else
2209 break;
2210 }
2211 return out_str.size();
2212}
2213
Greg Clayton58be07b2011-01-07 06:08:19 +00002214
2215size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002216Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2217 size_t type_width)
2218{
2219 size_t total_bytes_read = 0;
2220 if (dst && max_bytes && type_width && max_bytes >= type_width)
2221 {
2222 // Ensure a null terminator independent of the number of bytes that is read.
2223 memset (dst, 0, max_bytes);
2224 size_t bytes_left = max_bytes - type_width;
2225
2226 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2227 assert(sizeof(terminator) >= type_width &&
2228 "Attempting to validate a string with more than 4 bytes per character!");
2229
2230 addr_t curr_addr = addr;
2231 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2232 char *curr_dst = dst;
2233
2234 error.Clear();
2235 while (bytes_left > 0 && error.Success())
2236 {
2237 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2238 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2239 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2240
2241 if (bytes_read == 0)
2242 break;
2243
2244 // Search for a null terminator of correct size and alignment in bytes_read
2245 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2246 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2247 if (::strncmp(&dst[i], terminator, type_width) == 0)
2248 {
2249 error.Clear();
2250 return i;
2251 }
2252
2253 total_bytes_read += bytes_read;
2254 curr_dst += bytes_read;
2255 curr_addr += bytes_read;
2256 bytes_left -= bytes_read;
2257 }
2258 }
2259 else
2260 {
2261 if (max_bytes)
2262 error.SetErrorString("invalid arguments");
2263 }
2264 return total_bytes_read;
2265}
2266
2267// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2268// null terminators.
2269size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002270Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002271{
2272 size_t total_cstr_len = 0;
2273 if (dst && dst_max_len)
2274 {
Greg Claytone91b7952011-12-15 03:14:23 +00002275 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002276 // NULL out everything just to be safe
2277 memset (dst, 0, dst_max_len);
2278 Error error;
2279 addr_t curr_addr = addr;
2280 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2281 size_t bytes_left = dst_max_len - 1;
2282 char *curr_dst = dst;
2283
2284 while (bytes_left > 0)
2285 {
2286 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2287 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2288 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2289
2290 if (bytes_read == 0)
2291 {
Greg Claytone91b7952011-12-15 03:14:23 +00002292 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002293 dst[total_cstr_len] = '\0';
2294 break;
2295 }
2296 const size_t len = strlen(curr_dst);
2297
2298 total_cstr_len += len;
2299
2300 if (len < bytes_to_read)
2301 break;
2302
2303 curr_dst += bytes_read;
2304 curr_addr += bytes_read;
2305 bytes_left -= bytes_read;
2306 }
2307 }
Greg Claytone91b7952011-12-15 03:14:23 +00002308 else
2309 {
2310 if (dst == NULL)
2311 result_error.SetErrorString("invalid arguments");
2312 else
2313 result_error.Clear();
2314 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002315 return total_cstr_len;
2316}
2317
2318size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002319Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2320{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 if (buf == NULL || size == 0)
2322 return 0;
2323
2324 size_t bytes_read = 0;
2325 uint8_t *bytes = (uint8_t *)buf;
2326
2327 while (bytes_read < size)
2328 {
2329 const size_t curr_size = size - bytes_read;
2330 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2331 bytes + bytes_read,
2332 curr_size,
2333 error);
2334 bytes_read += curr_bytes_read;
2335 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2336 break;
2337 }
2338
2339 // Replace any software breakpoint opcodes that fall into this range back
2340 // into "buf" before we return
2341 if (bytes_read > 0)
2342 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2343 return bytes_read;
2344}
2345
Greg Clayton58a4c462010-12-16 20:01:20 +00002346uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002347Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002348{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002349 Scalar scalar;
2350 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2351 return scalar.ULongLong(fail_value);
2352 return fail_value;
2353}
2354
2355addr_t
2356Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2357{
2358 Scalar scalar;
2359 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2360 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2361 return LLDB_INVALID_ADDRESS;
2362}
2363
2364
2365bool
2366Process::WritePointerToMemory (lldb::addr_t vm_addr,
2367 lldb::addr_t ptr_value,
2368 Error &error)
2369{
2370 Scalar scalar;
2371 const uint32_t addr_byte_size = GetAddressByteSize();
2372 if (addr_byte_size <= 4)
2373 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002374 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002375 scalar = ptr_value;
2376 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002377}
2378
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002379size_t
2380Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2381{
2382 size_t bytes_written = 0;
2383 const uint8_t *bytes = (const uint8_t *)buf;
2384
2385 while (bytes_written < size)
2386 {
2387 const size_t curr_size = size - bytes_written;
2388 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2389 bytes + bytes_written,
2390 curr_size,
2391 error);
2392 bytes_written += curr_bytes_written;
2393 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2394 break;
2395 }
2396 return bytes_written;
2397}
2398
2399size_t
2400Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2401{
Greg Clayton58be07b2011-01-07 06:08:19 +00002402#if defined (ENABLE_MEMORY_CACHING)
2403 m_memory_cache.Flush (addr, size);
2404#endif
2405
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406 if (buf == NULL || size == 0)
2407 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002408
Jim Ingham4b536182011-08-09 02:12:22 +00002409 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002410
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 // We need to write any data that would go where any current software traps
2412 // (enabled software breakpoints) any software traps (breakpoints) that we
2413 // may have placed in our tasks memory.
2414
Greg Claytond8cf1a12013-06-12 00:46:38 +00002415 BreakpointSiteList bp_sites_in_range;
2416
2417 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002419 // No breakpoint sites overlap
2420 if (bp_sites_in_range.IsEmpty())
2421 return WriteMemoryPrivate (addr, buf, size, error);
2422 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002424 const uint8_t *ubuf = (const uint8_t *)buf;
2425 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002426
Greg Claytond8cf1a12013-06-12 00:46:38 +00002427 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2428
2429 if (error.Success())
2430 {
2431 addr_t intersect_addr;
2432 size_t intersect_size;
2433 size_t opcode_offset;
2434 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2435 assert(intersects);
2436 assert(addr <= intersect_addr && intersect_addr < addr + size);
2437 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2438 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2439
2440 // Check for bytes before this breakpoint
2441 const addr_t curr_addr = addr + bytes_written;
2442 if (intersect_addr > curr_addr)
2443 {
2444 // There are some bytes before this breakpoint that we need to
2445 // just write to memory
2446 size_t curr_size = intersect_addr - curr_addr;
2447 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2448 ubuf + bytes_written,
2449 curr_size,
2450 error);
2451 bytes_written += curr_bytes_written;
2452 if (curr_bytes_written != curr_size)
2453 {
2454 // We weren't able to write all of the requested bytes, we
2455 // are done looping and will return the number of bytes that
2456 // we have written so far.
2457 if (error.Success())
2458 error.SetErrorToGenericError();
2459 }
2460 }
2461 // Now write any bytes that would cover up any software breakpoints
2462 // directly into the breakpoint opcode buffer
2463 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2464 bytes_written += intersect_size;
2465 }
2466 });
2467
2468 if (bytes_written < size)
2469 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2470 ubuf + bytes_written,
2471 size - bytes_written,
2472 error);
2473 }
2474 }
2475 else
2476 {
2477 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002478 }
2479
2480 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002481 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002482}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002483
2484size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002485Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002486{
2487 if (byte_size == UINT32_MAX)
2488 byte_size = scalar.GetByteSize();
2489 if (byte_size > 0)
2490 {
2491 uint8_t buf[32];
2492 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2493 if (mem_size > 0)
2494 return WriteMemory(addr, buf, mem_size, error);
2495 else
2496 error.SetErrorString ("failed to get scalar as memory data");
2497 }
2498 else
2499 {
2500 error.SetErrorString ("invalid scalar value");
2501 }
2502 return 0;
2503}
2504
2505size_t
2506Process::ReadScalarIntegerFromMemory (addr_t addr,
2507 uint32_t byte_size,
2508 bool is_signed,
2509 Scalar &scalar,
2510 Error &error)
2511{
Greg Clayton7060f892013-05-01 23:41:30 +00002512 uint64_t uval = 0;
2513 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002514 {
Greg Clayton7060f892013-05-01 23:41:30 +00002515 error.SetErrorString ("byte size is zero");
2516 }
2517 else if (byte_size & (byte_size - 1))
2518 {
2519 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2520 }
2521 else if (byte_size <= sizeof(uval))
2522 {
2523 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002524 if (bytes_read == byte_size)
2525 {
2526 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002527 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002528 if (byte_size <= 4)
2529 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002530 else
Greg Clayton7060f892013-05-01 23:41:30 +00002531 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002532 if (is_signed)
2533 scalar.SignExtend(byte_size * 8);
2534 return bytes_read;
2535 }
2536 }
2537 else
2538 {
2539 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2540 }
2541 return 0;
2542}
2543
Greg Claytond495c532011-05-17 03:37:42 +00002544#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002545addr_t
2546Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2547{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002548 if (GetPrivateState() != eStateStopped)
2549 return LLDB_INVALID_ADDRESS;
2550
Greg Claytond495c532011-05-17 03:37:42 +00002551#if defined (USE_ALLOCATE_MEMORY_CACHE)
2552 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2553#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002554 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002555 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002556 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002557 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 +00002558 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002559 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002560 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002561 m_mod_id.GetStopID(),
2562 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002563 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002564#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002565}
2566
Sean Callanan90539452011-09-20 23:01:51 +00002567bool
2568Process::CanJIT ()
2569{
Sean Callanana7b443a2012-02-14 22:50:38 +00002570 if (m_can_jit == eCanJITDontKnow)
2571 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002572 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002573 Error err;
2574
2575 uint64_t allocated_memory = AllocateMemory(8,
2576 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2577 err);
2578
2579 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002580 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002581 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002582 if (log)
2583 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2584 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002585 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002586 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002587 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002588 if (log)
2589 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2590 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002591
2592 DeallocateMemory (allocated_memory);
2593 }
2594
Sean Callanan90539452011-09-20 23:01:51 +00002595 return m_can_jit == eCanJITYes;
2596}
2597
2598void
2599Process::SetCanJIT (bool can_jit)
2600{
2601 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2602}
2603
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002604Error
2605Process::DeallocateMemory (addr_t ptr)
2606{
Greg Claytond495c532011-05-17 03:37:42 +00002607 Error error;
2608#if defined (USE_ALLOCATE_MEMORY_CACHE)
2609 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2610 {
Daniel Malead01b2952012-11-29 21:49:15 +00002611 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002612 }
2613#else
2614 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002615
Greg Clayton5160ce52013-03-27 23:08:40 +00002616 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002617 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002618 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 +00002619 ptr,
2620 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002621 m_mod_id.GetStopID(),
2622 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002623#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002624 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002625}
2626
Han Ming Ongc811d382012-11-17 00:33:14 +00002627
Greg Claytonc9660542012-02-05 02:38:54 +00002628ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002629Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002630 lldb::addr_t header_addr,
2631 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002632{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002633 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002634 if (module_sp)
2635 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002636 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002637 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002638 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002639 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002640 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002641 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002642}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643
2644Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002645Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002646{
2647 Error error;
2648 error.SetErrorString("watchpoints are not supported");
2649 return error;
2650}
2651
2652Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002653Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654{
2655 Error error;
2656 error.SetErrorString("watchpoints are not supported");
2657 return error;
2658}
2659
2660StateType
2661Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2662{
2663 StateType state;
2664 // Now wait for the process to launch and return control to us, and then
2665 // call DidLaunch:
2666 while (1)
2667 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002668 event_sp.reset();
2669 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2670
Greg Clayton2637f822011-11-17 01:23:07 +00002671 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002673
2674 // If state is invalid, then we timed out
2675 if (state == eStateInvalid)
2676 break;
2677
2678 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679 HandlePrivateEvent (event_sp);
2680 }
2681 return state;
2682}
2683
2684Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002685Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002686{
2687 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002689 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002690 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002691 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002692 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002693 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694
Greg Claytonaa149cb2011-08-11 02:48:45 +00002695 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696 if (exe_module)
2697 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002698 char local_exec_file_path[PATH_MAX];
2699 char platform_exec_file_path[PATH_MAX];
2700 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2701 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702 if (exe_module->GetFileSpec().Exists())
2703 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002704 // Install anything that might need to be installed prior to launching.
2705 // For host systems, this will do nothing, but if we are connected to a
2706 // remote platform it will install any needed binaries
2707 error = GetTarget().Install(&launch_info);
2708 if (error.Fail())
2709 return error;
2710
Greg Clayton71337622011-02-24 22:24:29 +00002711 if (PrivateStateThreadIsValid ())
2712 PausePrivateStateThread ();
2713
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002714 error = WillLaunch (exe_module);
2715 if (error.Success())
2716 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002717 const bool restarted = false;
2718 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002719 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002720
Ed Maste64fad602013-07-29 20:58:06 +00002721 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002722 {
2723 // Now launch using these arguments.
2724 error = DoLaunch (exe_module, launch_info);
2725 }
2726 else
2727 {
2728 // This shouldn't happen
2729 error.SetErrorString("failed to acquire process run lock");
2730 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731
2732 if (error.Fail())
2733 {
2734 if (GetID() != LLDB_INVALID_PROCESS_ID)
2735 {
2736 SetID (LLDB_INVALID_PROCESS_ID);
2737 const char *error_string = error.AsCString();
2738 if (error_string == NULL)
2739 error_string = "launch failed";
2740 SetExitStatus (-1, error_string);
2741 }
2742 }
2743 else
2744 {
2745 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002746 TimeValue timeout_time;
2747 timeout_time = TimeValue::Now();
2748 timeout_time.OffsetWithSeconds(10);
2749 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750
Greg Clayton1a38ea72011-06-22 01:42:17 +00002751 if (state == eStateInvalid || event_sp.get() == NULL)
2752 {
2753 // We were able to launch the process, but we failed to
2754 // catch the initial stop.
2755 SetExitStatus (0, "failed to catch stop after launch");
2756 Destroy();
2757 }
2758 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002760
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002761 DidLaunch ();
2762
Greg Claytonc859e2d2012-02-13 23:10:39 +00002763 DynamicLoader *dyld = GetDynamicLoader ();
2764 if (dyld)
2765 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002766
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002767 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002768
Jason Molendaeef51062013-11-05 03:57:19 +00002769 SystemRuntime *system_runtime = GetSystemRuntime ();
2770 if (system_runtime)
2771 system_runtime->DidLaunch();
2772
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002773 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774 // This delays passing the stopped event to listeners till DidLaunch gets
2775 // a chance to complete...
2776 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002777
2778 if (PrivateStateThreadIsValid ())
2779 ResumePrivateStateThread ();
2780 else
2781 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782 }
2783 else if (state == eStateExited)
2784 {
2785 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2786 // not likely to work, and return an invalid pid.
2787 HandlePrivateEvent (event_sp);
2788 }
2789 }
2790 }
2791 }
2792 else
2793 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002794 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795 }
2796 }
2797 return error;
2798}
2799
Greg Claytonc3776bf2012-02-09 06:16:32 +00002800
2801Error
2802Process::LoadCore ()
2803{
2804 Error error = DoLoadCore();
2805 if (error.Success())
2806 {
2807 if (PrivateStateThreadIsValid ())
2808 ResumePrivateStateThread ();
2809 else
2810 StartPrivateStateThread ();
2811
Greg Claytonc859e2d2012-02-13 23:10:39 +00002812 DynamicLoader *dyld = GetDynamicLoader ();
2813 if (dyld)
2814 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002815
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002816 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002817
Jason Molendaeef51062013-11-05 03:57:19 +00002818 SystemRuntime *system_runtime = GetSystemRuntime ();
2819 if (system_runtime)
2820 system_runtime->DidAttach();
2821
Greg Claytonc859e2d2012-02-13 23:10:39 +00002822 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002823 // We successfully loaded a core file, now pretend we stopped so we can
2824 // show all of the threads in the core file and explore the crashed
2825 // state.
2826 SetPrivateState (eStateStopped);
2827
2828 }
2829 return error;
2830}
2831
Greg Claytonc859e2d2012-02-13 23:10:39 +00002832DynamicLoader *
2833Process::GetDynamicLoader ()
2834{
2835 if (m_dyld_ap.get() == NULL)
2836 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2837 return m_dyld_ap.get();
2838}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002839
Todd Fialaaf245d12014-06-30 21:05:18 +00002840const lldb::DataBufferSP
2841Process::GetAuxvData()
2842{
2843 return DataBufferSP ();
2844}
2845
Andrew MacPherson17220c12014-03-05 10:12:43 +00002846JITLoaderList &
2847Process::GetJITLoaders ()
2848{
2849 if (!m_jit_loaders_ap)
2850 {
2851 m_jit_loaders_ap.reset(new JITLoaderList());
2852 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2853 }
2854 return *m_jit_loaders_ap;
2855}
2856
Jason Molendaeef51062013-11-05 03:57:19 +00002857SystemRuntime *
2858Process::GetSystemRuntime ()
2859{
2860 if (m_system_runtime_ap.get() == NULL)
2861 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2862 return m_system_runtime_ap.get();
2863}
2864
Greg Claytonc3776bf2012-02-09 06:16:32 +00002865
Jim Inghambb3a2832011-01-29 01:49:25 +00002866Process::NextEventAction::EventActionResult
2867Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868{
Jim Inghambb3a2832011-01-29 01:49:25 +00002869 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2870 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002871 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002872 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002873 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002874 return eEventActionRetry;
2875
2876 case eStateStopped:
2877 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002878 {
2879 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002880 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002881 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002882 // We don't want these events to be reported, so go set the ShouldReportStop here:
2883 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2884
Greg Claytonc9ed4782011-11-12 02:10:56 +00002885 if (m_exec_count > 0)
2886 {
2887 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00002888 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002889 return eEventActionRetry;
2890 }
2891 else
2892 {
2893 m_process->CompleteAttach ();
2894 return eEventActionSuccess;
2895 }
2896 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002897 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002898
Greg Clayton513c26c2011-01-29 07:10:55 +00002899 default:
2900 case eStateExited:
2901 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002902 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002903 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002904
2905 m_exit_string.assign ("No valid Process");
2906 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002907}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908
Jim Inghambb3a2832011-01-29 01:49:25 +00002909Process::NextEventAction::EventActionResult
2910Process::AttachCompletionHandler::HandleBeingInterrupted()
2911{
2912 return eEventActionSuccess;
2913}
2914
2915const char *
2916Process::AttachCompletionHandler::GetExitString ()
2917{
2918 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919}
2920
2921Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002922Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002923{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002924 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002925 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002926 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002927 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002928 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002929 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002930
Greg Clayton144f3a92011-11-15 03:53:30 +00002931 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002932 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002933 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002934 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002935 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002936
Greg Clayton144f3a92011-11-15 03:53:30 +00002937 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002938 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002939 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2940
2941 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002943 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2944 if (error.Success())
2945 {
Ed Maste64fad602013-07-29 20:58:06 +00002946 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002947 {
2948 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002949 const bool restarted = false;
2950 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002951 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00002952 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00002953 }
2954 else
2955 {
2956 // This shouldn't happen
2957 error.SetErrorString("failed to acquire process run lock");
2958 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002959
Greg Clayton144f3a92011-11-15 03:53:30 +00002960 if (error.Fail())
2961 {
2962 if (GetID() != LLDB_INVALID_PROCESS_ID)
2963 {
2964 SetID (LLDB_INVALID_PROCESS_ID);
2965 if (error.AsCString() == NULL)
2966 error.SetErrorString("attach failed");
2967
2968 SetExitStatus(-1, error.AsCString());
2969 }
2970 }
2971 else
2972 {
2973 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2974 StartPrivateStateThread();
2975 }
2976 return error;
2977 }
Greg Claytone996fd32011-03-08 22:40:15 +00002978 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002979 else
Greg Claytone996fd32011-03-08 22:40:15 +00002980 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002981 ProcessInstanceInfoList process_infos;
2982 PlatformSP platform_sp (m_target.GetPlatform ());
2983
2984 if (platform_sp)
2985 {
2986 ProcessInstanceInfoMatch match_info;
2987 match_info.GetProcessInfo() = attach_info;
2988 match_info.SetNameMatchType (eNameMatchEquals);
2989 platform_sp->FindProcesses (match_info, process_infos);
2990 const uint32_t num_matches = process_infos.GetSize();
2991 if (num_matches == 1)
2992 {
2993 attach_pid = process_infos.GetProcessIDAtIndex(0);
2994 // Fall through and attach using the above process ID
2995 }
2996 else
2997 {
2998 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2999 if (num_matches > 1)
3000 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3001 else
3002 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3003 }
3004 }
3005 else
3006 {
3007 error.SetErrorString ("invalid platform, can't find processes by name");
3008 return error;
3009 }
Greg Claytone996fd32011-03-08 22:40:15 +00003010 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003011 }
3012 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003013 {
3014 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003015 }
3016 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003017
3018 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003019 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003020 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003021 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003023
Ed Maste64fad602013-07-29 20:58:06 +00003024 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003025 {
3026 // Now attach using these arguments.
3027 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003028 const bool restarted = false;
3029 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003030 error = DoAttachToProcessWithID (attach_pid, attach_info);
3031 }
3032 else
3033 {
3034 // This shouldn't happen
3035 error.SetErrorString("failed to acquire process run lock");
3036 }
3037
Greg Clayton144f3a92011-11-15 03:53:30 +00003038 if (error.Success())
3039 {
3040
3041 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3042 StartPrivateStateThread();
3043 }
3044 else
Greg Claytone996fd32011-03-08 22:40:15 +00003045 {
3046 if (GetID() != LLDB_INVALID_PROCESS_ID)
3047 {
3048 SetID (LLDB_INVALID_PROCESS_ID);
3049 const char *error_string = error.AsCString();
3050 if (error_string == NULL)
3051 error_string = "attach failed";
3052
3053 SetExitStatus(-1, error_string);
3054 }
3055 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 }
3057 }
3058 return error;
3059}
3060
Greg Clayton93d3c8332011-02-16 04:46:07 +00003061void
3062Process::CompleteAttach ()
3063{
3064 // Let the process subclass figure out at much as it can about the process
3065 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003066 ArchSpec process_arch;
3067 DidAttach(process_arch);
3068
3069 if (process_arch.IsValid())
3070 m_target.SetArchitecture(process_arch);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003071
Jim Ingham4299fdb2011-09-15 01:10:17 +00003072 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3073 // the same as the one we've already set, switch architectures.
3074 PlatformSP platform_sp (m_target.GetPlatform ());
3075 assert (platform_sp.get());
3076 if (platform_sp)
3077 {
Greg Clayton70512312012-05-08 01:45:38 +00003078 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003079 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003080 {
3081 ArchSpec platform_arch;
3082 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3083 if (platform_sp)
3084 {
3085 m_target.SetPlatform (platform_sp);
3086 m_target.SetArchitecture(platform_arch);
3087 }
3088 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003089 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003090 {
3091 ProcessInstanceInfo process_info;
3092 platform_sp->GetProcessInfo (GetID(), process_info);
3093 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003094 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003095 m_target.SetArchitecture (process_arch);
3096 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003097 }
3098
3099 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003100 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003101 DynamicLoader *dyld = GetDynamicLoader ();
3102 if (dyld)
3103 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003104
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003105 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003106
Jason Molendaeef51062013-11-05 03:57:19 +00003107 SystemRuntime *system_runtime = GetSystemRuntime ();
3108 if (system_runtime)
3109 system_runtime->DidAttach();
3110
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003111 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003112 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003113 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003114 Mutex::Locker modules_locker(target_modules.GetMutex());
3115 size_t num_modules = target_modules.GetSize();
3116 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003117
Andy Gibbsa297a972013-06-19 19:04:53 +00003118 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003119 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003120 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003121 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003122 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003123 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003124 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003125 break;
3126 }
3127 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003128 if (new_executable_module_sp)
3129 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003130}
3131
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003133Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003134{
Greg Claytonb766a732011-02-04 01:58:07 +00003135 m_abi_sp.reset();
3136 m_process_input_reader.reset();
3137
3138 // Find the process and its architecture. Make sure it matches the architecture
3139 // of the current Target, and if not adjust it.
3140
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003141 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003142 if (error.Success())
3143 {
Greg Clayton71337622011-02-24 22:24:29 +00003144 if (GetID() != LLDB_INVALID_PROCESS_ID)
3145 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003146 EventSP event_sp;
3147 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3148
3149 if (state == eStateStopped || state == eStateCrashed)
3150 {
3151 // If we attached and actually have a process on the other end, then
3152 // this ended up being the equivalent of an attach.
3153 CompleteAttach ();
3154
3155 // This delays passing the stopped event to listeners till
3156 // CompleteAttach gets a chance to complete...
3157 HandlePrivateEvent (event_sp);
3158
3159 }
Greg Clayton71337622011-02-24 22:24:29 +00003160 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003161
3162 if (PrivateStateThreadIsValid ())
3163 ResumePrivateStateThread ();
3164 else
3165 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003166 }
3167 return error;
3168}
3169
3170
3171Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003172Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003173{
Greg Clayton5160ce52013-03-27 23:08:40 +00003174 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003175 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003176 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003177 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003178 StateAsCString(m_public_state.GetValue()),
3179 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003180
3181 Error error (WillResume());
3182 // Tell the process it is about to resume before the thread list
3183 if (error.Success())
3184 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003185 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186 // can let all of our threads know that they are about to be
3187 // resumed. Threads will each be called with
3188 // Thread::WillResume(StateType) where StateType contains the state
3189 // that they are supposed to have when the process is resumed
3190 // (suspended/running/stepping). Threads should also check
3191 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003192 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193 if (m_thread_list.WillResume())
3194 {
Jim Ingham372787f2012-04-07 00:00:41 +00003195 // Last thing, do the PreResumeActions.
3196 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003197 {
Jim Ingham0161b492013-02-09 01:29:05 +00003198 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003199 }
3200 else
3201 {
3202 m_mod_id.BumpResumeID();
3203 error = DoResume();
3204 if (error.Success())
3205 {
3206 DidResume();
3207 m_thread_list.DidResume();
3208 if (log)
3209 log->Printf ("Process thinks the process has resumed.");
3210 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211 }
3212 }
3213 else
3214 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003215 // Somebody wanted to run without running. So generate a continue & a stopped event,
3216 // and let the world handle them.
3217 if (log)
3218 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3219
3220 SetPrivateState(eStateRunning);
3221 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 }
3223 }
Jim Ingham444586b2011-01-24 06:34:17 +00003224 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003225 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003226 return error;
3227}
3228
3229Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003230Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003232 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3233 // in case it was already set and some thread plan logic calls halt on its
3234 // own.
3235 m_clear_thread_plans_on_stop |= clear_thread_plans;
3236
Jim Inghamaacc3182012-06-06 00:29:30 +00003237 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3238 // we could just straightaway get another event. It just narrows the window...
3239 m_currently_handling_event.WaitForValueEqualTo(false);
3240
3241
Jim Inghambb3a2832011-01-29 01:49:25 +00003242 // Pause our private state thread so we can ensure no one else eats
3243 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003244 Listener halt_listener ("lldb.process.halt_listener");
3245 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003246
Jim Inghambb3a2832011-01-29 01:49:25 +00003247 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003248 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003249
Greg Clayton06357c92014-07-30 17:38:47 +00003250 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003251 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003252 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003253
Greg Clayton513c26c2011-01-29 07:10:55 +00003254 bool caused_stop = false;
3255
3256 // Ask the process subclass to actually halt our process
3257 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003259 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003260 if (m_public_state.GetValue() == eStateAttaching)
3261 {
Greg Clayton06357c92014-07-30 17:38:47 +00003262 // Don't hijack and eat the eStateExited as the code that was doing
3263 // the attach will be waiting for this event...
3264 RestorePrivateProcessEvents();
3265 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003266 SetExitStatus(SIGKILL, "Cancelled async attach.");
3267 Destroy ();
3268 }
3269 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003270 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003271 // If "caused_stop" is true, then DoHalt stopped the process. If
3272 // "caused_stop" is false, the process was already stopped.
3273 // If the DoHalt caused the process to stop, then we want to catch
3274 // this event and set the interrupted bool to true before we pass
3275 // this along so clients know that the process was interrupted by
3276 // a halt command.
3277 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003278 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003279 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003280 TimeValue timeout_time;
3281 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003282 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003283 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3284 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003285
Jim Ingham0f16e732011-02-08 05:20:59 +00003286 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003287 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003288 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003289 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003290 }
3291 else
3292 {
Greg Clayton2637f822011-11-17 01:23:07 +00003293 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003294 {
3295 // We caused the process to interrupt itself, so mark this
3296 // as such in the stop event so clients can tell an interrupted
3297 // process from a natural stop
3298 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3299 }
3300 else
3301 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003302 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003303 if (log)
3304 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3305 error.SetErrorString ("Did not get stopped event after halt.");
3306 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003307 }
3308 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003309 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003310 }
3311 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003313 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003314 if (!restored_process_events)
3315 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003316
3317 // Post any event we might have consumed. If all goes well, we will have
3318 // stopped the process, intercepted the event and set the interrupted
3319 // bool in the event. Post it to the private event queue and that will end up
3320 // correctly setting the state.
3321 if (event_sp)
3322 m_private_state_broadcaster.BroadcastEvent(event_sp);
3323
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324 return error;
3325}
3326
3327Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003328Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3329{
3330 Error error;
3331 if (m_public_state.GetValue() == eStateRunning)
3332 {
3333 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3334 if (log)
3335 log->Printf("Process::Destroy() About to halt.");
3336 error = Halt();
3337 if (error.Success())
3338 {
3339 // Consume the halt event.
3340 TimeValue timeout (TimeValue::Now());
3341 timeout.OffsetWithSeconds(1);
3342 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3343
3344 // If the process exited while we were waiting for it to stop, put the exited event into
3345 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3346 // they don't have a process anymore...
3347
3348 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3349 {
3350 if (log)
3351 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3352 return error;
3353 }
3354 else
3355 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3356
3357 if (state != eStateStopped)
3358 {
3359 if (log)
3360 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3361 // If we really couldn't stop the process then we should just error out here, but if the
3362 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3363 StateType private_state = m_private_state.GetValue();
3364 if (private_state != eStateStopped)
3365 {
3366 return error;
3367 }
3368 }
3369 }
3370 else
3371 {
3372 if (log)
3373 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3374 }
3375 }
3376 return error;
3377}
3378
3379Error
Jim Inghamacff8952013-05-02 00:27:30 +00003380Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003381{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003382 EventSP exit_event_sp;
3383 Error error;
3384 m_destroy_in_process = true;
3385
3386 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003387
3388 if (error.Success())
3389 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003390 if (DetachRequiresHalt())
3391 {
3392 error = HaltForDestroyOrDetach (exit_event_sp);
3393 if (!error.Success())
3394 {
3395 m_destroy_in_process = false;
3396 return error;
3397 }
3398 else if (exit_event_sp)
3399 {
3400 // We shouldn't need to do anything else here. There's no process left to detach from...
3401 StopPrivateStateThread();
3402 m_destroy_in_process = false;
3403 return error;
3404 }
3405 }
3406
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003407 m_thread_list.DiscardThreadPlans();
3408 DisableAllBreakpointSites();
3409
Jim Inghamacff8952013-05-02 00:27:30 +00003410 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003411 if (error.Success())
3412 {
3413 DidDetach();
3414 StopPrivateStateThread();
3415 }
Jim Inghamacff8952013-05-02 00:27:30 +00003416 else
3417 {
3418 return error;
3419 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003420 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003421 m_destroy_in_process = false;
3422
3423 // If we exited when we were waiting for a process to stop, then
3424 // forward the event here so we don't lose the event
3425 if (exit_event_sp)
3426 {
3427 // Directly broadcast our exited event because we shut down our
3428 // private state thread above
3429 BroadcastEvent(exit_event_sp);
3430 }
3431
3432 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3433 // the last events through the event system, in which case we might strand the write lock. Unlock
3434 // it here so when we do to tear down the process we don't get an error destroying the lock.
3435
Ed Maste64fad602013-07-29 20:58:06 +00003436 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 return error;
3438}
3439
3440Error
3441Process::Destroy ()
3442{
Jim Ingham09437922013-03-01 20:04:25 +00003443
3444 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3445 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3446 // failed and the process stays around for some reason it won't be in a confused state.
3447
3448 m_destroy_in_process = true;
3449
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003450 Error error (WillDestroy());
3451 if (error.Success())
3452 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003453 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003454 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003455 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003456 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003457 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003458
Jim Inghamaacc3182012-06-06 00:29:30 +00003459 if (m_public_state.GetValue() != eStateRunning)
3460 {
3461 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3462 // kill it, we don't want it hitting a breakpoint...
3463 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3464 // we're not going to have much luck doing this now.
3465 m_thread_list.DiscardThreadPlans();
3466 DisableAllBreakpointSites();
3467 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003468
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003469 error = DoDestroy();
3470 if (error.Success())
3471 {
3472 DidDestroy();
3473 StopPrivateStateThread();
3474 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003475 m_stdio_communication.StopReadThread();
3476 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003477
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003478 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003479 {
3480 m_process_input_reader->SetIsDone(true);
3481 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003482 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003483 }
3484
Greg Clayton85fb1b92012-09-11 02:33:37 +00003485 // If we exited when we were waiting for a process to stop, then
3486 // forward the event here so we don't lose the event
3487 if (exit_event_sp)
3488 {
3489 // Directly broadcast our exited event because we shut down our
3490 // private state thread above
3491 BroadcastEvent(exit_event_sp);
3492 }
3493
Jim Inghamb1e2e842012-04-12 18:49:31 +00003494 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3495 // the last events through the event system, in which case we might strand the write lock. Unlock
3496 // 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 +00003497 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498 }
Jim Ingham09437922013-03-01 20:04:25 +00003499
3500 m_destroy_in_process = false;
3501
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003502 return error;
3503}
3504
3505Error
3506Process::Signal (int signal)
3507{
3508 Error error (WillSignal());
3509 if (error.Success())
3510 {
3511 error = DoSignal(signal);
3512 if (error.Success())
3513 DidSignal();
3514 }
3515 return error;
3516}
3517
Greg Clayton514487e2011-02-15 21:59:32 +00003518lldb::ByteOrder
3519Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003520{
Greg Clayton514487e2011-02-15 21:59:32 +00003521 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522}
3523
3524uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003525Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003526{
Greg Clayton514487e2011-02-15 21:59:32 +00003527 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003528}
3529
Greg Clayton514487e2011-02-15 21:59:32 +00003530
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003531bool
3532Process::ShouldBroadcastEvent (Event *event_ptr)
3533{
3534 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3535 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003536 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003537
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538 switch (state)
3539 {
Greg Claytonb766a732011-02-04 01:58:07 +00003540 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541 case eStateAttaching:
3542 case eStateLaunching:
3543 case eStateDetached:
3544 case eStateExited:
3545 case eStateUnloaded:
3546 // These events indicate changes in the state of the debugging session, always report them.
3547 return_value = true;
3548 break;
3549 case eStateInvalid:
3550 // We stopped for no apparent reason, don't report it.
3551 return_value = false;
3552 break;
3553 case eStateRunning:
3554 case eStateStepping:
3555 // If we've started the target running, we handle the cases where we
3556 // are already running and where there is a transition from stopped to
3557 // running differently.
3558 // running -> running: Automatically suppress extra running events
3559 // stopped -> running: Report except when there is one or more no votes
3560 // and no yes votes.
3561 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003562 if (m_force_next_event_delivery)
3563 return_value = true;
3564 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003566 switch (m_last_broadcast_state)
3567 {
3568 case eStateRunning:
3569 case eStateStepping:
3570 // We always suppress multiple runnings with no PUBLIC stop in between.
3571 return_value = false;
3572 break;
3573 default:
3574 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003575 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003576 // events. If I run the lldb/test/thread/a.out file and
3577 // break at main.cpp:58, run and hit the breakpoints on
3578 // multiple threads, then somehow during the stepping over
3579 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580
Jim Ingham1460e4b2014-01-10 23:46:59 +00003581 // This is a transition from stop to run.
3582 switch (m_thread_list.ShouldReportRun (event_ptr))
3583 {
3584 case eVoteYes:
3585 case eVoteNoOpinion:
3586 return_value = true;
3587 break;
3588 case eVoteNo:
3589 return_value = false;
3590 break;
3591 }
3592 break;
3593 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003594 }
3595 break;
3596 case eStateStopped:
3597 case eStateCrashed:
3598 case eStateSuspended:
3599 {
3600 // We've stopped. First see if we're going to restart the target.
3601 // If we are going to stop, then we always broadcast the event.
3602 // 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 +00003603 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003604
Jim Inghamcb4ca112012-05-16 01:32:14 +00003605 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003606 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003607 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003608 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003609 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003610 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003611 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003612 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3613 // so they can properly set their state.
3614 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003615 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003616 }
3617 else
3618 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003619 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3620 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003621
Jim Ingham0161b492013-02-09 01:29:05 +00003622 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3623 // Asking the thread list is also not likely to go well, since we are running again.
3624 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003625
Jim Ingham0161b492013-02-09 01:29:05 +00003626 if (!was_restarted)
3627 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003628
Jim Ingham221d51c2013-05-08 00:35:16 +00003629 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003630 {
Jim Ingham0161b492013-02-09 01:29:05 +00003631 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3632 if (log)
3633 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003634 should_resume, StateAsCString(state),
3635 was_restarted, stop_vote);
3636
Jim Ingham0161b492013-02-09 01:29:05 +00003637 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003638 {
3639 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003640 return_value = true;
3641 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003642 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003643 case eVoteNo:
3644 return_value = false;
3645 break;
3646 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003647
Jim Inghamcb95f342012-09-05 21:13:56 +00003648 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003649 {
3650 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003651 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3652 static_cast<void*>(event_ptr),
3653 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003654 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003655 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003656 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003657
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658 }
3659 else
3660 {
3661 return_value = true;
3662 SynchronouslyNotifyStateChanged (state);
3663 }
3664 }
3665 }
Jim Ingham0161b492013-02-09 01:29:05 +00003666 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003667 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003668
Jim Ingham1460e4b2014-01-10 23:46:59 +00003669 // Forcing the next event delivery is a one shot deal. So reset it here.
3670 m_force_next_event_delivery = false;
3671
Jim Ingham0161b492013-02-09 01:29:05 +00003672 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3673 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3674 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3675 // because the PublicState reflects the last event pulled off the queue, and there may be several
3676 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3677 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003678
Jim Ingham0161b492013-02-09 01:29:05 +00003679 if (return_value)
3680 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003681
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003682 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003683 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003684 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003685 StateAsCString(m_last_broadcast_state),
3686 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003687 return return_value;
3688}
3689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003690
3691bool
Jim Ingham372787f2012-04-07 00:00:41 +00003692Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003693{
Greg Clayton5160ce52013-03-27 23:08:40 +00003694 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003695
Greg Clayton8b82f082011-04-12 05:54:46 +00003696 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003697 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003698 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3699
Jim Ingham372787f2012-04-07 00:00:41 +00003700 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003701 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003702
3703 // Create a thread that watches our internal state and controls which
3704 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003705 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003706
3707 if (Host::MAX_THREAD_NAME_LENGTH <= 16)
3708 {
3709 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3710 if (already_running)
3711 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3712 else
3713 snprintf(thread_name, sizeof(thread_name), "intern-state");
3714 }
Jim Ingham372787f2012-04-07 00:00:41 +00003715 else
Todd Fiala17096d72014-07-16 19:03:16 +00003716 {
3717 if (already_running)
3718 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3719 else
3720 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3721 }
3722
Jim Ingham076b3042012-04-10 01:21:57 +00003723 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003724 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003725 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3726 if (success)
3727 {
3728 ResumePrivateStateThread();
3729 return true;
3730 }
3731 else
3732 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733}
3734
3735void
3736Process::PausePrivateStateThread ()
3737{
3738 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3739}
3740
3741void
3742Process::ResumePrivateStateThread ()
3743{
3744 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3745}
3746
3747void
3748Process::StopPrivateStateThread ()
3749{
Greg Clayton8b82f082011-04-12 05:54:46 +00003750 if (PrivateStateThreadIsValid ())
3751 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003752 else
3753 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003754 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003755 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003756 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003757 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758}
3759
3760void
3761Process::ControlPrivateStateThread (uint32_t signal)
3762{
Greg Clayton5160ce52013-03-27 23:08:40 +00003763 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764
3765 assert (signal == eBroadcastInternalStateControlStop ||
3766 signal == eBroadcastInternalStateControlPause ||
3767 signal == eBroadcastInternalStateControlResume);
3768
3769 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003770 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003772 // Signal the private state thread. First we should copy this is case the
3773 // thread starts exiting since the private state thread will NULL this out
3774 // when it exits
3775 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003776 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777 {
3778 TimeValue timeout_time;
3779 bool timed_out;
3780
3781 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3782
3783 timeout_time = TimeValue::Now();
3784 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003785 if (log)
3786 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3788 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3789
3790 if (signal == eBroadcastInternalStateControlStop)
3791 {
3792 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003793 {
3794 Error error;
3795 Host::ThreadCancel (private_state_thread, &error);
3796 if (log)
3797 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3798 }
3799 else
3800 {
3801 if (log)
3802 log->Printf ("The control event killed the private state thread without having to cancel.");
3803 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003804
3805 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003806 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003807 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003808 }
3809 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003810 else
3811 {
3812 if (log)
3813 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3814 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003815}
3816
3817void
Jim Inghamcfc09352012-07-27 23:57:19 +00003818Process::SendAsyncInterrupt ()
3819{
3820 if (PrivateStateThreadIsValid())
3821 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3822 else
3823 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3824}
3825
3826void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003827Process::HandlePrivateEvent (EventSP &event_sp)
3828{
Greg Clayton5160ce52013-03-27 23:08:40 +00003829 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003830 m_resume_requested = false;
3831
Jim Inghamaacc3182012-06-06 00:29:30 +00003832 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003833
Greg Clayton414f5d32011-01-25 02:58:48 +00003834 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003835
3836 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003837 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003838 {
Jim Ingham754ab982011-01-29 04:05:41 +00003839 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003840 if (log)
3841 log->Printf ("Ran next event action, result was %d.", action_result);
3842
Jim Inghambb3a2832011-01-29 01:49:25 +00003843 switch (action_result)
3844 {
3845 case NextEventAction::eEventActionSuccess:
3846 SetNextEventAction(NULL);
3847 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003848
Jim Inghambb3a2832011-01-29 01:49:25 +00003849 case NextEventAction::eEventActionRetry:
3850 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003851
Jim Inghambb3a2832011-01-29 01:49:25 +00003852 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003853 // Handle Exiting Here. If we already got an exited event,
3854 // we should just propagate it. Otherwise, swallow this event,
3855 // and set our state to exit so the next event will kill us.
3856 if (new_state != eStateExited)
3857 {
3858 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003859 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003860 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003861 SetNextEventAction(NULL);
3862 return;
3863 }
3864 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003865 break;
3866 }
3867 }
3868
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003869 // See if we should broadcast this state to external clients?
3870 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871
3872 if (should_broadcast)
3873 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003874 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003875 if (log)
3876 {
Daniel Malead01b2952012-11-29 21:49:15 +00003877 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003878 __FUNCTION__,
3879 GetID(),
3880 StateAsCString(new_state),
3881 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003882 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883 }
Jim Ingham9575d842011-03-11 03:53:59 +00003884 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003885 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003886 {
3887 // Only push the input handler if we aren't fowarding events,
3888 // as this means the curses GUI is in use...
3889 if (!GetTarget().GetDebugger().IsForwardingEvents())
3890 PushProcessIOHandler ();
3891 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003892 else if (StateIsStoppedState(new_state, false))
3893 {
3894 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3895 {
3896 // If the lldb_private::Debugger is handling the events, we don't
3897 // want to pop the process IOHandler here, we want to do it when
3898 // we receive the stopped event so we can carefully control when
3899 // the process IOHandler is popped because when we stop we want to
3900 // display some text stating how and why we stopped, then maybe some
3901 // process/thread/frame info, and then we want the "(lldb) " prompt
3902 // to show up. If we pop the process IOHandler here, then we will
3903 // cause the command interpreter to become the top IOHandler after
3904 // the process pops off and it will update its prompt right away...
3905 // See the Debugger.cpp file where it calls the function as
3906 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3907 // Otherwise we end up getting overlapping "(lldb) " prompts and
3908 // garbled output.
3909 //
3910 // If we aren't handling the events in the debugger (which is indicated
3911 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3912 // are hijacked, then we always pop the process IO handler manually.
3913 // Hijacking happens when the internal process state thread is running
3914 // thread plans, or when commands want to run in synchronous mode
3915 // and they call "process->WaitForProcessToStop()". An example of something
3916 // that will hijack the events is a simple expression:
3917 //
3918 // (lldb) expr (int)puts("hello")
3919 //
3920 // This will cause the internal process state thread to resume and halt
3921 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3922 // events) and we do need the IO handler to be pushed and popped
3923 // correctly.
3924
3925 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
3926 PopProcessIOHandler ();
3927 }
3928 }
Jim Ingham9575d842011-03-11 03:53:59 +00003929
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930 BroadcastEvent (event_sp);
3931 }
3932 else
3933 {
3934 if (log)
3935 {
Daniel Malead01b2952012-11-29 21:49:15 +00003936 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003937 __FUNCTION__,
3938 GetID(),
3939 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003940 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003941 }
3942 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003943 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003944}
3945
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003946thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947Process::PrivateStateThread (void *arg)
3948{
3949 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003950 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003951 return result;
3952}
3953
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003954thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003955Process::RunPrivateStateThread ()
3956{
Jim Ingham076b3042012-04-10 01:21:57 +00003957 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003958 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003959
Greg Clayton5160ce52013-03-27 23:08:40 +00003960 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003961 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003962 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3963 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964
3965 bool exit_now = false;
3966 while (!exit_now)
3967 {
3968 EventSP event_sp;
3969 WaitForEventsPrivate (NULL, event_sp, control_only);
3970 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3971 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003972 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003973 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
3974 __FUNCTION__, static_cast<void*>(this), GetID(),
3975 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00003976
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003977 switch (event_sp->GetType())
3978 {
3979 case eBroadcastInternalStateControlStop:
3980 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003981 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982
3983 case eBroadcastInternalStateControlPause:
3984 control_only = true;
3985 break;
3986
3987 case eBroadcastInternalStateControlResume:
3988 control_only = false;
3989 break;
3990 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003992 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003993 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003994 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003995 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3996 {
3997 if (m_public_state.GetValue() == eStateAttaching)
3998 {
3999 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004000 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4001 __FUNCTION__, static_cast<void*>(this),
4002 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004003 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4004 }
4005 else
4006 {
4007 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004008 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4009 __FUNCTION__, static_cast<void*>(this),
4010 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004011 Halt();
4012 }
4013 continue;
4014 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004015
4016 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4017
4018 if (internal_state != eStateInvalid)
4019 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004020 if (m_clear_thread_plans_on_stop &&
4021 StateIsStoppedState(internal_state, true))
4022 {
4023 m_clear_thread_plans_on_stop = false;
4024 m_thread_list.DiscardThreadPlans();
4025 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004026 HandlePrivateEvent (event_sp);
4027 }
4028
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004029 if (internal_state == eStateInvalid ||
4030 internal_state == eStateExited ||
4031 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004032 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004033 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004034 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4035 __FUNCTION__, static_cast<void*>(this), GetID(),
4036 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004037
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004039 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004040 }
4041
Caroline Tice20ad3c42010-10-29 21:48:37 +00004042 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004043 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004044 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4045 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004046
Ed Maste64fad602013-07-29 20:58:06 +00004047 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004048 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4049 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050 return NULL;
4051}
4052
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053//------------------------------------------------------------------
4054// Process Event Data
4055//------------------------------------------------------------------
4056
4057Process::ProcessEventData::ProcessEventData () :
4058 EventData (),
4059 m_process_sp (),
4060 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004061 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004062 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004063 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004064{
4065}
4066
4067Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4068 EventData (),
4069 m_process_sp (process_sp),
4070 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004071 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004072 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004073 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074{
4075}
4076
4077Process::ProcessEventData::~ProcessEventData()
4078{
4079}
4080
4081const ConstString &
4082Process::ProcessEventData::GetFlavorString ()
4083{
4084 static ConstString g_flavor ("Process::ProcessEventData");
4085 return g_flavor;
4086}
4087
4088const ConstString &
4089Process::ProcessEventData::GetFlavor () const
4090{
4091 return ProcessEventData::GetFlavorString ();
4092}
4093
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094void
4095Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4096{
4097 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004098 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4099 // the public event queue, then other times when we're pretending that this is where we stopped at the
4100 // end of expression evaluation. m_update_state is used to distinguish these
4101 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004102 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004103 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004105
Jim Ingham221d51c2013-05-08 00:35:16 +00004106 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004107
4108 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4109 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4110 // end up restarting the process.
4111 if (m_interrupted)
4112 return;
4113
4114 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004116 {
4117 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004118 uint32_t num_threads = curr_thread_list.GetSize();
4119 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004120
Jim Ingham4b536182011-08-09 02:12:22 +00004121 // The actions might change one of the thread's stop_info's opinions about whether we should
4122 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004123
4124 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4125 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4126 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4127 // 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
4128 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004129 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004130 for (idx = 0; idx < num_threads; ++idx)
4131 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4132
Jim Inghamc7078c22012-12-13 22:24:15 +00004133 // Use this to track whether we should continue from here. We will only continue the target running if
4134 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4135 // then it doesn't matter what the other threads say...
4136
4137 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004138
Jim Ingham0ad7e052013-04-25 02:04:59 +00004139 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4140 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4141 // thing to do is, and it's better to let the user decide than continue behind their backs.
4142
4143 bool does_anybody_have_an_opinion = false;
4144
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145 for (idx = 0; idx < num_threads; ++idx)
4146 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004147 curr_thread_list = m_process_sp->GetThreadList();
4148 if (curr_thread_list.GetSize() != num_threads)
4149 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004150 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004151 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004152 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 +00004153 break;
4154 }
4155
4156 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4157
4158 if (thread_sp->GetIndexID() != thread_index_array[idx])
4159 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004160 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004161 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004162 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004163 idx,
4164 thread_index_array[idx],
4165 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004166 break;
4167 }
4168
Jim Inghamb15bfc72010-10-20 00:39:53 +00004169 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004170 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004171 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004172 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004173 bool this_thread_wants_to_stop;
4174 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004175 {
Jim Ingham0161b492013-02-09 01:29:05 +00004176 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4177 }
4178 else
4179 {
4180 stop_info_sp->PerformAction(event_ptr);
4181 // The stop action might restart the target. If it does, then we want to mark that in the
4182 // event so that whoever is receiving it will know to wait for the running event and reflect
4183 // that state appropriately.
4184 // We also need to stop processing actions, since they aren't expecting the target to be running.
4185
4186 // FIXME: we might have run.
4187 if (stop_info_sp->HasTargetRunSinceMe())
4188 {
4189 SetRestarted (true);
4190 break;
4191 }
4192
4193 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004194 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004195
Jim Inghamc7078c22012-12-13 22:24:15 +00004196 if (still_should_stop == false)
4197 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004198 }
4199 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004200
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004201
Jim Inghama8ca6e22013-05-03 23:04:37 +00004202 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004203 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004204 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004205 {
4206 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004207 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004208 // Use the public resume method here, since this is just
4209 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004210 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004211 }
4212 else
4213 {
4214 // If we didn't restart, run the Stop Hooks here:
4215 // They might also restart the target, so watch for that.
4216 m_process_sp->GetTarget().RunStopHooks();
4217 if (m_process_sp->GetPrivateState() == eStateRunning)
4218 SetRestarted(true);
4219 }
Jim Ingham9575d842011-03-11 03:53:59 +00004220 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004221 }
4222}
4223
4224void
4225Process::ProcessEventData::Dump (Stream *s) const
4226{
4227 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004228 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4229 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004230
Greg Clayton8b82f082011-04-12 05:54:46 +00004231 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004232}
4233
4234const Process::ProcessEventData *
4235Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4236{
4237 if (event_ptr)
4238 {
4239 const EventData *event_data = event_ptr->GetData();
4240 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4241 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4242 }
4243 return NULL;
4244}
4245
4246ProcessSP
4247Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4248{
4249 ProcessSP process_sp;
4250 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4251 if (data)
4252 process_sp = data->GetProcessSP();
4253 return process_sp;
4254}
4255
4256StateType
4257Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4258{
4259 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4260 if (data == NULL)
4261 return eStateInvalid;
4262 else
4263 return data->GetState();
4264}
4265
4266bool
4267Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4268{
4269 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4270 if (data == NULL)
4271 return false;
4272 else
4273 return data->GetRestarted();
4274}
4275
4276void
4277Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4278{
4279 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4280 if (data != NULL)
4281 data->SetRestarted(new_value);
4282}
4283
Jim Ingham0161b492013-02-09 01:29:05 +00004284size_t
4285Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4286{
4287 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4288 if (data != NULL)
4289 return data->GetNumRestartedReasons();
4290 else
4291 return 0;
4292}
4293
4294const char *
4295Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4296{
4297 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4298 if (data != NULL)
4299 return data->GetRestartedReasonAtIndex(idx);
4300 else
4301 return NULL;
4302}
4303
4304void
4305Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4306{
4307 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4308 if (data != NULL)
4309 data->AddRestartedReason(reason);
4310}
4311
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004312bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004313Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4314{
4315 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4316 if (data == NULL)
4317 return false;
4318 else
4319 return data->GetInterrupted ();
4320}
4321
4322void
4323Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4324{
4325 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4326 if (data != NULL)
4327 data->SetInterrupted(new_value);
4328}
4329
4330bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004331Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4332{
4333 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4334 if (data)
4335 {
4336 data->SetUpdateStateOnRemoval();
4337 return true;
4338 }
4339 return false;
4340}
4341
Greg Claytond9e416c2012-02-18 05:35:26 +00004342lldb::TargetSP
4343Process::CalculateTarget ()
4344{
4345 return m_target.shared_from_this();
4346}
4347
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348void
Greg Clayton0603aa92010-10-04 01:05:56 +00004349Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004350{
Greg Claytonc14ee322011-09-22 04:58:26 +00004351 exe_ctx.SetTargetPtr (&m_target);
4352 exe_ctx.SetProcessPtr (this);
4353 exe_ctx.SetThreadPtr(NULL);
4354 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004355}
4356
Greg Claytone996fd32011-03-08 22:40:15 +00004357//uint32_t
4358//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4359//{
4360// return 0;
4361//}
4362//
4363//ArchSpec
4364//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4365//{
4366// return Host::GetArchSpecForExistingProcess (pid);
4367//}
4368//
4369//ArchSpec
4370//Process::GetArchSpecForExistingProcess (const char *process_name)
4371//{
4372// return Host::GetArchSpecForExistingProcess (process_name);
4373//}
4374//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004375void
4376Process::AppendSTDOUT (const char * s, size_t len)
4377{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004378 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004379 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004380 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004381}
4382
4383void
Greg Clayton93e86192011-11-13 04:45:22 +00004384Process::AppendSTDERR (const char * s, size_t len)
4385{
4386 Mutex::Locker locker (m_stdio_communication_mutex);
4387 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004388 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004389}
4390
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004391void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004392Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004393{
4394 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004395 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004396 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4397}
4398
4399size_t
4400Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4401{
4402 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004403 if (m_profile_data.empty())
4404 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004405
4406 std::string &one_profile_data = m_profile_data.front();
4407 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004408 if (bytes_available > 0)
4409 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004410 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004411 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004412 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4413 static_cast<void*>(buf),
4414 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004415 if (bytes_available > buf_size)
4416 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004417 memcpy(buf, one_profile_data.c_str(), buf_size);
4418 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004419 bytes_available = buf_size;
4420 }
4421 else
4422 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004423 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004424 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004425 }
4426 }
4427 return bytes_available;
4428}
4429
4430
Greg Clayton93e86192011-11-13 04:45:22 +00004431//------------------------------------------------------------------
4432// Process STDIO
4433//------------------------------------------------------------------
4434
4435size_t
4436Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4437{
4438 Mutex::Locker locker(m_stdio_communication_mutex);
4439 size_t bytes_available = m_stdout_data.size();
4440 if (bytes_available > 0)
4441 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004442 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004443 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004444 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4445 static_cast<void*>(buf),
4446 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004447 if (bytes_available > buf_size)
4448 {
4449 memcpy(buf, m_stdout_data.c_str(), buf_size);
4450 m_stdout_data.erase(0, buf_size);
4451 bytes_available = buf_size;
4452 }
4453 else
4454 {
4455 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4456 m_stdout_data.clear();
4457 }
4458 }
4459 return bytes_available;
4460}
4461
4462
4463size_t
4464Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4465{
4466 Mutex::Locker locker(m_stdio_communication_mutex);
4467 size_t bytes_available = m_stderr_data.size();
4468 if (bytes_available > 0)
4469 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004470 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004471 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004472 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4473 static_cast<void*>(buf),
4474 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004475 if (bytes_available > buf_size)
4476 {
4477 memcpy(buf, m_stderr_data.c_str(), buf_size);
4478 m_stderr_data.erase(0, buf_size);
4479 bytes_available = buf_size;
4480 }
4481 else
4482 {
4483 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4484 m_stderr_data.clear();
4485 }
4486 }
4487 return bytes_available;
4488}
4489
4490void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004491Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4492{
4493 Process *process = (Process *) baton;
4494 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4495}
4496
Greg Clayton44d93782014-01-27 23:43:24 +00004497class IOHandlerProcessSTDIO :
4498 public IOHandler
4499{
4500public:
4501 IOHandlerProcessSTDIO (Process *process,
4502 int write_fd) :
4503 IOHandler(process->GetTarget().GetDebugger()),
4504 m_process (process),
4505 m_read_file (),
4506 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004507 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004508 {
4509 m_read_file.SetDescriptor(GetInputFD(), false);
4510 }
4511
4512 virtual
4513 ~IOHandlerProcessSTDIO ()
4514 {
4515
4516 }
4517
4518 bool
4519 OpenPipes ()
4520 {
Greg Clayton100eb932014-07-02 21:10:39 +00004521 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004522 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004523 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004524 }
4525
4526 void
4527 ClosePipes()
4528 {
Greg Clayton100eb932014-07-02 21:10:39 +00004529 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004530 }
4531
4532 // Each IOHandler gets to run until it is done. It should read data
4533 // from the "in" and place output into "out" and "err and return
4534 // when done.
4535 virtual void
4536 Run ()
4537 {
4538 if (m_read_file.IsValid() && m_write_file.IsValid())
4539 {
4540 SetIsDone(false);
4541 if (OpenPipes())
4542 {
4543 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004544 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004545 TerminalState terminal_state;
4546 terminal_state.Save (read_fd, false);
4547 Terminal terminal(read_fd);
4548 terminal.SetCanonical(false);
4549 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004550// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004551#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004552 while (!GetIsDone())
4553 {
4554 fd_set read_fdset;
4555 FD_ZERO (&read_fdset);
4556 FD_SET (read_fd, &read_fdset);
4557 FD_SET (pipe_read_fd, &read_fdset);
4558 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4559 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4560 if (num_set_fds < 0)
4561 {
4562 const int select_errno = errno;
4563
4564 if (select_errno != EINTR)
4565 SetIsDone(true);
4566 }
4567 else if (num_set_fds > 0)
4568 {
4569 char ch = 0;
4570 size_t n;
4571 if (FD_ISSET (read_fd, &read_fdset))
4572 {
4573 n = 1;
4574 if (m_read_file.Read(&ch, n).Success() && n == 1)
4575 {
4576 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4577 SetIsDone(true);
4578 }
4579 else
4580 SetIsDone(true);
4581 }
4582 if (FD_ISSET (pipe_read_fd, &read_fdset))
4583 {
4584 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004585 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004586 {
Greg Clayton100eb932014-07-02 21:10:39 +00004587 switch (ch)
4588 {
4589 case 'q':
4590 SetIsDone(true);
4591 break;
4592 case 'i':
4593 if (StateIsRunningState(m_process->GetState()))
4594 m_process->Halt();
4595 break;
4596 }
Greg Clayton19e11352014-02-26 22:47:33 +00004597 }
Greg Clayton44d93782014-01-27 23:43:24 +00004598 }
4599 }
4600 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004601#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004602 terminal_state.Restore();
4603
4604 }
4605 else
4606 SetIsDone(true);
4607 }
4608 else
4609 SetIsDone(true);
4610 }
4611
4612 // Hide any characters that have been displayed so far so async
4613 // output can be displayed. Refresh() will be called after the
4614 // output has been displayed.
4615 virtual void
4616 Hide ()
4617 {
4618
4619 }
4620 // Called when the async output has been received in order to update
4621 // the input reader (refresh the prompt and redisplay any current
4622 // line(s) that are being edited
4623 virtual void
4624 Refresh ()
4625 {
4626
4627 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004628
Greg Clayton44d93782014-01-27 23:43:24 +00004629 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004630 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004631 {
Greg Clayton19e11352014-02-26 22:47:33 +00004632 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004633 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004634 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004635
Greg Claytonf0066ad2014-05-02 00:45:31 +00004636 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004637 Interrupt ()
4638 {
Greg Clayton19e11352014-02-26 22:47:33 +00004639 // Do only things that are safe to do in an interrupt context (like in
4640 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4641 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4642 // that was written to the pipe and then call m_process->Halt() from a
4643 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004644 if (m_active)
4645 {
4646 char ch = 'i'; // Send 'i' for interrupt
4647 return m_pipe.Write (&ch, 1) == 1;
4648 }
4649 else
4650 {
4651 // This IOHandler might be pushed on the stack, but not being run currently
4652 // so do the right thing if we aren't actively watching for STDIN by sending
4653 // the interrupt to the process. Otherwise the write to the pipe above would
4654 // do nothing. This can happen when the command interpreter is running and
4655 // gets a "expression ...". It will be on the IOHandler thread and sending
4656 // the input is complete to the delegate which will cause the expression to
4657 // run, which will push the process IO handler, but not run it.
4658
4659 if (StateIsRunningState(m_process->GetState()))
4660 {
4661 m_process->SendAsyncInterrupt();
4662 return true;
4663 }
4664 }
4665 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004666 }
Greg Clayton44d93782014-01-27 23:43:24 +00004667
4668 virtual void
4669 GotEOF()
4670 {
4671
4672 }
4673
4674protected:
4675 Process *m_process;
4676 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4677 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004678 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004679};
4680
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004681void
Greg Clayton44d93782014-01-27 23:43:24 +00004682Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004683{
4684 // First set up the Read Thread for reading/handling process I/O
4685
Greg Clayton44d93782014-01-27 23:43:24 +00004686 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004687
4688 if (conn_ap.get())
4689 {
4690 m_stdio_communication.SetConnection (conn_ap.release());
4691 if (m_stdio_communication.IsConnected())
4692 {
4693 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4694 m_stdio_communication.StartReadThread();
4695
4696 // Now read thread is set up, set up input reader.
4697
4698 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004699 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004700 }
4701 }
4702}
4703
Greg Claytonb4874f12014-02-28 18:22:24 +00004704bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004705Process::ProcessIOHandlerIsActive ()
4706{
4707 IOHandlerSP io_handler_sp (m_process_input_reader);
4708 if (io_handler_sp)
4709 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4710 return false;
4711}
4712bool
Greg Clayton44d93782014-01-27 23:43:24 +00004713Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004714{
Greg Clayton44d93782014-01-27 23:43:24 +00004715 IOHandlerSP io_handler_sp (m_process_input_reader);
4716 if (io_handler_sp)
4717 {
4718 io_handler_sp->SetIsDone(false);
4719 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004720 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004721 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004722 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004723}
4724
Greg Claytonb4874f12014-02-28 18:22:24 +00004725bool
Greg Clayton44d93782014-01-27 23:43:24 +00004726Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004727{
Greg Clayton44d93782014-01-27 23:43:24 +00004728 IOHandlerSP io_handler_sp (m_process_input_reader);
4729 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004730 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4731 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004732}
4733
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004734// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004735void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004736Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004737{
Greg Clayton6920b522012-08-22 18:39:03 +00004738 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004739}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004740
Greg Clayton99d0faf2010-11-18 23:32:35 +00004741void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004742Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004743{
Greg Clayton6920b522012-08-22 18:39:03 +00004744 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004745}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004746
Jim Ingham1624a2d2014-05-05 02:26:40 +00004747ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004748Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004749 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004750 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004751 Stream &errors)
4752{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004753 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004754
Jim Ingham77787032011-01-20 02:03:18 +00004755 if (thread_plan_sp.get() == NULL)
4756 {
4757 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004758 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004759 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004760
Jim Ingham7d7931d2013-03-28 00:05:34 +00004761 if (!thread_plan_sp->ValidatePlan(NULL))
4762 {
4763 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004764 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004765 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004766
Greg Claytonc14ee322011-09-22 04:58:26 +00004767 if (exe_ctx.GetProcessPtr() != this)
4768 {
4769 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004770 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004771 }
4772
4773 Thread *thread = exe_ctx.GetThreadPtr();
4774 if (thread == NULL)
4775 {
4776 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004777 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004778 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004779
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004780 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4781 // For that to be true the plan can't be private - since private plans suppress themselves in the
4782 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004783
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004784 bool orig_plan_private = thread_plan_sp->GetPrivate();
4785 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004786
Jim Ingham444586b2011-01-24 06:34:17 +00004787 if (m_private_state.GetValue() != eStateStopped)
4788 {
4789 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004790 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004791 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004792
Jim Ingham66243842011-08-13 00:56:10 +00004793 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004794 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004795 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004796 if (!selected_frame_sp)
4797 {
4798 thread->SetSelectedFrame(0);
4799 selected_frame_sp = thread->GetSelectedFrame();
4800 if (!selected_frame_sp)
4801 {
4802 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004803 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004804 }
4805 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004806
Jim Ingham11b0e052013-02-19 23:22:45 +00004807 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004808
4809 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4810 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004811
Greg Claytonc14ee322011-09-22 04:58:26 +00004812 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004813
Jim Ingham66243842011-08-13 00:56:10 +00004814 uint32_t selected_tid;
4815 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004816 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004817 {
4818 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004819 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004820 }
4821 else
4822 {
4823 selected_tid = LLDB_INVALID_THREAD_ID;
4824 }
4825
Jim Ingham372787f2012-04-07 00:00:41 +00004826 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004827 lldb::StateType old_state;
4828 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004829
Greg Clayton5160ce52013-03-27 23:08:40 +00004830 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004831 if (Host::GetCurrentThread() == m_private_state_thread)
4832 {
Jim Ingham076b3042012-04-10 01:21:57 +00004833 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4834 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004835 // 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 +00004836 // we are fielding public events here.
4837 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004838 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 +00004839
Jim Ingham372787f2012-04-07 00:00:41 +00004840 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004841
4842 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4843 // returning control here.
4844 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4845 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4846 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4847 // do just what we want.
4848 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4849 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4850 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4851 old_state = m_public_state.GetValue();
4852 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004853
Jim Ingham076b3042012-04-10 01:21:57 +00004854 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004855 StartPrivateStateThread(true);
4856 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004857
Jim Ingham372787f2012-04-07 00:00:41 +00004858 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004859
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004860 if (options.GetDebug())
4861 {
4862 // In this case, we aren't actually going to run, we just want to stop right away.
4863 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4864 // FIXME: To make this prettier we should invent some stop reason for this, but that
4865 // is only cosmetic, and this functionality is only of use to lldb developers who can
4866 // live with not pretty...
4867 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004868 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004869 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004870
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004871 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004872
Sean Callanana46ec452012-07-11 21:31:24 +00004873 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004874
Jim Ingham77787032011-01-20 02:03:18 +00004875 {
Sean Callanana46ec452012-07-11 21:31:24 +00004876 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4877 // restored on exit to the function.
4878 //
4879 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4880 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004881
Sean Callanana46ec452012-07-11 21:31:24 +00004882 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004883
Jim Inghamf48169b2010-11-30 02:22:11 +00004884 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004885 {
4886 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004887 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004888 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004889 thread->GetIndexID(),
4890 thread->GetID(),
4891 s.GetData());
4892 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004893
Sean Callanana46ec452012-07-11 21:31:24 +00004894 bool got_event;
4895 lldb::EventSP event_sp;
4896 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004897
Sean Callanana46ec452012-07-11 21:31:24 +00004898 TimeValue* timeout_ptr = NULL;
4899 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004900
Jim Ingham0161b492013-02-09 01:29:05 +00004901 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 +00004902 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004903 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004904 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004905
Jim Ingham0161b492013-02-09 01:29:05 +00004906 // This is just for accounting:
4907 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004908
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004909 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00004910 uint32_t one_thread_timeout_usec;
4911 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00004912
4913 // If we are going to run all threads the whole time, or if we are only going to run one thread,
4914 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
4915 // first timeout already.
4916
4917 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00004918 {
4919 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00004920 one_thread_timeout_usec = 0;
4921 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00004922 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004923 else
Jim Ingham0161b492013-02-09 01:29:05 +00004924 {
Jim Inghamfd95f892014-04-22 01:41:52 +00004925 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004926
Jim Ingham914f4e72014-03-28 21:58:28 +00004927 // If the overall wait is forever, then we only need to set the one thread timeout:
4928 if (timeout_usec == 0)
4929 {
Ed Maste801335c2014-03-31 19:28:14 +00004930 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00004931 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00004932 else
Jim Inghamfd95f892014-04-22 01:41:52 +00004933 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00004934 }
Jim Ingham0161b492013-02-09 01:29:05 +00004935 else
4936 {
Jim Ingham914f4e72014-03-28 21:58:28 +00004937 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
4938 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
4939 uint64_t computed_one_thread_timeout;
4940 if (option_one_thread_timeout != 0)
4941 {
4942 if (timeout_usec < option_one_thread_timeout)
4943 {
4944 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004945 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00004946 }
4947 computed_one_thread_timeout = option_one_thread_timeout;
4948 }
4949 else
4950 {
4951 computed_one_thread_timeout = timeout_usec / 2;
4952 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
4953 computed_one_thread_timeout = default_one_thread_timeout_usec;
4954 }
Jim Inghamfd95f892014-04-22 01:41:52 +00004955 one_thread_timeout_usec = computed_one_thread_timeout;
4956 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
4957
Jim Ingham0161b492013-02-09 01:29:05 +00004958 }
Jim Ingham0161b492013-02-09 01:29:05 +00004959 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004960
4961 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00004962 log->Printf ("Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32 " - all threads: %" PRIu32 ".\n",
Jim Inghamfe1c3422014-04-16 02:24:48 +00004963 options.GetStopOthers(),
4964 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00004965 before_first_timeout,
4966 one_thread_timeout_usec,
4967 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00004968
Jim Ingham1460e4b2014-01-10 23:46:59 +00004969 // This isn't going to work if there are unfetched events on the queue.
4970 // Are there cases where we might want to run the remaining events here, and then try to
4971 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004972
Jim Ingham1460e4b2014-01-10 23:46:59 +00004973 Event *other_events = listener.PeekAtNextEvent();
4974 if (other_events != NULL)
4975 {
4976 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004977 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00004978 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004979
Jim Ingham1460e4b2014-01-10 23:46:59 +00004980 // We also need to make sure that the next event is delivered. We might be calling a function as part of
4981 // a thread plan, in which case the last delivered event could be the running event, and we don't want
4982 // event coalescing to cause us to lose OUR running event...
4983 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004984
Jim Ingham8559a352012-11-26 23:52:18 +00004985 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4986 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00004987
4988#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4989 // It's pretty much impossible to write test cases for things like:
4990 // One thread timeout expires, I go to halt, but the process already stopped
4991 // on the function call stop breakpoint. Turning on this define will make us not
4992 // fetch the first event till after the halt. So if you run a quick function, it will have
4993 // completed, and the completion event will be waiting, when you interrupt for halt.
4994 // The expression evaluation should still succeed.
4995 bool miss_first_event = true;
4996#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00004997 TimeValue one_thread_timeout;
4998 TimeValue final_timeout;
4999
Jim Ingham35878c42014-04-08 21:33:21 +00005000
Sean Callanana46ec452012-07-11 21:31:24 +00005001 while (1)
5002 {
5003 // We usually want to resume the process if we get to the top of the loop.
5004 // The only exception is if we get two running events with no intervening
5005 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005006 if (log)
5007 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5008 do_resume,
5009 handle_running_event,
5010 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005011
Jim Ingham184e9812013-01-15 02:47:48 +00005012 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005013 {
5014 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005015
Jim Ingham184e9812013-01-15 02:47:48 +00005016 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005017 {
Jim Ingham0161b492013-02-09 01:29:05 +00005018 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005019 Error resume_error = PrivateResume ();
5020 if (!resume_error.Success())
5021 {
Jim Ingham0161b492013-02-09 01:29:05 +00005022 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5023 num_resumes,
5024 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005025 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005026 break;
5027 }
Sean Callanana46ec452012-07-11 21:31:24 +00005028 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005029
Jim Ingham0161b492013-02-09 01:29:05 +00005030 TimeValue resume_timeout = TimeValue::Now();
5031 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005032
Jim Ingham0161b492013-02-09 01:29:05 +00005033 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005034 if (!got_event)
5035 {
5036 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005037 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5038 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005039
Jim Ingham0161b492013-02-09 01:29:05 +00005040 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005041 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005042 break;
5043 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005044
Sean Callanana46ec452012-07-11 21:31:24 +00005045 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005046
Sean Callanana46ec452012-07-11 21:31:24 +00005047 if (stop_state != eStateRunning)
5048 {
Jim Ingham0161b492013-02-09 01:29:05 +00005049 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005050
Jim Ingham0161b492013-02-09 01:29:05 +00005051 if (stop_state == eStateStopped)
5052 {
5053 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5054 if (log)
5055 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5056 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5057 num_resumes,
5058 StateAsCString(stop_state),
5059 restarted,
5060 do_resume,
5061 handle_running_event);
5062 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005063
Jim Ingham0161b492013-02-09 01:29:05 +00005064 if (restarted)
5065 {
5066 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5067 // event here. But if I do, the best thing is to Halt and then get out of here.
5068 Halt();
5069 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005070
Jim Ingham35e1bda2012-10-16 21:41:58 +00005071 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5072 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005073 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005074 break;
5075 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005076
Sean Callanana46ec452012-07-11 21:31:24 +00005077 if (log)
5078 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5079 // We need to call the function synchronously, so spin waiting for it to return.
5080 // If we get interrupted while executing, we're going to lose our context, and
5081 // won't be able to gather the result at this point.
5082 // We set the timeout AFTER the resume, since the resume takes some time and we
5083 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005084 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005085 else
5086 {
Sean Callanana46ec452012-07-11 21:31:24 +00005087 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005088 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005089 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005090
Jim Ingham0161b492013-02-09 01:29:05 +00005091 if (before_first_timeout)
5092 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005093 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005094 {
5095 one_thread_timeout = TimeValue::Now();
5096 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005097 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005098 }
Jim Ingham0161b492013-02-09 01:29:05 +00005099 else
5100 {
5101 if (timeout_usec == 0)
5102 timeout_ptr = NULL;
5103 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005104 {
5105 final_timeout = TimeValue::Now();
5106 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005107 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005108 }
Jim Ingham0161b492013-02-09 01:29:05 +00005109 }
5110 }
5111 else
5112 {
5113 if (timeout_usec == 0)
5114 timeout_ptr = NULL;
5115 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005116 {
5117 final_timeout = TimeValue::Now();
5118 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005119 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005120 }
Jim Ingham0161b492013-02-09 01:29:05 +00005121 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005122
Jim Ingham0161b492013-02-09 01:29:05 +00005123 do_resume = true;
5124 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005125
Sean Callanana46ec452012-07-11 21:31:24 +00005126 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005127 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005128
Jim Ingham0f16e732011-02-08 05:20:59 +00005129 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005130 {
Sean Callanana46ec452012-07-11 21:31:24 +00005131 if (timeout_ptr)
5132 {
Matt Kopec676a4872013-02-21 23:55:31 +00005133 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005134 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5135 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005136 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005137 else
Sean Callanana46ec452012-07-11 21:31:24 +00005138 {
5139 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5140 }
5141 }
Jim Ingham35878c42014-04-08 21:33:21 +00005142
5143#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5144 // See comment above...
5145 if (miss_first_event)
5146 {
5147 usleep(1000);
5148 miss_first_event = false;
5149 got_event = false;
5150 }
5151 else
5152#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005153 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005154
Sean Callanana46ec452012-07-11 21:31:24 +00005155 if (got_event)
5156 {
5157 if (event_sp.get())
5158 {
5159 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005160 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005161 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005162 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005163 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005164 errors.Printf ("Execution halted by user interrupt.");
5165 if (log)
5166 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005167 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005168 }
5169 else
5170 {
5171 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5172 if (log)
5173 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005174
Jim Inghamcfc09352012-07-27 23:57:19 +00005175 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005176 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005177 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005178 {
Jim Ingham0161b492013-02-09 01:29:05 +00005179 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005180 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5181 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005182 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005183 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005184 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005185 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005186 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005187 }
5188 else
5189 {
Jim Ingham0161b492013-02-09 01:29:05 +00005190 // If we were restarted, we just need to go back up to fetch another event.
5191 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005192 {
5193 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005194 {
5195 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5196 }
5197 keep_going = true;
5198 do_resume = false;
5199 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005200
Jim Inghamcfc09352012-07-27 23:57:19 +00005201 }
5202 else
5203 {
Jim Ingham0161b492013-02-09 01:29:05 +00005204 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5205 StopReason stop_reason = eStopReasonInvalid;
5206 if (stop_info_sp)
5207 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005208
Jim Ingham0161b492013-02-09 01:29:05 +00005209 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5210 // it is OUR plan that is complete?
5211 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005212 {
5213 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005214 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5215 // Now mark this plan as private so it doesn't get reported as the stop reason
5216 // after this point.
5217 if (thread_plan_sp)
5218 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005219 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005220 }
5221 else
5222 {
Jim Ingham0161b492013-02-09 01:29:05 +00005223 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005224 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005225 {
5226 if (log)
5227 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005228 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005229 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005230 {
5231 event_to_broadcast_sp = event_sp;
5232 }
Jim Ingham0161b492013-02-09 01:29:05 +00005233 }
Jim Ingham184e9812013-01-15 02:47:48 +00005234 else
Jim Ingham0161b492013-02-09 01:29:05 +00005235 {
5236 if (log)
5237 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005238 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005239 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005240 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005241 }
Jim Ingham184e9812013-01-15 02:47:48 +00005242 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005243 }
Sean Callanana46ec452012-07-11 21:31:24 +00005244 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005245 }
5246 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005247
Jim Inghamcfc09352012-07-27 23:57:19 +00005248 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005249 // This shouldn't really happen, but sometimes we do get two running events without an
5250 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005251 do_resume = false;
5252 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005253 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005254 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005255
Jim Inghamcfc09352012-07-27 23:57:19 +00005256 default:
5257 if (log)
5258 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005259
Jim Inghamcfc09352012-07-27 23:57:19 +00005260 if (stop_state == eStateExited)
5261 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005262
Sean Callananbf154da2012-08-08 17:35:10 +00005263 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005264 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005265 break;
5266 }
Sean Callanana46ec452012-07-11 21:31:24 +00005267 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005268
Sean Callanana46ec452012-07-11 21:31:24 +00005269 if (keep_going)
5270 continue;
5271 else
5272 break;
5273 }
5274 else
5275 {
5276 if (log)
5277 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005278 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005279 break;
5280 }
5281 }
5282 else
5283 {
5284 // If we didn't get an event that means we've timed out...
5285 // We will interrupt the process here. Depending on what we were asked to do we will
5286 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005287
Sean Callanana46ec452012-07-11 21:31:24 +00005288 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005289 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005290 {
Jim Ingham0161b492013-02-09 01:29:05 +00005291 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005292 {
5293 if (timeout_usec != 0)
5294 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005295 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005296 "running for %" PRIu32 " usec with all threads enabled.",
5297 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005298 }
5299 else
5300 {
5301 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005302 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005303 }
5304 }
Sean Callanana46ec452012-07-11 21:31:24 +00005305 else
5306 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005307 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005308 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005309 }
5310 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005311 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005312 "abandoning execution.",
5313 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005314 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005315
Jim Ingham0161b492013-02-09 01:29:05 +00005316 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5317 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5318 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5319 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5320 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005321
Jim Ingham0161b492013-02-09 01:29:05 +00005322 bool back_to_top = true;
5323 uint32_t try_halt_again = 0;
5324 bool do_halt = true;
5325 const uint32_t num_retries = 5;
5326 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005327 {
Jim Ingham0161b492013-02-09 01:29:05 +00005328 Error halt_error;
5329 if (do_halt)
5330 {
5331 if (log)
5332 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5333 halt_error = Halt();
5334 }
5335 if (halt_error.Success())
5336 {
5337 if (log)
5338 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005339
Jim Ingham0161b492013-02-09 01:29:05 +00005340 real_timeout = TimeValue::Now();
5341 real_timeout.OffsetWithMicroSeconds(500000);
5342
5343 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005344
Jim Ingham0161b492013-02-09 01:29:05 +00005345 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005346 {
Jim Ingham0161b492013-02-09 01:29:05 +00005347 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5348 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005349 {
Jim Ingham0161b492013-02-09 01:29:05 +00005350 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5351 if (stop_state == lldb::eStateStopped
5352 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5353 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005354 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005355
Jim Ingham0161b492013-02-09 01:29:05 +00005356 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005357 {
Jim Ingham0161b492013-02-09 01:29:05 +00005358 // Between the time we initiated the Halt and the time we delivered it, the process could have
5359 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005360
Jim Ingham0161b492013-02-09 01:29:05 +00005361 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5362 {
5363 if (log)
5364 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5365 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005366 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005367 back_to_top = false;
5368 break;
5369 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005370
Jim Ingham0161b492013-02-09 01:29:05 +00005371 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5372 {
5373 if (log)
5374 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5375 "Exiting wait loop.");
5376 try_halt_again++;
5377 do_halt = false;
5378 continue;
5379 }
Sean Callanana46ec452012-07-11 21:31:24 +00005380
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005381 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005382 {
5383 if (log)
5384 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005385 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005386 back_to_top = false;
5387 break;
5388 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005389
Jim Ingham0161b492013-02-09 01:29:05 +00005390 if (before_first_timeout)
5391 {
5392 // Set all the other threads to run, and return to the top of the loop, which will continue;
5393 before_first_timeout = false;
5394 thread_plan_sp->SetStopOthers (false);
5395 if (log)
5396 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005397
Jim Ingham0161b492013-02-09 01:29:05 +00005398 back_to_top = true;
5399 break;
5400 }
5401 else
5402 {
5403 // Running all threads failed, so return Interrupted.
5404 if (log)
5405 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005406 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005407 back_to_top = false;
5408 break;
5409 }
Sean Callanana46ec452012-07-11 21:31:24 +00005410 }
5411 }
5412 else
Jim Ingham0161b492013-02-09 01:29:05 +00005413 { if (log)
5414 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5415 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005416 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005417 back_to_top = false;
5418 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005419 }
5420 }
Jim Ingham0161b492013-02-09 01:29:05 +00005421 else
5422 {
5423 try_halt_again++;
5424 continue;
5425 }
Sean Callanana46ec452012-07-11 21:31:24 +00005426 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005427
Jim Ingham0161b492013-02-09 01:29:05 +00005428 if (!back_to_top || try_halt_again > num_retries)
5429 break;
5430 else
5431 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005432 }
Sean Callanana46ec452012-07-11 21:31:24 +00005433 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005434
Sean Callanana46ec452012-07-11 21:31:24 +00005435 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5436 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5437 {
5438 StopPrivateStateThread();
5439 Error error;
5440 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005441 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005442 {
5443 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5444 }
5445 m_public_state.SetValueNoLock(old_state);
5446
5447 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005448
Jim Ingham184e9812013-01-15 02:47:48 +00005449 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5450 // could happen:
5451 // 1) The execution successfully completed
5452 // 2) We hit a breakpoint, and ignore_breakpoints was true
5453 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005454 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5455 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005456
Jim Ingham8646d3c2014-05-05 02:47:44 +00005457 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005458 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005459 {
5460 thread_plan_sp->RestoreThreadState();
5461 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005462
Sean Callanana46ec452012-07-11 21:31:24 +00005463 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005464 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005465 {
5466 if (log)
5467 {
5468 StreamString s;
5469 if (event_sp)
5470 event_sp->Dump (&s);
5471 else
5472 {
5473 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5474 }
5475
5476 StreamString ts;
5477
5478 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005479
Sean Callanana46ec452012-07-11 21:31:24 +00005480 do
5481 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005482 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005483 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005484 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005485 break;
5486 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005487 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005488 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005489 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005490 break;
5491 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005492 else
Sean Callanana46ec452012-07-11 21:31:24 +00005493 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005494 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5495
5496 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005497 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005498 event_explanation = "<no event data>";
5499 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005500 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005501
Jim Inghamcfc09352012-07-27 23:57:19 +00005502 Process *process = event_data->GetProcessSP().get();
5503
5504 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005505 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005506 event_explanation = "<no process>";
5507 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005508 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005509
Jim Inghamcfc09352012-07-27 23:57:19 +00005510 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005511
Jim Inghamcfc09352012-07-27 23:57:19 +00005512 uint32_t num_threads = thread_list.GetSize();
5513 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005514
Jim Inghamcfc09352012-07-27 23:57:19 +00005515 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005516
Jim Inghamcfc09352012-07-27 23:57:19 +00005517 for (thread_index = 0;
5518 thread_index < num_threads;
5519 ++thread_index)
5520 {
5521 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005522
Jim Inghamcfc09352012-07-27 23:57:19 +00005523 if (!thread)
5524 {
5525 ts.Printf("<?> ");
5526 continue;
5527 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005528
Daniel Malead01b2952012-11-29 21:49:15 +00005529 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005530 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005531
Jim Inghamcfc09352012-07-27 23:57:19 +00005532 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005533 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005534 else
5535 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005536
Jim Inghamcfc09352012-07-27 23:57:19 +00005537 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5538 if (stop_info_sp)
5539 {
5540 const char *stop_desc = stop_info_sp->GetDescription();
5541 if (stop_desc)
5542 ts.PutCString (stop_desc);
5543 }
5544 ts.Printf(">");
5545 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005546
Jim Inghamcfc09352012-07-27 23:57:19 +00005547 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005548 }
Sean Callanana46ec452012-07-11 21:31:24 +00005549 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005550
Jim Inghamcfc09352012-07-27 23:57:19 +00005551 if (event_explanation)
5552 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005553 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005554 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5555 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005556
Jim Inghame4483cf2013-09-27 01:13:01 +00005557 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005558 {
5559 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005560 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5561 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005562 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5563 thread_plan_sp->SetPrivate (orig_plan_private);
5564 }
5565 else
5566 {
5567 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005568 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5569 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005570 }
5571 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005572 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005573 {
5574 if (log)
5575 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005576
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005577 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005578 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005579 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005580 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005581 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005582 }
5583 else
5584 {
Sean Callanana46ec452012-07-11 21:31:24 +00005585 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005586 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005587 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005588 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005589 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005590 }
5591 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5592 {
5593 if (log)
5594 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005595 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005596 }
5597 else
5598 {
5599 if (log)
5600 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005601 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005602 {
5603 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005604 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005605 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5606 thread_plan_sp->SetPrivate (orig_plan_private);
5607 }
5608 }
5609 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005610
Sean Callanana46ec452012-07-11 21:31:24 +00005611 // Thread we ran the function in may have gone away because we ran the target
5612 // Check that it's still there, and if it is put it back in the context. Also restore the
5613 // frame in the context if it is still present.
5614 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5615 if (thread)
5616 {
5617 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5618 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005619
Sean Callanana46ec452012-07-11 21:31:24 +00005620 // Also restore the current process'es selected frame & thread, since this function calling may
5621 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005622
Sean Callanana46ec452012-07-11 21:31:24 +00005623 if (selected_tid != LLDB_INVALID_THREAD_ID)
5624 {
5625 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5626 {
5627 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005628 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005629 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005630 if (old_frame_sp)
5631 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005632 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005633 }
5634 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005635
Sean Callanana46ec452012-07-11 21:31:24 +00005636 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005637
Sean Callanana46ec452012-07-11 21:31:24 +00005638 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005639 {
Sean Callanana46ec452012-07-11 21:31:24 +00005640 if (log)
5641 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5642 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005643 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005644
Jim Inghamf48169b2010-11-30 02:22:11 +00005645 return return_value;
5646}
5647
5648const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005649Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005650{
5651 const char *result_name;
5652
5653 switch (result)
5654 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005655 case eExpressionCompleted:
5656 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005657 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005658 case eExpressionDiscarded:
5659 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005660 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005661 case eExpressionInterrupted:
5662 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005663 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005664 case eExpressionHitBreakpoint:
5665 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005666 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005667 case eExpressionSetupError:
5668 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005669 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005670 case eExpressionParseError:
5671 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005672 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005673 case eExpressionResultUnavailable:
5674 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005675 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005676 case eExpressionTimedOut:
5677 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005678 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005679 case eExpressionStoppedForDebug:
5680 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005681 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005682 }
5683 return result_name;
5684}
5685
Greg Clayton7260f622011-04-18 08:33:37 +00005686void
5687Process::GetStatus (Stream &strm)
5688{
5689 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005690 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005691 {
5692 if (state == eStateExited)
5693 {
5694 int exit_status = GetExitStatus();
5695 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005696 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005697 GetID(),
5698 exit_status,
5699 exit_status,
5700 exit_description ? exit_description : "");
5701 }
5702 else
5703 {
5704 if (state == eStateConnected)
5705 strm.Printf ("Connected to remote target.\n");
5706 else
Daniel Malead01b2952012-11-29 21:49:15 +00005707 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005708 }
5709 }
5710 else
5711 {
Daniel Malead01b2952012-11-29 21:49:15 +00005712 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005713 }
5714}
5715
5716size_t
5717Process::GetThreadStatus (Stream &strm,
5718 bool only_threads_with_stop_reason,
5719 uint32_t start_frame,
5720 uint32_t num_frames,
5721 uint32_t num_frames_with_source)
5722{
5723 size_t num_thread_infos_dumped = 0;
5724
Jim Ingham4a65fb12014-03-07 11:20:03 +00005725 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5726 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5727 // ID's, and look them up one by one:
5728
5729 uint32_t num_threads;
5730 std::vector<uint32_t> thread_index_array;
5731 //Scope for thread list locker;
5732 {
5733 Mutex::Locker locker (GetThreadList().GetMutex());
5734 ThreadList &curr_thread_list = GetThreadList();
5735 num_threads = curr_thread_list.GetSize();
5736 uint32_t idx;
5737 thread_index_array.resize(num_threads);
5738 for (idx = 0; idx < num_threads; ++idx)
5739 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5740 }
5741
Greg Clayton7260f622011-04-18 08:33:37 +00005742 for (uint32_t i = 0; i < num_threads; i++)
5743 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005744 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5745 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005746 {
5747 if (only_threads_with_stop_reason)
5748 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005749 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005750 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005751 continue;
5752 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005753 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005754 start_frame,
5755 num_frames,
5756 num_frames_with_source);
5757 ++num_thread_infos_dumped;
5758 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005759 else
5760 {
5761 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5762 if (log)
5763 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5764
5765 }
Greg Clayton7260f622011-04-18 08:33:37 +00005766 }
5767 return num_thread_infos_dumped;
5768}
5769
Greg Claytona9f40ad2012-02-22 04:37:26 +00005770void
5771Process::AddInvalidMemoryRegion (const LoadRange &region)
5772{
5773 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5774}
5775
5776bool
5777Process::RemoveInvalidMemoryRange (const LoadRange &region)
5778{
5779 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5780}
5781
Jim Ingham372787f2012-04-07 00:00:41 +00005782void
5783Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5784{
5785 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5786}
5787
5788bool
5789Process::RunPreResumeActions ()
5790{
5791 bool result = true;
5792 while (!m_pre_resume_actions.empty())
5793 {
5794 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5795 m_pre_resume_actions.pop_back();
5796 bool this_result = action.callback (action.baton);
5797 if (result == true) result = this_result;
5798 }
5799 return result;
5800}
5801
5802void
5803Process::ClearPreResumeActions ()
5804{
5805 m_pre_resume_actions.clear();
5806}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005807
Greg Claytonfa559e52012-05-18 02:38:05 +00005808void
5809Process::Flush ()
5810{
5811 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005812 m_extended_thread_list.Flush();
5813 m_extended_thread_stop_id = 0;
5814 m_queue_list.Clear();
5815 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005816}
Greg Clayton90ba8112012-12-05 00:16:59 +00005817
5818void
5819Process::DidExec ()
5820{
5821 Target &target = GetTarget();
5822 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005823 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005824 m_dynamic_checkers_ap.reset();
5825 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005826 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005827 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005828 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005829 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005830 m_image_tokens.clear();
5831 m_allocated_memory_cache.Clear();
5832 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005833 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005834 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005835 DoDidExec();
5836 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005837 // Flush the process (threads and all stack frames) after running CompleteAttach()
5838 // in case the dynamic loader loaded things in new locations.
5839 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005840
5841 // After we figure out what was loaded/unloaded in CompleteAttach,
5842 // we need to let the target know so it can do any cleanup it needs to.
5843 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005844}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005845
Jim Ingham1460e4b2014-01-10 23:46:59 +00005846addr_t
5847Process::ResolveIndirectFunction(const Address *address, Error &error)
5848{
5849 if (address == nullptr)
5850 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005851 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005852 return LLDB_INVALID_ADDRESS;
5853 }
5854
5855 addr_t function_addr = LLDB_INVALID_ADDRESS;
5856
5857 addr_t addr = address->GetLoadAddress(&GetTarget());
5858 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5859 if (iter != m_resolved_indirect_addresses.end())
5860 {
5861 function_addr = (*iter).second;
5862 }
5863 else
5864 {
5865 if (!InferiorCall(this, address, function_addr))
5866 {
5867 Symbol *symbol = address->CalculateSymbolContextSymbol();
5868 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5869 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5870 function_addr = LLDB_INVALID_ADDRESS;
5871 }
5872 else
5873 {
5874 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5875 }
5876 }
5877 return function_addr;
5878}
5879
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005880void
5881Process::ModulesDidLoad (ModuleList &module_list)
5882{
5883 SystemRuntime *sys_runtime = GetSystemRuntime();
5884 if (sys_runtime)
5885 {
5886 sys_runtime->ModulesDidLoad (module_list);
5887 }
5888
5889 GetJITLoaders().ModulesDidLoad (module_list);
5890}