blob: 95785a93ec27ef944a7ece223d04f6dae505c569 [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
50using namespace lldb;
51using namespace lldb_private;
52
Greg Clayton67cc0632012-08-22 17:17:09 +000053
54// Comment out line below to disable memory caching, overriding the process setting
55// target.process.disable-memory-cache
56#define ENABLE_MEMORY_CACHING
57
58#ifdef ENABLE_MEMORY_CACHING
59#define DISABLE_MEM_CACHE_DEFAULT false
60#else
61#define DISABLE_MEM_CACHE_DEFAULT true
62#endif
63
64class ProcessOptionValueProperties : public OptionValueProperties
65{
66public:
67 ProcessOptionValueProperties (const ConstString &name) :
68 OptionValueProperties (name)
69 {
70 }
71
72 // This constructor is used when creating ProcessOptionValueProperties when it
73 // is part of a new lldb_private::Process instance. It will copy all current
74 // global property values as needed
75 ProcessOptionValueProperties (ProcessProperties *global_properties) :
76 OptionValueProperties(*global_properties->GetValueProperties())
77 {
78 }
79
80 virtual const Property *
81 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
82 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000083 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000084 // try and grab the setting from the current process if there is one. Else we just
85 // use the one from this instance.
86 if (exe_ctx)
87 {
88 Process *process = exe_ctx->GetProcessPtr();
89 if (process)
90 {
91 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
92 if (this != instance_properties)
93 return instance_properties->ProtectedGetPropertyAtIndex (idx);
94 }
95 }
96 return ProtectedGetPropertyAtIndex (idx);
97 }
98};
99
100static PropertyDefinition
101g_properties[] =
102{
103 { "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 +0000104 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
105 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000106 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
107 { "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 +0000108 { "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 +0000109 { "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 +0000110 { "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 +0000111 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
112};
113
114enum {
115 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000116 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000117 ePropertyIgnoreBreakpointsInExpressions,
118 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000119 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000120 ePropertyStopOnSharedLibraryEvents,
121 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000122};
123
124ProcessProperties::ProcessProperties (bool is_global) :
125 Properties ()
126{
127 if (is_global)
128 {
129 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
130 m_collection_sp->Initialize(g_properties);
131 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000132 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000133 true,
134 Thread::GetGlobalProperties()->GetValueProperties());
135 }
136 else
137 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
138}
139
140ProcessProperties::~ProcessProperties()
141{
142}
143
144bool
145ProcessProperties::GetDisableMemoryCache() const
146{
147 const uint32_t idx = ePropertyDisableMemCache;
148 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
149}
150
151Args
152ProcessProperties::GetExtraStartupCommands () const
153{
154 Args args;
155 const uint32_t idx = ePropertyExtraStartCommand;
156 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
157 return args;
158}
159
160void
161ProcessProperties::SetExtraStartupCommands (const Args &args)
162{
163 const uint32_t idx = ePropertyExtraStartCommand;
164 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
165}
166
Greg Claytonc9d645d2012-10-18 22:40:37 +0000167FileSpec
168ProcessProperties::GetPythonOSPluginPath () const
169{
170 const uint32_t idx = ePropertyPythonOSPluginPath;
171 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
172}
173
174void
175ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
176{
177 const uint32_t idx = ePropertyPythonOSPluginPath;
178 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
179}
180
Jim Ingham184e9812013-01-15 02:47:48 +0000181
182bool
183ProcessProperties::GetIgnoreBreakpointsInExpressions () const
184{
185 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
186 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
187}
188
189void
190ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
191{
192 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
193 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
194}
195
196bool
197ProcessProperties::GetUnwindOnErrorInExpressions () const
198{
199 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
200 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
201}
202
203void
204ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
205{
206 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
207 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
208}
209
Jim Ingham29950772013-01-26 02:19:28 +0000210bool
211ProcessProperties::GetStopOnSharedLibraryEvents () const
212{
213 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
214 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
215}
216
217void
218ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
219{
220 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
221 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
222}
223
Jim Inghamacff8952013-05-02 00:27:30 +0000224bool
225ProcessProperties::GetDetachKeepsStopped () const
226{
227 const uint32_t idx = ePropertyDetachKeepsStopped;
228 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
229}
230
231void
232ProcessProperties::SetDetachKeepsStopped (bool stop)
233{
234 const uint32_t idx = ePropertyDetachKeepsStopped;
235 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
236}
237
Greg Clayton32e0a752011-03-30 18:16:51 +0000238void
Greg Clayton8b82f082011-04-12 05:54:46 +0000239ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000240{
241 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000242 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000243 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000244
245 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000246 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000247
248 if (m_executable)
249 {
250 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
251 s.PutCString (" file = ");
252 m_executable.Dump(&s);
253 s.EOL();
254 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000255 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000256 if (argc > 0)
257 {
258 for (uint32_t i=0; i<argc; i++)
259 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000260 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000261 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000262 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000263 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000264 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000265 }
266 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000267
268 const uint32_t envc = m_environment.GetArgumentCount();
269 if (envc > 0)
270 {
271 for (uint32_t i=0; i<envc; i++)
272 {
273 const char *env = m_environment.GetArgumentAtIndex(i);
274 if (i < 10)
275 s.Printf (" env[%u] = %s\n", i, env);
276 else
277 s.Printf ("env[%u] = %s\n", i, env);
278 }
279 }
280
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000281 if (m_arch.IsValid())
282 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
283
Greg Clayton8b82f082011-04-12 05:54:46 +0000284 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000285 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000286 cstr = platform->GetUserName (m_uid);
287 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000288 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000289 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000290 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000291 cstr = platform->GetGroupName (m_gid);
292 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000293 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000294 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000295 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000296 cstr = platform->GetUserName (m_euid);
297 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000298 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000300 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000301 cstr = platform->GetGroupName (m_egid);
302 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000303 }
304}
305
306void
Greg Clayton8b82f082011-04-12 05:54:46 +0000307ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000308{
Greg Clayton8b82f082011-04-12 05:54:46 +0000309 const char *label;
310 if (show_args || verbose)
311 label = "ARGUMENTS";
312 else
313 label = "NAME";
314
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000315 if (verbose)
316 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000317 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000318 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
319 }
320 else
321 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000322 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000323 s.PutCString ("====== ====== ========== ======= ============================\n");
324 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000325}
326
327void
Greg Clayton8b82f082011-04-12 05:54:46 +0000328ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000329{
330 if (m_pid != LLDB_INVALID_PROCESS_ID)
331 {
332 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000333 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000334
Greg Clayton32e0a752011-03-30 18:16:51 +0000335
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000336 if (verbose)
337 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000338 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000339 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
340 s.Printf ("%-10s ", cstr);
341 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000343
Greg Clayton8b82f082011-04-12 05:54:46 +0000344 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000345 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
346 s.Printf ("%-10s ", cstr);
347 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000348 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000349
Greg Clayton8b82f082011-04-12 05:54:46 +0000350 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000351 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
352 s.Printf ("%-10s ", cstr);
353 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000354 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000355
Greg Clayton8b82f082011-04-12 05:54:46 +0000356 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000357 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
358 s.Printf ("%-10s ", cstr);
359 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000360 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
362 }
363 else
364 {
Jason Molendafd54b362011-09-20 21:44:10 +0000365 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000366 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000367 (int)m_arch.GetTriple().getArchName().size(),
368 m_arch.GetTriple().getArchName().data());
369 }
370
Greg Clayton8b82f082011-04-12 05:54:46 +0000371 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000372 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000373 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000374 if (argc > 0)
375 {
376 for (uint32_t i=0; i<argc; i++)
377 {
378 if (i > 0)
379 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000380 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000381 }
382 }
383 }
384 else
385 {
386 s.PutCString (GetName());
387 }
388
389 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000390 }
391}
392
Greg Clayton8b82f082011-04-12 05:54:46 +0000393Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000394ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000395{
396 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000397 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000398
399 switch (short_option)
400 {
401 case 's': // Stop at program entry point
402 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
403 break;
404
Greg Clayton8b82f082011-04-12 05:54:46 +0000405 case 'i': // STDIN for read only
406 {
Zachary Turner696b5282014-08-14 16:01:25 +0000407 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000408 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 launch_info.AppendFileAction (action);
410 }
411 break;
412
413 case 'o': // Open STDOUT for write only
414 {
Zachary Turner696b5282014-08-14 16:01:25 +0000415 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000416 if (action.Open (STDOUT_FILENO, option_arg, false, true))
417 launch_info.AppendFileAction (action);
418 }
419 break;
420
421 case 'e': // STDERR for write only
422 {
Zachary Turner696b5282014-08-14 16:01:25 +0000423 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000424 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000425 launch_info.AppendFileAction (action);
426 }
427 break;
428
Greg Clayton9845a8d2012-03-06 04:01:04 +0000429
Greg Clayton8b82f082011-04-12 05:54:46 +0000430 case 'p': // Process plug-in name
431 launch_info.SetProcessPluginName (option_arg);
432 break;
433
434 case 'n': // Disable STDIO
435 {
Zachary Turner696b5282014-08-14 16:01:25 +0000436 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000437 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000438 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000439 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000440 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000441 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000442 launch_info.AppendFileAction (action);
443 }
444 break;
445
446 case 'w':
447 launch_info.SetWorkingDirectory (option_arg);
448 break;
449
450 case 't': // Open process in new terminal window
451 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
452 break;
453
454 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000455 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
456 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000457 break;
458
459 case 'A':
460 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
461 break;
462
Greg Clayton982c9762011-11-03 21:22:33 +0000463 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000464 if (option_arg && option_arg[0])
465 launch_info.SetShell (option_arg);
466 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000467 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000468 break;
469
Greg Clayton8b82f082011-04-12 05:54:46 +0000470 case 'v':
471 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
472 break;
473
474 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000475 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000476 break;
477
478 }
479 return error;
480}
481
482OptionDefinition
483ProcessLaunchCommandOptions::g_option_table[] =
484{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000485{ 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."},
486{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
487{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
488{ 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."},
489{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
490{ 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."},
491{ 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 +0000492
Zachary Turnerd37221d2014-07-09 16:31:49 +0000493{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
494{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
495{ 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 +0000496
Zachary Turnerd37221d2014-07-09 16:31:49 +0000497{ 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 +0000498
Zachary Turnerd37221d2014-07-09 16:31:49 +0000499{ 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 +0000500
Zachary Turnerd37221d2014-07-09 16:31:49 +0000501{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000502};
503
504
505
506bool
507ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000508{
509 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
510 return true;
511 const char *match_name = m_match_info.GetName();
512 if (!match_name)
513 return true;
514
515 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
516}
517
518bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000519ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000520{
521 if (!NameMatches (proc_info.GetName()))
522 return false;
523
524 if (m_match_info.ProcessIDIsValid() &&
525 m_match_info.GetProcessID() != proc_info.GetProcessID())
526 return false;
527
528 if (m_match_info.ParentProcessIDIsValid() &&
529 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
530 return false;
531
Greg Clayton8b82f082011-04-12 05:54:46 +0000532 if (m_match_info.UserIDIsValid () &&
533 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000534 return false;
535
Greg Clayton8b82f082011-04-12 05:54:46 +0000536 if (m_match_info.GroupIDIsValid () &&
537 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000538 return false;
539
540 if (m_match_info.EffectiveUserIDIsValid () &&
541 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
542 return false;
543
544 if (m_match_info.EffectiveGroupIDIsValid () &&
545 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
546 return false;
547
548 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000549 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000550 return false;
551 return true;
552}
553
554bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000555ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000556{
557 if (m_name_match_type != eNameMatchIgnore)
558 return false;
559
560 if (m_match_info.ProcessIDIsValid())
561 return false;
562
563 if (m_match_info.ParentProcessIDIsValid())
564 return false;
565
Greg Clayton8b82f082011-04-12 05:54:46 +0000566 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000567 return false;
568
Greg Clayton8b82f082011-04-12 05:54:46 +0000569 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000570 return false;
571
572 if (m_match_info.EffectiveUserIDIsValid ())
573 return false;
574
575 if (m_match_info.EffectiveGroupIDIsValid ())
576 return false;
577
578 if (m_match_info.GetArchitecture().IsValid())
579 return false;
580
581 if (m_match_all_users)
582 return false;
583
584 return true;
585
586}
587
588void
Greg Clayton8b82f082011-04-12 05:54:46 +0000589ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000590{
591 m_match_info.Clear();
592 m_name_match_type = eNameMatchIgnore;
593 m_match_all_users = false;
594}
Greg Clayton58be07b2011-01-07 06:08:19 +0000595
Greg Claytonc3776bf2012-02-09 06:16:32 +0000596ProcessSP
597Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000598{
Greg Clayton949e8222013-01-16 17:29:04 +0000599 static uint32_t g_process_unique_id = 0;
600
Greg Claytonc3776bf2012-02-09 06:16:32 +0000601 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602 ProcessCreateInstance create_callback = NULL;
603 if (plugin_name)
604 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000605 ConstString const_plugin_name(plugin_name);
606 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000607 if (create_callback)
608 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000609 process_sp = create_callback(target, listener, crash_file_path);
610 if (process_sp)
611 {
Greg Clayton949e8222013-01-16 17:29:04 +0000612 if (process_sp->CanDebug(target, true))
613 {
614 process_sp->m_process_unique_id = ++g_process_unique_id;
615 }
616 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000617 process_sp.reset();
618 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000619 }
620 }
621 else
622 {
Greg Claytonc982c762010-07-09 20:39:50 +0000623 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000624 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000625 process_sp = create_callback(target, listener, crash_file_path);
626 if (process_sp)
627 {
Greg Clayton949e8222013-01-16 17:29:04 +0000628 if (process_sp->CanDebug(target, false))
629 {
630 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000631 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000632 }
633 else
634 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000635 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636 }
637 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000638 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639}
640
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000641ConstString &
642Process::GetStaticBroadcasterClass ()
643{
644 static ConstString class_name ("lldb.process");
645 return class_name;
646}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647
648//----------------------------------------------------------------------
649// Process constructor
650//----------------------------------------------------------------------
651Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000652 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000654 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656 m_public_state (eStateUnloaded),
657 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000658 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
659 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 m_private_state_listener ("lldb.process.internal_state_listener"),
661 m_private_state_control_wait(),
662 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000663 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000664 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000666 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000667 m_exit_status (-1),
668 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000669 m_thread_mutex (Mutex::eMutexTypeRecursive),
670 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000672 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000673 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000674 m_queue_list (this),
675 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000676 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000677 m_image_tokens (),
678 m_listener (listener),
679 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000680 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000681 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000682 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000683 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000684 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000685 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000686 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000687 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000688 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
689 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000690 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000691 m_memory_cache (*this),
692 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000693 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000694 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000695 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000696 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000697 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000698 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000699 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000700 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000701 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000702 m_destroy_in_process (false),
703 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000705 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000706
Greg Clayton5160ce52013-03-27 23:08:40 +0000707 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000709 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000711 SetEventName (eBroadcastBitStateChanged, "state-changed");
712 SetEventName (eBroadcastBitInterrupt, "interrupt");
713 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
714 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000715 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000716
Greg Clayton35a4cc52012-10-29 20:52:08 +0000717 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
718 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
719 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
720
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721 listener.StartListeningForEvents (this,
722 eBroadcastBitStateChanged |
723 eBroadcastBitInterrupt |
724 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000725 eBroadcastBitSTDERR |
726 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727
728 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000729 eBroadcastBitStateChanged |
730 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731
732 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
733 eBroadcastInternalStateControlStop |
734 eBroadcastInternalStateControlPause |
735 eBroadcastInternalStateControlResume);
736}
737
738//----------------------------------------------------------------------
739// Destructor
740//----------------------------------------------------------------------
741Process::~Process()
742{
Greg Clayton5160ce52013-03-27 23:08:40 +0000743 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000744 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000745 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 StopPrivateStateThread();
747}
748
Greg Clayton67cc0632012-08-22 17:17:09 +0000749const ProcessPropertiesSP &
750Process::GetGlobalProperties()
751{
752 static ProcessPropertiesSP g_settings_sp;
753 if (!g_settings_sp)
754 g_settings_sp.reset (new ProcessProperties (true));
755 return g_settings_sp;
756}
757
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758void
759Process::Finalize()
760{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000761 switch (GetPrivateState())
762 {
763 case eStateConnected:
764 case eStateAttaching:
765 case eStateLaunching:
766 case eStateStopped:
767 case eStateRunning:
768 case eStateStepping:
769 case eStateCrashed:
770 case eStateSuspended:
771 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000772 {
773 // FIXME: This will have to be a process setting:
774 bool keep_stopped = false;
775 Detach(keep_stopped);
776 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000777 else
778 Destroy();
779 break;
780
781 case eStateInvalid:
782 case eStateUnloaded:
783 case eStateDetached:
784 case eStateExited:
785 break;
786 }
787
Greg Clayton1ed54f52011-10-01 00:45:15 +0000788 // Clear our broadcaster before we proceed with destroying
789 Broadcaster::Clear();
790
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791 // Do any cleanup needed prior to being destructed... Subclasses
792 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000793
794 // We need to destroy the loader before the derived Process class gets destroyed
795 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000796 m_dynamic_checkers_ap.reset();
797 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000798 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000799 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000800 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000801 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000802 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000803 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000804 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000805 m_queue_list.Clear();
806 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000807 std::vector<Notifications> empty_notifications;
808 m_notifications.swap(empty_notifications);
809 m_image_tokens.clear();
810 m_memory_cache.Clear();
811 m_allocated_memory_cache.Clear();
812 m_language_runtimes.clear();
813 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000814//#ifdef LLDB_CONFIGURATION_DEBUG
815// StreamFile s(stdout, false);
816// EventSP event_sp;
817// while (m_private_state_listener.GetNextEvent(event_sp))
818// {
819// event_sp->Dump (&s);
820// s.EOL();
821// }
822//#endif
823 // We have to be very careful here as the m_private_state_listener might
824 // contain events that have ProcessSP values in them which can keep this
825 // process around forever. These events need to be cleared out.
826 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000827 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
828 m_public_run_lock.SetStopped();
829 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
830 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000831 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832}
833
834void
835Process::RegisterNotificationCallbacks (const Notifications& callbacks)
836{
837 m_notifications.push_back(callbacks);
838 if (callbacks.initialize != NULL)
839 callbacks.initialize (callbacks.baton, this);
840}
841
842bool
843Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
844{
845 std::vector<Notifications>::iterator pos, end = m_notifications.end();
846 for (pos = m_notifications.begin(); pos != end; ++pos)
847 {
848 if (pos->baton == callbacks.baton &&
849 pos->initialize == callbacks.initialize &&
850 pos->process_state_changed == callbacks.process_state_changed)
851 {
852 m_notifications.erase(pos);
853 return true;
854 }
855 }
856 return false;
857}
858
859void
860Process::SynchronouslyNotifyStateChanged (StateType state)
861{
862 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
863 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
864 {
865 if (notification_pos->process_state_changed)
866 notification_pos->process_state_changed (notification_pos->baton, this, state);
867 }
868}
869
870// FIXME: We need to do some work on events before the general Listener sees them.
871// For instance if we are continuing from a breakpoint, we need to ensure that we do
872// the little "insert real insn, step & stop" trick. But we can't do that when the
873// event is delivered by the broadcaster - since that is done on the thread that is
874// waiting for new events, so if we needed more than one event for our handling, we would
875// stall. So instead we do it when we fetch the event off of the queue.
876//
877
878StateType
879Process::GetNextEvent (EventSP &event_sp)
880{
881 StateType state = eStateInvalid;
882
883 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
884 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
885
886 return state;
887}
888
Todd Fialaa3b89e22014-08-12 14:33:19 +0000889bool
890Process::SyncIOHandler (uint64_t timeout_msec)
891{
892 bool timed_out = false;
893
894 // don't sync (potentially context switch) in case where there is no process IO
895 if (m_process_input_reader)
896 {
897 TimeValue timeout = TimeValue::Now();
898 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
899
900 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
901
902 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
903 if(log)
904 {
905 if(timed_out)
906 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
907 else
908 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
909 }
910
911 // reset sync one-shot so it will be ready for next time
912 m_iohandler_sync.SetValue(false, eBroadcastNever);
913 }
914
915 return !timed_out;
916}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000917
918StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000919Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000920{
Jim Ingham4b536182011-08-09 02:12:22 +0000921 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
922 // We have to actually check each event, and in the case of a stopped event check the restarted flag
923 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000924 if (event_sp_ptr)
925 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000926 StateType state = GetState();
927 // If we are exited or detached, we won't ever get back to any
928 // other valid state...
929 if (state == eStateDetached || state == eStateExited)
930 return state;
931
Daniel Malea9e9919f2013-10-09 16:56:28 +0000932 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
933 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000934 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
935 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000936
937 if (!wait_always &&
938 StateIsStoppedState(state, true) &&
939 StateIsStoppedState(GetPrivateState(), true)) {
940 if (log)
941 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
942 __FUNCTION__);
943 return state;
944 }
945
Jim Ingham4b536182011-08-09 02:12:22 +0000946 while (state != eStateInvalid)
947 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000948 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000949 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000950 if (event_sp_ptr && event_sp)
951 *event_sp_ptr = event_sp;
952
Jim Ingham4b536182011-08-09 02:12:22 +0000953 switch (state)
954 {
955 case eStateCrashed:
956 case eStateDetached:
957 case eStateExited:
958 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000959 // We need to toggle the run lock as this won't get done in
960 // SetPublicState() if the process is hijacked.
961 if (hijack_listener)
962 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000963 return state;
964 case eStateStopped:
965 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
966 continue;
967 else
Greg Clayton44d93782014-01-27 23:43:24 +0000968 {
969 // We need to toggle the run lock as this won't get done in
970 // SetPublicState() if the process is hijacked.
971 if (hijack_listener)
972 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000973 return state;
Greg Clayton44d93782014-01-27 23:43:24 +0000974 }
Jim Ingham4b536182011-08-09 02:12:22 +0000975 default:
976 continue;
977 }
978 }
979 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980}
981
982
983StateType
984Process::WaitForState
985(
986 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +0000987 const StateType *match_states,
988 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989)
990{
991 EventSP event_sp;
992 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000993 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994 while (state != eStateInvalid)
995 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000996 // If we are exited or detached, we won't ever get back to any
997 // other valid state...
998 if (state == eStateDetached || state == eStateExited)
999 return state;
1000
Greg Clayton44d93782014-01-27 23:43:24 +00001001 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002
1003 for (i=0; i<num_match_states; ++i)
1004 {
1005 if (match_states[i] == state)
1006 return state;
1007 }
1008 }
1009 return state;
1010}
1011
Jim Ingham30f9b212010-10-11 23:53:14 +00001012bool
1013Process::HijackProcessEvents (Listener *listener)
1014{
1015 if (listener != NULL)
1016 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001017 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001018 }
1019 else
1020 return false;
1021}
1022
1023void
1024Process::RestoreProcessEvents ()
1025{
1026 RestoreBroadcaster();
1027}
1028
Jim Ingham0f16e732011-02-08 05:20:59 +00001029bool
1030Process::HijackPrivateProcessEvents (Listener *listener)
1031{
1032 if (listener != NULL)
1033 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001034 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001035 }
1036 else
1037 return false;
1038}
1039
1040void
1041Process::RestorePrivateProcessEvents ()
1042{
1043 m_private_state_broadcaster.RestoreBroadcaster();
1044}
1045
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001047Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048{
Greg Clayton5160ce52013-03-27 23:08:40 +00001049 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050
1051 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001052 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1053 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054
Greg Clayton44d93782014-01-27 23:43:24 +00001055 Listener *listener = hijack_listener;
1056 if (listener == NULL)
1057 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001059 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001060 if (listener->WaitForEventForBroadcasterWithType (timeout,
1061 this,
1062 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1063 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001064 {
1065 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1066 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1067 else if (log)
1068 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1069 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070
1071 if (log)
1072 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001073 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074 StateAsCString(state));
1075 return state;
1076}
1077
1078Event *
1079Process::PeekAtStateChangedEvents ()
1080{
Greg Clayton5160ce52013-03-27 23:08:40 +00001081 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082
1083 if (log)
1084 log->Printf ("Process::%s...", __FUNCTION__);
1085
1086 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001087 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1088 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 if (log)
1090 {
1091 if (event_ptr)
1092 {
1093 log->Printf ("Process::%s (event_ptr) => %s",
1094 __FUNCTION__,
1095 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1096 }
1097 else
1098 {
1099 log->Printf ("Process::%s no events found",
1100 __FUNCTION__);
1101 }
1102 }
1103 return event_ptr;
1104}
1105
1106StateType
1107Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1108{
Greg Clayton5160ce52013-03-27 23:08:40 +00001109 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110
1111 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001112 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1113 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114
1115 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001116 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1117 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001118 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001119 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001120 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1121 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122
1123 // This is a bit of a hack, but when we wait here we could very well return
1124 // to the command-line, and that could disable the log, which would render the
1125 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001127 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1128 __FUNCTION__, static_cast<const void *>(timeout),
1129 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001130 return state;
1131}
1132
1133bool
1134Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1135{
Greg Clayton5160ce52013-03-27 23:08:40 +00001136 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137
1138 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001139 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1140 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141
1142 if (control_only)
1143 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1144 else
1145 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1146}
1147
1148bool
1149Process::IsRunning () const
1150{
1151 return StateIsRunningState (m_public_state.GetValue());
1152}
1153
1154int
1155Process::GetExitStatus ()
1156{
1157 if (m_public_state.GetValue() == eStateExited)
1158 return m_exit_status;
1159 return -1;
1160}
1161
Greg Clayton85851dd2010-12-04 00:10:17 +00001162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163const char *
1164Process::GetExitDescription ()
1165{
1166 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1167 return m_exit_string.c_str();
1168 return NULL;
1169}
1170
Greg Clayton6779606a2011-01-22 23:43:18 +00001171bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172Process::SetExitStatus (int status, const char *cstr)
1173{
Greg Clayton5160ce52013-03-27 23:08:40 +00001174 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001175 if (log)
1176 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1177 status, status,
1178 cstr ? "\"" : "",
1179 cstr ? cstr : "NULL",
1180 cstr ? "\"" : "");
1181
Greg Clayton6779606a2011-01-22 23:43:18 +00001182 // We were already in the exited state
1183 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001184 {
Greg Clayton385d6032011-01-26 23:47:29 +00001185 if (log)
1186 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001187 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001188 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001189
1190 m_exit_status = status;
1191 if (cstr)
1192 m_exit_string = cstr;
1193 else
1194 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195
Greg Clayton6779606a2011-01-22 23:43:18 +00001196 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001197
Greg Clayton6779606a2011-01-22 23:43:18 +00001198 SetPrivateState (eStateExited);
1199 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200}
1201
1202// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001203// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204// found in the global target list (we want to be completely sure that the
1205// lldb_private::Process doesn't go away before we can deliver the signal.
1206bool
Greg Claytone4e45922011-11-16 05:37:56 +00001207Process::SetProcessExitStatus (void *callback_baton,
1208 lldb::pid_t pid,
1209 bool exited,
1210 int signo, // Zero for no signal
1211 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212)
1213{
Greg Clayton5160ce52013-03-27 23:08:40 +00001214 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001215 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001216 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001217 callback_baton,
1218 pid,
1219 exited,
1220 signo,
1221 exit_status);
1222
1223 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001224 {
Greg Clayton66111032010-06-23 01:19:29 +00001225 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001226 if (target_sp)
1227 {
1228 ProcessSP process_sp (target_sp->GetProcessSP());
1229 if (process_sp)
1230 {
1231 const char *signal_cstr = NULL;
1232 if (signo)
1233 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1234
1235 process_sp->SetExitStatus (exit_status, signal_cstr);
1236 }
1237 }
1238 return true;
1239 }
1240 return false;
1241}
1242
1243
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001244void
1245Process::UpdateThreadListIfNeeded ()
1246{
1247 const uint32_t stop_id = GetStopID();
1248 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1249 {
Greg Clayton2637f822011-11-17 01:23:07 +00001250 const StateType state = GetPrivateState();
1251 if (StateIsStoppedState (state, true))
1252 {
1253 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001254 // m_thread_list does have its own mutex, but we need to
1255 // hold onto the mutex between the call to UpdateThreadList(...)
1256 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001257 ThreadList &old_thread_list = m_thread_list;
1258 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001259 ThreadList new_thread_list(this);
1260 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001261 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001262 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001263 {
Jim Ingham09437922013-03-01 20:04:25 +00001264 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1265 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1266 // shutting us down, causing a deadlock.
1267 if (!m_destroy_in_process)
1268 {
1269 OperatingSystem *os = GetOperatingSystem ();
1270 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001271 {
1272 // Clear any old backing threads where memory threads might have been
1273 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001274 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001275 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001276 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001277
1278 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001279 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1280 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1281 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 +00001282 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001283 else
1284 {
1285 // No OS plug-in, the new thread list is the same as the real thread list
1286 new_thread_list = real_thread_list;
1287 }
Jim Ingham09437922013-03-01 20:04:25 +00001288 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001289
1290 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001291 m_thread_list.Update (new_thread_list);
1292 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001293
Jason Molenda4ff13262013-11-20 00:31:38 +00001294 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1295 {
1296 // Clear any extended threads that we may have accumulated previously
1297 m_extended_thread_list.Clear();
1298 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001299
1300 m_queue_list.Clear();
1301 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001302 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001303 }
Greg Clayton2637f822011-11-17 01:23:07 +00001304 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001305 }
1306}
1307
Jason Molenda5e8dce42013-12-13 00:29:16 +00001308void
1309Process::UpdateQueueListIfNeeded ()
1310{
1311 if (m_system_runtime_ap.get())
1312 {
1313 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1314 {
1315 const StateType state = GetPrivateState();
1316 if (StateIsStoppedState (state, true))
1317 {
1318 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1319 m_queue_list_stop_id = GetLastNaturalStopID();
1320 }
1321 }
1322 }
1323}
1324
Greg Claytona4d87472013-01-18 23:41:08 +00001325ThreadSP
1326Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1327{
1328 OperatingSystem *os = GetOperatingSystem ();
1329 if (os)
1330 return os->CreateThread(tid, context);
1331 return ThreadSP();
1332}
1333
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001334uint32_t
1335Process::GetNextThreadIndexID (uint64_t thread_id)
1336{
1337 return AssignIndexIDToThread(thread_id);
1338}
1339
1340bool
1341Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1342{
1343 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1344 if (iterator == m_thread_id_to_index_id_map.end())
1345 {
1346 return false;
1347 }
1348 else
1349 {
1350 return true;
1351 }
1352}
1353
1354uint32_t
1355Process::AssignIndexIDToThread(uint64_t thread_id)
1356{
1357 uint32_t result = 0;
1358 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1359 if (iterator == m_thread_id_to_index_id_map.end())
1360 {
1361 result = ++m_thread_index_id;
1362 m_thread_id_to_index_id_map[thread_id] = result;
1363 }
1364 else
1365 {
1366 result = iterator->second;
1367 }
1368
1369 return result;
1370}
1371
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372StateType
1373Process::GetState()
1374{
1375 // If any other threads access this we will need a mutex for it
1376 return m_public_state.GetValue ();
1377}
1378
1379void
Jim Ingham221d51c2013-05-08 00:35:16 +00001380Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381{
Greg Clayton5160ce52013-03-27 23:08:40 +00001382 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001384 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001385 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001386 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001387
1388 // On the transition from Run to Stopped, we unlock the writer end of the
1389 // run lock. The lock gets locked in Resume, which is the public API
1390 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001391 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1392 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001393 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001394 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001395 if (log)
1396 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001397 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001398 }
1399 else
1400 {
1401 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1402 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001403 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001404 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001405 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001406 {
1407 if (log)
1408 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001409 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001410 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001411 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001412 }
1413 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414}
1415
Jim Ingham3b8285d2012-04-19 01:40:33 +00001416Error
1417Process::Resume ()
1418{
Greg Clayton5160ce52013-03-27 23:08:40 +00001419 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001420 if (log)
1421 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001422 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001423 {
1424 Error error("Resume request failed - process still running.");
1425 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001426 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001427 return error;
1428 }
1429 return PrivateResume();
1430}
1431
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001432StateType
1433Process::GetPrivateState ()
1434{
1435 return m_private_state.GetValue();
1436}
1437
1438void
1439Process::SetPrivateState (StateType new_state)
1440{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001441 if (m_finalize_called)
1442 return;
1443
Greg Clayton5160ce52013-03-27 23:08:40 +00001444 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001445 bool state_changed = false;
1446
1447 if (log)
1448 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1449
Andrew Kaylor29d65742013-05-10 17:19:04 +00001450 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001451 Mutex::Locker locker(m_private_state.GetMutex());
1452
1453 const StateType old_state = m_private_state.GetValueNoLock ();
1454 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001455
Greg Claytonaa49c832013-05-03 22:25:56 +00001456 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1457 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1458 if (old_state_is_stopped != new_state_is_stopped)
1459 {
1460 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001461 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001462 else
Ed Maste64fad602013-07-29 20:58:06 +00001463 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001464 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001465
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001466 if (state_changed)
1467 {
1468 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001469 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001471 // Note, this currently assumes that all threads in the list
1472 // stop when the process stops. In the future we will want to
1473 // support a debugging model where some threads continue to run
1474 // while others are stopped. When that happens we will either need
1475 // a way for the thread list to identify which threads are stopping
1476 // or create a special thread list containing only threads which
1477 // actually stopped.
1478 //
1479 // The process plugin is responsible for managing the actual
1480 // behavior of the threads and should have stopped any threads
1481 // that are going to stop before we get here.
1482 m_thread_list.DidStop();
1483
Jim Ingham4b536182011-08-09 02:12:22 +00001484 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001485 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001487 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001488 }
1489 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001490 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1491 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1492 else
1493 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001494 }
1495 else
1496 {
1497 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001498 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499 }
1500}
1501
Jim Ingham0faa43f2011-11-08 03:00:11 +00001502void
1503Process::SetRunningUserExpression (bool on)
1504{
1505 m_mod_id.SetRunningUserExpression (on);
1506}
1507
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508addr_t
1509Process::GetImageInfoAddress()
1510{
1511 return LLDB_INVALID_ADDRESS;
1512}
1513
Greg Clayton8f343b02010-11-04 01:54:29 +00001514//----------------------------------------------------------------------
1515// LoadImage
1516//
1517// This function provides a default implementation that works for most
1518// unix variants. Any Process subclasses that need to do shared library
1519// loading differently should override LoadImage and UnloadImage and
1520// do what is needed.
1521//----------------------------------------------------------------------
1522uint32_t
1523Process::LoadImage (const FileSpec &image_spec, Error &error)
1524{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001525 char path[PATH_MAX];
1526 image_spec.GetPath(path, sizeof(path));
1527
Greg Clayton8f343b02010-11-04 01:54:29 +00001528 DynamicLoader *loader = GetDynamicLoader();
1529 if (loader)
1530 {
1531 error = loader->CanLoadImage();
1532 if (error.Fail())
1533 return LLDB_INVALID_IMAGE_TOKEN;
1534 }
1535
1536 if (error.Success())
1537 {
1538 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001539
1540 if (thread_sp)
1541 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001542 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001543
1544 if (frame_sp)
1545 {
1546 ExecutionContext exe_ctx;
1547 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001548 EvaluateExpressionOptions expr_options;
1549 expr_options.SetUnwindOnError(true);
1550 expr_options.SetIgnoreBreakpoints(true);
1551 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001552 expr_options.SetResultIsInternal(true);
1553
Greg Clayton8f343b02010-11-04 01:54:29 +00001554 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001555 expr.Printf(R"(
1556 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1557 the_result.image_ptr = dlopen ("%s", 2);
1558 if (the_result.image_ptr == (void *) 0x0)
1559 {
1560 the_result.error_str = dlerror();
1561 }
1562 else
1563 {
1564 the_result.error_str = (const char *) 0x0;
1565 }
1566 the_result;
1567 )",
1568 path);
1569 const char *prefix = R"(
1570 extern "C" void* dlopen (const char *path, int mode);
1571 extern "C" const char *dlerror (void);
1572 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001573 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001574 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001575 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001576 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001577 expr.GetData(),
1578 prefix,
1579 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001580 expr_error);
1581 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001582 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001583 error = result_valobj_sp->GetError();
1584 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001585 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001586 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001587 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1588 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001589 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001590 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1591 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1592 {
1593 uint32_t image_token = m_image_tokens.size();
1594 m_image_tokens.push_back (image_ptr);
1595 return image_token;
1596 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001597 else if (image_ptr == 0)
1598 {
Jim Ingham6971b862014-07-19 00:37:06 +00001599 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1600 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001601 {
Jim Ingham6971b862014-07-19 00:37:06 +00001602 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001603 {
Jim Inghamcf973792014-07-17 21:53:48 +00001604 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001605 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001606 if (error.Success() && num_chars > 0)
1607 {
1608 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001609 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001610 }
1611 }
1612 }
1613 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001614 }
1615 }
1616 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001617 else
1618 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001619 }
1620 }
1621 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001622 if (!error.AsCString())
1623 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001624 return LLDB_INVALID_IMAGE_TOKEN;
1625}
1626
1627//----------------------------------------------------------------------
1628// UnloadImage
1629//
1630// This function provides a default implementation that works for most
1631// unix variants. Any Process subclasses that need to do shared library
1632// loading differently should override LoadImage and UnloadImage and
1633// do what is needed.
1634//----------------------------------------------------------------------
1635Error
1636Process::UnloadImage (uint32_t image_token)
1637{
1638 Error error;
1639 if (image_token < m_image_tokens.size())
1640 {
1641 const addr_t image_addr = m_image_tokens[image_token];
1642 if (image_addr == LLDB_INVALID_ADDRESS)
1643 {
1644 error.SetErrorString("image already unloaded");
1645 }
1646 else
1647 {
1648 DynamicLoader *loader = GetDynamicLoader();
1649 if (loader)
1650 error = loader->CanLoadImage();
1651
1652 if (error.Success())
1653 {
1654 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001655
1656 if (thread_sp)
1657 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001658 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001659
1660 if (frame_sp)
1661 {
1662 ExecutionContext exe_ctx;
1663 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001664 EvaluateExpressionOptions expr_options;
1665 expr_options.SetUnwindOnError(true);
1666 expr_options.SetIgnoreBreakpoints(true);
1667 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001668 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001669 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001670 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001671 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001672 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001673 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001674 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001675 expr.GetData(),
1676 prefix,
1677 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001678 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001679 if (result_valobj_sp->GetError().Success())
1680 {
1681 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001682 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001683 {
1684 if (scalar.UInt(1))
1685 {
1686 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1687 }
1688 else
1689 {
1690 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1691 }
1692 }
1693 }
1694 else
1695 {
1696 error = result_valobj_sp->GetError();
1697 }
1698 }
1699 }
1700 }
1701 }
1702 }
1703 else
1704 {
1705 error.SetErrorString("invalid image token");
1706 }
1707 return error;
1708}
1709
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001710const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001711Process::GetABI()
1712{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001713 if (!m_abi_sp)
1714 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1715 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001716}
1717
Jim Ingham22777012010-09-23 02:01:19 +00001718LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001719Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001720{
1721 LanguageRuntimeCollection::iterator pos;
1722 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001723 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001724 {
Jim Inghamab175242012-03-10 00:22:19 +00001725 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001726
Jim Inghamab175242012-03-10 00:22:19 +00001727 m_language_runtimes[language] = runtime_sp;
1728 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001729 }
1730 else
1731 return (*pos).second.get();
1732}
1733
1734CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001735Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001736{
Jim Inghamab175242012-03-10 00:22:19 +00001737 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001738 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1739 return static_cast<CPPLanguageRuntime *> (runtime);
1740 return NULL;
1741}
1742
1743ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001744Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001745{
Jim Inghamab175242012-03-10 00:22:19 +00001746 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001747 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1748 return static_cast<ObjCLanguageRuntime *> (runtime);
1749 return NULL;
1750}
1751
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001752bool
1753Process::IsPossibleDynamicValue (ValueObject& in_value)
1754{
1755 if (in_value.IsDynamic())
1756 return false;
1757 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1758
1759 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1760 {
1761 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1762 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1763 }
1764
1765 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1766 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1767 return true;
1768
1769 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1770 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1771}
1772
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001773BreakpointSiteList &
1774Process::GetBreakpointSiteList()
1775{
1776 return m_breakpoint_site_list;
1777}
1778
1779const BreakpointSiteList &
1780Process::GetBreakpointSiteList() const
1781{
1782 return m_breakpoint_site_list;
1783}
1784
1785
1786void
1787Process::DisableAllBreakpointSites ()
1788{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001789 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1790// bp_site->SetEnabled(true);
1791 DisableBreakpointSite(bp_site);
1792 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793}
1794
1795Error
1796Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1797{
1798 Error error (DisableBreakpointSiteByID (break_id));
1799
1800 if (error.Success())
1801 m_breakpoint_site_list.Remove(break_id);
1802
1803 return error;
1804}
1805
1806Error
1807Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1808{
1809 Error error;
1810 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1811 if (bp_site_sp)
1812 {
1813 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001814 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001815 }
1816 else
1817 {
Daniel Malead01b2952012-11-29 21:49:15 +00001818 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 }
1820
1821 return error;
1822}
1823
1824Error
1825Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1826{
1827 Error error;
1828 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1829 if (bp_site_sp)
1830 {
1831 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001832 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833 }
1834 else
1835 {
Daniel Malead01b2952012-11-29 21:49:15 +00001836 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 }
1838 return error;
1839}
1840
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001841lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001842Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001843{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001844 addr_t load_addr = LLDB_INVALID_ADDRESS;
1845
1846 bool show_error = true;
1847 switch (GetState())
1848 {
1849 case eStateInvalid:
1850 case eStateUnloaded:
1851 case eStateConnected:
1852 case eStateAttaching:
1853 case eStateLaunching:
1854 case eStateDetached:
1855 case eStateExited:
1856 show_error = false;
1857 break;
1858
1859 case eStateStopped:
1860 case eStateRunning:
1861 case eStateStepping:
1862 case eStateCrashed:
1863 case eStateSuspended:
1864 show_error = IsAlive();
1865 break;
1866 }
1867
1868 // Reset the IsIndirect flag here, in case the location changes from
1869 // pointing to a indirect symbol to a regular symbol.
1870 owner->SetIsIndirect (false);
1871
1872 if (owner->ShouldResolveIndirectFunctions())
1873 {
1874 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1875 if (symbol && symbol->IsIndirect())
1876 {
1877 Error error;
1878 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1879 if (!error.Success() && show_error)
1880 {
Greg Clayton44d93782014-01-27 23:43:24 +00001881 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1882 symbol->GetAddress().GetLoadAddress(&m_target),
1883 owner->GetBreakpoint().GetID(),
1884 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001885 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001886 return LLDB_INVALID_BREAK_ID;
1887 }
1888 Address resolved_address(load_addr);
1889 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1890 owner->SetIsIndirect(true);
1891 }
1892 else
1893 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1894 }
1895 else
1896 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1897
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001898 if (load_addr != LLDB_INVALID_ADDRESS)
1899 {
1900 BreakpointSiteSP bp_site_sp;
1901
1902 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1903 // create a new breakpoint site and add it.
1904
1905 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1906
1907 if (bp_site_sp)
1908 {
1909 bp_site_sp->AddOwner (owner);
1910 owner->SetBreakpointSite (bp_site_sp);
1911 return bp_site_sp->GetID();
1912 }
1913 else
1914 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001915 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001916 if (bp_site_sp)
1917 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001918 Error error = EnableBreakpointSite (bp_site_sp.get());
1919 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001920 {
1921 owner->SetBreakpointSite (bp_site_sp);
1922 return m_breakpoint_site_list.Add (bp_site_sp);
1923 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001924 else
1925 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001926 if (show_error)
1927 {
1928 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001929 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1930 load_addr,
1931 owner->GetBreakpoint().GetID(),
1932 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001933 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001934 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001935 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001936 }
1937 }
1938 }
1939 // We failed to enable the breakpoint
1940 return LLDB_INVALID_BREAK_ID;
1941
1942}
1943
1944void
1945Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1946{
1947 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1948 if (num_owners == 0)
1949 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001950 // Don't try to disable the site if we don't have a live process anymore.
1951 if (IsAlive())
1952 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001953 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1954 }
1955}
1956
1957
1958size_t
1959Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1960{
1961 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001962 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001963
Jim Ingham20c77192011-06-29 19:42:28 +00001964 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001965 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001966 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1967 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001968 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001969 addr_t intersect_addr;
1970 size_t intersect_size;
1971 size_t opcode_offset;
1972 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001973 {
1974 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1975 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00001976 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001977 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00001978 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001979 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00001981 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001982 }
1983 return bytes_removed;
1984}
1985
1986
Greg Claytonded470d2011-03-19 01:12:21 +00001987
1988size_t
1989Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1990{
1991 PlatformSP platform_sp (m_target.GetPlatform());
1992 if (platform_sp)
1993 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1994 return 0;
1995}
1996
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997Error
1998Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1999{
2000 Error error;
2001 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002002 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003 const addr_t bp_addr = bp_site->GetLoadAddress();
2004 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002005 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 if (bp_site->IsEnabled())
2007 {
2008 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002009 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 +00002010 return error;
2011 }
2012
2013 if (bp_addr == LLDB_INVALID_ADDRESS)
2014 {
2015 error.SetErrorString("BreakpointSite contains an invalid load address.");
2016 return error;
2017 }
2018 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2019 // trap for the breakpoint site
2020 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2021
2022 if (bp_opcode_size == 0)
2023 {
Daniel Malead01b2952012-11-29 21:49:15 +00002024 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002025 }
2026 else
2027 {
2028 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2029
2030 if (bp_opcode_bytes == NULL)
2031 {
2032 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2033 return error;
2034 }
2035
2036 // Save the original opcode by reading it
2037 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2038 {
2039 // Write a software breakpoint in place of the original opcode
2040 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2041 {
2042 uint8_t verify_bp_opcode_bytes[64];
2043 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2044 {
2045 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2046 {
2047 bp_site->SetEnabled(true);
2048 bp_site->SetType (BreakpointSite::eSoftware);
2049 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002050 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002051 bp_site->GetID(),
2052 (uint64_t)bp_addr);
2053 }
2054 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002055 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002056 }
2057 else
2058 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2059 }
2060 else
2061 error.SetErrorString("Unable to write breakpoint trap to memory.");
2062 }
2063 else
2064 error.SetErrorString("Unable to read memory at breakpoint address.");
2065 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002066 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002067 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068 bp_site->GetID(),
2069 (uint64_t)bp_addr,
2070 error.AsCString());
2071 return error;
2072}
2073
2074Error
2075Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2076{
2077 Error error;
2078 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002079 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080 addr_t bp_addr = bp_site->GetLoadAddress();
2081 lldb::user_id_t breakID = bp_site->GetID();
2082 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002083 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002084
2085 if (bp_site->IsHardware())
2086 {
2087 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2088 }
2089 else if (bp_site->IsEnabled())
2090 {
2091 const size_t break_op_size = bp_site->GetByteSize();
2092 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2093 if (break_op_size > 0)
2094 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002095 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002096 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002097 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 bool break_op_found = false;
2099
2100 // Read the breakpoint opcode
2101 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2102 {
2103 bool verify = false;
2104 // Make sure we have the a breakpoint opcode exists at this address
2105 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2106 {
2107 break_op_found = true;
2108 // We found a valid breakpoint opcode at this address, now restore
2109 // the saved opcode.
2110 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2111 {
2112 verify = true;
2113 }
2114 else
2115 error.SetErrorString("Memory write failed when restoring original opcode.");
2116 }
2117 else
2118 {
2119 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2120 // Set verify to true and so we can check if the original opcode has already been restored
2121 verify = true;
2122 }
2123
2124 if (verify)
2125 {
Greg Claytonc982c762010-07-09 20:39:50 +00002126 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002127 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128 // Verify that our original opcode made it back to the inferior
2129 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2130 {
2131 // compare the memory we just read with the original opcode
2132 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2133 {
2134 // SUCCESS
2135 bp_site->SetEnabled(false);
2136 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002137 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 +00002138 return error;
2139 }
2140 else
2141 {
2142 if (break_op_found)
2143 error.SetErrorString("Failed to restore original opcode.");
2144 }
2145 }
2146 else
2147 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2148 }
2149 }
2150 else
2151 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2152 }
2153 }
2154 else
2155 {
2156 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002157 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 +00002158 return error;
2159 }
2160
2161 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002162 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002163 bp_site->GetID(),
2164 (uint64_t)bp_addr,
2165 error.AsCString());
2166 return error;
2167
2168}
2169
Greg Clayton58be07b2011-01-07 06:08:19 +00002170// Uncomment to verify memory caching works after making changes to caching code
2171//#define VERIFY_MEMORY_READS
2172
Sean Callanan64c0cf22012-06-07 22:26:42 +00002173size_t
2174Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2175{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002176 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002177 if (!GetDisableMemoryCache())
2178 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002179#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002180 // Memory caching is enabled, with debug verification
2181
2182 if (buf && size)
2183 {
2184 // Uncomment the line below to make sure memory caching is working.
2185 // I ran this through the test suite and got no assertions, so I am
2186 // pretty confident this is working well. If any changes are made to
2187 // memory caching, uncomment the line below and test your changes!
2188
2189 // Verify all memory reads by using the cache first, then redundantly
2190 // reading the same memory from the inferior and comparing to make sure
2191 // everything is exactly the same.
2192 std::string verify_buf (size, '\0');
2193 assert (verify_buf.size() == size);
2194 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2195 Error verify_error;
2196 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2197 assert (cache_bytes_read == verify_bytes_read);
2198 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2199 assert (verify_error.Success() == error.Success());
2200 return cache_bytes_read;
2201 }
2202 return 0;
2203#else // !defined(VERIFY_MEMORY_READS)
2204 // Memory caching is enabled, without debug verification
2205
2206 return m_memory_cache.Read (addr, buf, size, error);
2207#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002208 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002209 else
2210 {
2211 // Memory caching is disabled
2212
2213 return ReadMemoryFromInferior (addr, buf, size, error);
2214 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002215}
Greg Clayton58be07b2011-01-07 06:08:19 +00002216
Greg Clayton4c82d422012-05-18 23:20:01 +00002217size_t
2218Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2219{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002220 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002221 out_str.clear();
2222 addr_t curr_addr = addr;
2223 while (1)
2224 {
2225 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2226 if (length == 0)
2227 break;
2228 out_str.append(buf, length);
2229 // If we got "length - 1" bytes, we didn't get the whole C string, we
2230 // need to read some more characters
2231 if (length == sizeof(buf) - 1)
2232 curr_addr += length;
2233 else
2234 break;
2235 }
2236 return out_str.size();
2237}
2238
Greg Clayton58be07b2011-01-07 06:08:19 +00002239
2240size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002241Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2242 size_t type_width)
2243{
2244 size_t total_bytes_read = 0;
2245 if (dst && max_bytes && type_width && max_bytes >= type_width)
2246 {
2247 // Ensure a null terminator independent of the number of bytes that is read.
2248 memset (dst, 0, max_bytes);
2249 size_t bytes_left = max_bytes - type_width;
2250
2251 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2252 assert(sizeof(terminator) >= type_width &&
2253 "Attempting to validate a string with more than 4 bytes per character!");
2254
2255 addr_t curr_addr = addr;
2256 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2257 char *curr_dst = dst;
2258
2259 error.Clear();
2260 while (bytes_left > 0 && error.Success())
2261 {
2262 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2263 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2264 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2265
2266 if (bytes_read == 0)
2267 break;
2268
2269 // Search for a null terminator of correct size and alignment in bytes_read
2270 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2271 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2272 if (::strncmp(&dst[i], terminator, type_width) == 0)
2273 {
2274 error.Clear();
2275 return i;
2276 }
2277
2278 total_bytes_read += bytes_read;
2279 curr_dst += bytes_read;
2280 curr_addr += bytes_read;
2281 bytes_left -= bytes_read;
2282 }
2283 }
2284 else
2285 {
2286 if (max_bytes)
2287 error.SetErrorString("invalid arguments");
2288 }
2289 return total_bytes_read;
2290}
2291
2292// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2293// null terminators.
2294size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002295Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002296{
2297 size_t total_cstr_len = 0;
2298 if (dst && dst_max_len)
2299 {
Greg Claytone91b7952011-12-15 03:14:23 +00002300 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002301 // NULL out everything just to be safe
2302 memset (dst, 0, dst_max_len);
2303 Error error;
2304 addr_t curr_addr = addr;
2305 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2306 size_t bytes_left = dst_max_len - 1;
2307 char *curr_dst = dst;
2308
2309 while (bytes_left > 0)
2310 {
2311 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2312 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2313 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2314
2315 if (bytes_read == 0)
2316 {
Greg Claytone91b7952011-12-15 03:14:23 +00002317 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002318 dst[total_cstr_len] = '\0';
2319 break;
2320 }
2321 const size_t len = strlen(curr_dst);
2322
2323 total_cstr_len += len;
2324
2325 if (len < bytes_to_read)
2326 break;
2327
2328 curr_dst += bytes_read;
2329 curr_addr += bytes_read;
2330 bytes_left -= bytes_read;
2331 }
2332 }
Greg Claytone91b7952011-12-15 03:14:23 +00002333 else
2334 {
2335 if (dst == NULL)
2336 result_error.SetErrorString("invalid arguments");
2337 else
2338 result_error.Clear();
2339 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002340 return total_cstr_len;
2341}
2342
2343size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002344Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2345{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 if (buf == NULL || size == 0)
2347 return 0;
2348
2349 size_t bytes_read = 0;
2350 uint8_t *bytes = (uint8_t *)buf;
2351
2352 while (bytes_read < size)
2353 {
2354 const size_t curr_size = size - bytes_read;
2355 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2356 bytes + bytes_read,
2357 curr_size,
2358 error);
2359 bytes_read += curr_bytes_read;
2360 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2361 break;
2362 }
2363
2364 // Replace any software breakpoint opcodes that fall into this range back
2365 // into "buf" before we return
2366 if (bytes_read > 0)
2367 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2368 return bytes_read;
2369}
2370
Greg Clayton58a4c462010-12-16 20:01:20 +00002371uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002372Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002373{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002374 Scalar scalar;
2375 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2376 return scalar.ULongLong(fail_value);
2377 return fail_value;
2378}
2379
2380addr_t
2381Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2382{
2383 Scalar scalar;
2384 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2385 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2386 return LLDB_INVALID_ADDRESS;
2387}
2388
2389
2390bool
2391Process::WritePointerToMemory (lldb::addr_t vm_addr,
2392 lldb::addr_t ptr_value,
2393 Error &error)
2394{
2395 Scalar scalar;
2396 const uint32_t addr_byte_size = GetAddressByteSize();
2397 if (addr_byte_size <= 4)
2398 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002399 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002400 scalar = ptr_value;
2401 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002402}
2403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404size_t
2405Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2406{
2407 size_t bytes_written = 0;
2408 const uint8_t *bytes = (const uint8_t *)buf;
2409
2410 while (bytes_written < size)
2411 {
2412 const size_t curr_size = size - bytes_written;
2413 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2414 bytes + bytes_written,
2415 curr_size,
2416 error);
2417 bytes_written += curr_bytes_written;
2418 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2419 break;
2420 }
2421 return bytes_written;
2422}
2423
2424size_t
2425Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2426{
Greg Clayton58be07b2011-01-07 06:08:19 +00002427#if defined (ENABLE_MEMORY_CACHING)
2428 m_memory_cache.Flush (addr, size);
2429#endif
2430
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002431 if (buf == NULL || size == 0)
2432 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002433
Jim Ingham4b536182011-08-09 02:12:22 +00002434 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 // We need to write any data that would go where any current software traps
2437 // (enabled software breakpoints) any software traps (breakpoints) that we
2438 // may have placed in our tasks memory.
2439
Greg Claytond8cf1a12013-06-12 00:46:38 +00002440 BreakpointSiteList bp_sites_in_range;
2441
2442 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002444 // No breakpoint sites overlap
2445 if (bp_sites_in_range.IsEmpty())
2446 return WriteMemoryPrivate (addr, buf, size, error);
2447 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002449 const uint8_t *ubuf = (const uint8_t *)buf;
2450 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451
Greg Claytond8cf1a12013-06-12 00:46:38 +00002452 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2453
2454 if (error.Success())
2455 {
2456 addr_t intersect_addr;
2457 size_t intersect_size;
2458 size_t opcode_offset;
2459 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2460 assert(intersects);
2461 assert(addr <= intersect_addr && intersect_addr < addr + size);
2462 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2463 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2464
2465 // Check for bytes before this breakpoint
2466 const addr_t curr_addr = addr + bytes_written;
2467 if (intersect_addr > curr_addr)
2468 {
2469 // There are some bytes before this breakpoint that we need to
2470 // just write to memory
2471 size_t curr_size = intersect_addr - curr_addr;
2472 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2473 ubuf + bytes_written,
2474 curr_size,
2475 error);
2476 bytes_written += curr_bytes_written;
2477 if (curr_bytes_written != curr_size)
2478 {
2479 // We weren't able to write all of the requested bytes, we
2480 // are done looping and will return the number of bytes that
2481 // we have written so far.
2482 if (error.Success())
2483 error.SetErrorToGenericError();
2484 }
2485 }
2486 // Now write any bytes that would cover up any software breakpoints
2487 // directly into the breakpoint opcode buffer
2488 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2489 bytes_written += intersect_size;
2490 }
2491 });
2492
2493 if (bytes_written < size)
2494 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2495 ubuf + bytes_written,
2496 size - bytes_written,
2497 error);
2498 }
2499 }
2500 else
2501 {
2502 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503 }
2504
2505 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002506 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002508
2509size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002510Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002511{
2512 if (byte_size == UINT32_MAX)
2513 byte_size = scalar.GetByteSize();
2514 if (byte_size > 0)
2515 {
2516 uint8_t buf[32];
2517 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2518 if (mem_size > 0)
2519 return WriteMemory(addr, buf, mem_size, error);
2520 else
2521 error.SetErrorString ("failed to get scalar as memory data");
2522 }
2523 else
2524 {
2525 error.SetErrorString ("invalid scalar value");
2526 }
2527 return 0;
2528}
2529
2530size_t
2531Process::ReadScalarIntegerFromMemory (addr_t addr,
2532 uint32_t byte_size,
2533 bool is_signed,
2534 Scalar &scalar,
2535 Error &error)
2536{
Greg Clayton7060f892013-05-01 23:41:30 +00002537 uint64_t uval = 0;
2538 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002539 {
Greg Clayton7060f892013-05-01 23:41:30 +00002540 error.SetErrorString ("byte size is zero");
2541 }
2542 else if (byte_size & (byte_size - 1))
2543 {
2544 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2545 }
2546 else if (byte_size <= sizeof(uval))
2547 {
2548 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002549 if (bytes_read == byte_size)
2550 {
2551 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002552 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002553 if (byte_size <= 4)
2554 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002555 else
Greg Clayton7060f892013-05-01 23:41:30 +00002556 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002557 if (is_signed)
2558 scalar.SignExtend(byte_size * 8);
2559 return bytes_read;
2560 }
2561 }
2562 else
2563 {
2564 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2565 }
2566 return 0;
2567}
2568
Greg Claytond495c532011-05-17 03:37:42 +00002569#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570addr_t
2571Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2572{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002573 if (GetPrivateState() != eStateStopped)
2574 return LLDB_INVALID_ADDRESS;
2575
Greg Claytond495c532011-05-17 03:37:42 +00002576#if defined (USE_ALLOCATE_MEMORY_CACHE)
2577 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2578#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002579 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002580 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002581 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002582 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 +00002583 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002584 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002585 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002586 m_mod_id.GetStopID(),
2587 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002588 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002589#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002590}
2591
Sean Callanan90539452011-09-20 23:01:51 +00002592bool
2593Process::CanJIT ()
2594{
Sean Callanana7b443a2012-02-14 22:50:38 +00002595 if (m_can_jit == eCanJITDontKnow)
2596 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002597 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002598 Error err;
2599
2600 uint64_t allocated_memory = AllocateMemory(8,
2601 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2602 err);
2603
2604 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002605 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002606 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002607 if (log)
2608 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2609 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002610 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002611 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002612 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002613 if (log)
2614 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2615 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002616
2617 DeallocateMemory (allocated_memory);
2618 }
2619
Sean Callanan90539452011-09-20 23:01:51 +00002620 return m_can_jit == eCanJITYes;
2621}
2622
2623void
2624Process::SetCanJIT (bool can_jit)
2625{
2626 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2627}
2628
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002629Error
2630Process::DeallocateMemory (addr_t ptr)
2631{
Greg Claytond495c532011-05-17 03:37:42 +00002632 Error error;
2633#if defined (USE_ALLOCATE_MEMORY_CACHE)
2634 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2635 {
Daniel Malead01b2952012-11-29 21:49:15 +00002636 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002637 }
2638#else
2639 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002640
Greg Clayton5160ce52013-03-27 23:08:40 +00002641 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002642 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002643 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 +00002644 ptr,
2645 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002646 m_mod_id.GetStopID(),
2647 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002648#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002649 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002650}
2651
Han Ming Ongc811d382012-11-17 00:33:14 +00002652
Greg Claytonc9660542012-02-05 02:38:54 +00002653ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002654Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002655 lldb::addr_t header_addr,
2656 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002657{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002658 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002659 if (module_sp)
2660 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002661 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002662 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002663 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002664 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002665 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002666 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002667}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002668
2669Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002670Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002671{
2672 Error error;
2673 error.SetErrorString("watchpoints are not supported");
2674 return error;
2675}
2676
2677Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002678Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679{
2680 Error error;
2681 error.SetErrorString("watchpoints are not supported");
2682 return error;
2683}
2684
2685StateType
2686Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2687{
2688 StateType state;
2689 // Now wait for the process to launch and return control to us, and then
2690 // call DidLaunch:
2691 while (1)
2692 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002693 event_sp.reset();
2694 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2695
Greg Clayton2637f822011-11-17 01:23:07 +00002696 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002698
2699 // If state is invalid, then we timed out
2700 if (state == eStateInvalid)
2701 break;
2702
2703 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704 HandlePrivateEvent (event_sp);
2705 }
2706 return state;
2707}
2708
2709Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002710Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711{
2712 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002714 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002715 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002716 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002717 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002718 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002719
Greg Claytonaa149cb2011-08-11 02:48:45 +00002720 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721 if (exe_module)
2722 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002723 char local_exec_file_path[PATH_MAX];
2724 char platform_exec_file_path[PATH_MAX];
2725 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2726 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727 if (exe_module->GetFileSpec().Exists())
2728 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002729 // Install anything that might need to be installed prior to launching.
2730 // For host systems, this will do nothing, but if we are connected to a
2731 // remote platform it will install any needed binaries
2732 error = GetTarget().Install(&launch_info);
2733 if (error.Fail())
2734 return error;
2735
Greg Clayton71337622011-02-24 22:24:29 +00002736 if (PrivateStateThreadIsValid ())
2737 PausePrivateStateThread ();
2738
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739 error = WillLaunch (exe_module);
2740 if (error.Success())
2741 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002742 const bool restarted = false;
2743 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002744 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745
Ed Maste64fad602013-07-29 20:58:06 +00002746 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002747 {
2748 // Now launch using these arguments.
2749 error = DoLaunch (exe_module, launch_info);
2750 }
2751 else
2752 {
2753 // This shouldn't happen
2754 error.SetErrorString("failed to acquire process run lock");
2755 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756
2757 if (error.Fail())
2758 {
2759 if (GetID() != LLDB_INVALID_PROCESS_ID)
2760 {
2761 SetID (LLDB_INVALID_PROCESS_ID);
2762 const char *error_string = error.AsCString();
2763 if (error_string == NULL)
2764 error_string = "launch failed";
2765 SetExitStatus (-1, error_string);
2766 }
2767 }
2768 else
2769 {
2770 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002771 TimeValue timeout_time;
2772 timeout_time = TimeValue::Now();
2773 timeout_time.OffsetWithSeconds(10);
2774 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775
Greg Clayton1a38ea72011-06-22 01:42:17 +00002776 if (state == eStateInvalid || event_sp.get() == NULL)
2777 {
2778 // We were able to launch the process, but we failed to
2779 // catch the initial stop.
2780 SetExitStatus (0, "failed to catch stop after launch");
2781 Destroy();
2782 }
2783 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002784 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002785
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002786 DidLaunch ();
2787
Greg Claytonc859e2d2012-02-13 23:10:39 +00002788 DynamicLoader *dyld = GetDynamicLoader ();
2789 if (dyld)
2790 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002791
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002792 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002793
Jason Molendaeef51062013-11-05 03:57:19 +00002794 SystemRuntime *system_runtime = GetSystemRuntime ();
2795 if (system_runtime)
2796 system_runtime->DidLaunch();
2797
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002798 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002799 // This delays passing the stopped event to listeners till DidLaunch gets
2800 // a chance to complete...
2801 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002802
2803 if (PrivateStateThreadIsValid ())
2804 ResumePrivateStateThread ();
2805 else
2806 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807 }
2808 else if (state == eStateExited)
2809 {
2810 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2811 // not likely to work, and return an invalid pid.
2812 HandlePrivateEvent (event_sp);
2813 }
2814 }
2815 }
2816 }
2817 else
2818 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002819 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002820 }
2821 }
2822 return error;
2823}
2824
Greg Claytonc3776bf2012-02-09 06:16:32 +00002825
2826Error
2827Process::LoadCore ()
2828{
2829 Error error = DoLoadCore();
2830 if (error.Success())
2831 {
2832 if (PrivateStateThreadIsValid ())
2833 ResumePrivateStateThread ();
2834 else
2835 StartPrivateStateThread ();
2836
Greg Claytonc859e2d2012-02-13 23:10:39 +00002837 DynamicLoader *dyld = GetDynamicLoader ();
2838 if (dyld)
2839 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002840
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002841 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002842
Jason Molendaeef51062013-11-05 03:57:19 +00002843 SystemRuntime *system_runtime = GetSystemRuntime ();
2844 if (system_runtime)
2845 system_runtime->DidAttach();
2846
Greg Claytonc859e2d2012-02-13 23:10:39 +00002847 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002848 // We successfully loaded a core file, now pretend we stopped so we can
2849 // show all of the threads in the core file and explore the crashed
2850 // state.
2851 SetPrivateState (eStateStopped);
2852
2853 }
2854 return error;
2855}
2856
Greg Claytonc859e2d2012-02-13 23:10:39 +00002857DynamicLoader *
2858Process::GetDynamicLoader ()
2859{
2860 if (m_dyld_ap.get() == NULL)
2861 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2862 return m_dyld_ap.get();
2863}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002864
Todd Fialaaf245d12014-06-30 21:05:18 +00002865const lldb::DataBufferSP
2866Process::GetAuxvData()
2867{
2868 return DataBufferSP ();
2869}
2870
Andrew MacPherson17220c12014-03-05 10:12:43 +00002871JITLoaderList &
2872Process::GetJITLoaders ()
2873{
2874 if (!m_jit_loaders_ap)
2875 {
2876 m_jit_loaders_ap.reset(new JITLoaderList());
2877 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2878 }
2879 return *m_jit_loaders_ap;
2880}
2881
Jason Molendaeef51062013-11-05 03:57:19 +00002882SystemRuntime *
2883Process::GetSystemRuntime ()
2884{
2885 if (m_system_runtime_ap.get() == NULL)
2886 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2887 return m_system_runtime_ap.get();
2888}
2889
Greg Claytonc3776bf2012-02-09 06:16:32 +00002890
Jim Inghambb3a2832011-01-29 01:49:25 +00002891Process::NextEventAction::EventActionResult
2892Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893{
Jim Inghambb3a2832011-01-29 01:49:25 +00002894 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2895 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002896 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002897 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002898 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002899 return eEventActionRetry;
2900
2901 case eStateStopped:
2902 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002903 {
2904 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002905 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002906 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002907 // We don't want these events to be reported, so go set the ShouldReportStop here:
2908 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2909
Greg Claytonc9ed4782011-11-12 02:10:56 +00002910 if (m_exec_count > 0)
2911 {
2912 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00002913 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002914 return eEventActionRetry;
2915 }
2916 else
2917 {
2918 m_process->CompleteAttach ();
2919 return eEventActionSuccess;
2920 }
2921 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002922 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002923
Greg Clayton513c26c2011-01-29 07:10:55 +00002924 default:
2925 case eStateExited:
2926 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002927 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002928 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002929
2930 m_exit_string.assign ("No valid Process");
2931 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002932}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002933
Jim Inghambb3a2832011-01-29 01:49:25 +00002934Process::NextEventAction::EventActionResult
2935Process::AttachCompletionHandler::HandleBeingInterrupted()
2936{
2937 return eEventActionSuccess;
2938}
2939
2940const char *
2941Process::AttachCompletionHandler::GetExitString ()
2942{
2943 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944}
2945
2946Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002947Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002949 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002950 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002951 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002952 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002953 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002954 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002955
Greg Clayton144f3a92011-11-15 03:53:30 +00002956 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002957 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002958 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002959 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002960 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002961
Greg Clayton144f3a92011-11-15 03:53:30 +00002962 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002963 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002964 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2965
2966 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002967 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002968 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2969 if (error.Success())
2970 {
Ed Maste64fad602013-07-29 20:58:06 +00002971 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002972 {
2973 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002974 const bool restarted = false;
2975 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002976 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00002977 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00002978 }
2979 else
2980 {
2981 // This shouldn't happen
2982 error.SetErrorString("failed to acquire process run lock");
2983 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002984
Greg Clayton144f3a92011-11-15 03:53:30 +00002985 if (error.Fail())
2986 {
2987 if (GetID() != LLDB_INVALID_PROCESS_ID)
2988 {
2989 SetID (LLDB_INVALID_PROCESS_ID);
2990 if (error.AsCString() == NULL)
2991 error.SetErrorString("attach failed");
2992
2993 SetExitStatus(-1, error.AsCString());
2994 }
2995 }
2996 else
2997 {
2998 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2999 StartPrivateStateThread();
3000 }
3001 return error;
3002 }
Greg Claytone996fd32011-03-08 22:40:15 +00003003 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003004 else
Greg Claytone996fd32011-03-08 22:40:15 +00003005 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003006 ProcessInstanceInfoList process_infos;
3007 PlatformSP platform_sp (m_target.GetPlatform ());
3008
3009 if (platform_sp)
3010 {
3011 ProcessInstanceInfoMatch match_info;
3012 match_info.GetProcessInfo() = attach_info;
3013 match_info.SetNameMatchType (eNameMatchEquals);
3014 platform_sp->FindProcesses (match_info, process_infos);
3015 const uint32_t num_matches = process_infos.GetSize();
3016 if (num_matches == 1)
3017 {
3018 attach_pid = process_infos.GetProcessIDAtIndex(0);
3019 // Fall through and attach using the above process ID
3020 }
3021 else
3022 {
3023 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3024 if (num_matches > 1)
3025 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3026 else
3027 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3028 }
3029 }
3030 else
3031 {
3032 error.SetErrorString ("invalid platform, can't find processes by name");
3033 return error;
3034 }
Greg Claytone996fd32011-03-08 22:40:15 +00003035 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 }
3037 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003038 {
3039 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003040 }
3041 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003042
3043 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003044 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003045 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003046 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003047 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003048
Ed Maste64fad602013-07-29 20:58:06 +00003049 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003050 {
3051 // Now attach using these arguments.
3052 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003053 const bool restarted = false;
3054 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003055 error = DoAttachToProcessWithID (attach_pid, attach_info);
3056 }
3057 else
3058 {
3059 // This shouldn't happen
3060 error.SetErrorString("failed to acquire process run lock");
3061 }
3062
Greg Clayton144f3a92011-11-15 03:53:30 +00003063 if (error.Success())
3064 {
3065
3066 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3067 StartPrivateStateThread();
3068 }
3069 else
Greg Claytone996fd32011-03-08 22:40:15 +00003070 {
3071 if (GetID() != LLDB_INVALID_PROCESS_ID)
3072 {
3073 SetID (LLDB_INVALID_PROCESS_ID);
3074 const char *error_string = error.AsCString();
3075 if (error_string == NULL)
3076 error_string = "attach failed";
3077
3078 SetExitStatus(-1, error_string);
3079 }
3080 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 }
3082 }
3083 return error;
3084}
3085
Greg Clayton93d3c8332011-02-16 04:46:07 +00003086void
3087Process::CompleteAttach ()
3088{
3089 // Let the process subclass figure out at much as it can about the process
3090 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003091 ArchSpec process_arch;
3092 DidAttach(process_arch);
3093
3094 if (process_arch.IsValid())
3095 m_target.SetArchitecture(process_arch);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003096
Jim Ingham4299fdb2011-09-15 01:10:17 +00003097 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3098 // the same as the one we've already set, switch architectures.
3099 PlatformSP platform_sp (m_target.GetPlatform ());
3100 assert (platform_sp.get());
3101 if (platform_sp)
3102 {
Greg Clayton70512312012-05-08 01:45:38 +00003103 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003104 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003105 {
3106 ArchSpec platform_arch;
3107 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3108 if (platform_sp)
3109 {
3110 m_target.SetPlatform (platform_sp);
3111 m_target.SetArchitecture(platform_arch);
3112 }
3113 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003114 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003115 {
3116 ProcessInstanceInfo process_info;
3117 platform_sp->GetProcessInfo (GetID(), process_info);
3118 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003119 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003120 m_target.SetArchitecture (process_arch);
3121 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003122 }
3123
3124 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003125 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003126 DynamicLoader *dyld = GetDynamicLoader ();
3127 if (dyld)
3128 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003129
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003130 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003131
Jason Molendaeef51062013-11-05 03:57:19 +00003132 SystemRuntime *system_runtime = GetSystemRuntime ();
3133 if (system_runtime)
3134 system_runtime->DidAttach();
3135
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003136 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003137 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003138 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003139 Mutex::Locker modules_locker(target_modules.GetMutex());
3140 size_t num_modules = target_modules.GetSize();
3141 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003142
Andy Gibbsa297a972013-06-19 19:04:53 +00003143 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003144 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003145 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003146 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003147 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003148 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003149 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003150 break;
3151 }
3152 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003153 if (new_executable_module_sp)
3154 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003155}
3156
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003158Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003159{
Greg Claytonb766a732011-02-04 01:58:07 +00003160 m_abi_sp.reset();
3161 m_process_input_reader.reset();
3162
3163 // Find the process and its architecture. Make sure it matches the architecture
3164 // of the current Target, and if not adjust it.
3165
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003166 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003167 if (error.Success())
3168 {
Greg Clayton71337622011-02-24 22:24:29 +00003169 if (GetID() != LLDB_INVALID_PROCESS_ID)
3170 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003171 EventSP event_sp;
3172 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3173
3174 if (state == eStateStopped || state == eStateCrashed)
3175 {
3176 // If we attached and actually have a process on the other end, then
3177 // this ended up being the equivalent of an attach.
3178 CompleteAttach ();
3179
3180 // This delays passing the stopped event to listeners till
3181 // CompleteAttach gets a chance to complete...
3182 HandlePrivateEvent (event_sp);
3183
3184 }
Greg Clayton71337622011-02-24 22:24:29 +00003185 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003186
3187 if (PrivateStateThreadIsValid ())
3188 ResumePrivateStateThread ();
3189 else
3190 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003191 }
3192 return error;
3193}
3194
3195
3196Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003197Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003198{
Greg Clayton5160ce52013-03-27 23:08:40 +00003199 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003201 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003202 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003203 StateAsCString(m_public_state.GetValue()),
3204 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205
3206 Error error (WillResume());
3207 // Tell the process it is about to resume before the thread list
3208 if (error.Success())
3209 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003210 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211 // can let all of our threads know that they are about to be
3212 // resumed. Threads will each be called with
3213 // Thread::WillResume(StateType) where StateType contains the state
3214 // that they are supposed to have when the process is resumed
3215 // (suspended/running/stepping). Threads should also check
3216 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003217 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218 if (m_thread_list.WillResume())
3219 {
Jim Ingham372787f2012-04-07 00:00:41 +00003220 // Last thing, do the PreResumeActions.
3221 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 {
Jim Ingham0161b492013-02-09 01:29:05 +00003223 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003224 }
3225 else
3226 {
3227 m_mod_id.BumpResumeID();
3228 error = DoResume();
3229 if (error.Success())
3230 {
3231 DidResume();
3232 m_thread_list.DidResume();
3233 if (log)
3234 log->Printf ("Process thinks the process has resumed.");
3235 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003236 }
3237 }
3238 else
3239 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003240 // Somebody wanted to run without running. So generate a continue & a stopped event,
3241 // and let the world handle them.
3242 if (log)
3243 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3244
3245 SetPrivateState(eStateRunning);
3246 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003247 }
3248 }
Jim Ingham444586b2011-01-24 06:34:17 +00003249 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003250 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003251 return error;
3252}
3253
3254Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003255Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003257 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3258 // in case it was already set and some thread plan logic calls halt on its
3259 // own.
3260 m_clear_thread_plans_on_stop |= clear_thread_plans;
3261
Jim Inghamaacc3182012-06-06 00:29:30 +00003262 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3263 // we could just straightaway get another event. It just narrows the window...
3264 m_currently_handling_event.WaitForValueEqualTo(false);
3265
3266
Jim Inghambb3a2832011-01-29 01:49:25 +00003267 // Pause our private state thread so we can ensure no one else eats
3268 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003269 Listener halt_listener ("lldb.process.halt_listener");
3270 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003271
Jim Inghambb3a2832011-01-29 01:49:25 +00003272 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003273 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003274
Greg Clayton06357c92014-07-30 17:38:47 +00003275 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003276 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003277 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003278
Greg Clayton513c26c2011-01-29 07:10:55 +00003279 bool caused_stop = false;
3280
3281 // Ask the process subclass to actually halt our process
3282 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003284 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003285 if (m_public_state.GetValue() == eStateAttaching)
3286 {
Greg Clayton06357c92014-07-30 17:38:47 +00003287 // Don't hijack and eat the eStateExited as the code that was doing
3288 // the attach will be waiting for this event...
3289 RestorePrivateProcessEvents();
3290 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003291 SetExitStatus(SIGKILL, "Cancelled async attach.");
3292 Destroy ();
3293 }
3294 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003295 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003296 // If "caused_stop" is true, then DoHalt stopped the process. If
3297 // "caused_stop" is false, the process was already stopped.
3298 // If the DoHalt caused the process to stop, then we want to catch
3299 // this event and set the interrupted bool to true before we pass
3300 // this along so clients know that the process was interrupted by
3301 // a halt command.
3302 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003303 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003304 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003305 TimeValue timeout_time;
3306 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003307 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003308 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3309 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003310
Jim Ingham0f16e732011-02-08 05:20:59 +00003311 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003312 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003313 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003314 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003315 }
3316 else
3317 {
Greg Clayton2637f822011-11-17 01:23:07 +00003318 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003319 {
3320 // We caused the process to interrupt itself, so mark this
3321 // as such in the stop event so clients can tell an interrupted
3322 // process from a natural stop
3323 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3324 }
3325 else
3326 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003327 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003328 if (log)
3329 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3330 error.SetErrorString ("Did not get stopped event after halt.");
3331 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003332 }
3333 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003334 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003335 }
3336 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003337 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003338 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003339 if (!restored_process_events)
3340 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003341
3342 // Post any event we might have consumed. If all goes well, we will have
3343 // stopped the process, intercepted the event and set the interrupted
3344 // bool in the event. Post it to the private event queue and that will end up
3345 // correctly setting the state.
3346 if (event_sp)
3347 m_private_state_broadcaster.BroadcastEvent(event_sp);
3348
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003349 return error;
3350}
3351
3352Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003353Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3354{
3355 Error error;
3356 if (m_public_state.GetValue() == eStateRunning)
3357 {
3358 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3359 if (log)
3360 log->Printf("Process::Destroy() About to halt.");
3361 error = Halt();
3362 if (error.Success())
3363 {
3364 // Consume the halt event.
3365 TimeValue timeout (TimeValue::Now());
3366 timeout.OffsetWithSeconds(1);
3367 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3368
3369 // If the process exited while we were waiting for it to stop, put the exited event into
3370 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3371 // they don't have a process anymore...
3372
3373 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3374 {
3375 if (log)
3376 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3377 return error;
3378 }
3379 else
3380 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3381
3382 if (state != eStateStopped)
3383 {
3384 if (log)
3385 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3386 // If we really couldn't stop the process then we should just error out here, but if the
3387 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3388 StateType private_state = m_private_state.GetValue();
3389 if (private_state != eStateStopped)
3390 {
3391 return error;
3392 }
3393 }
3394 }
3395 else
3396 {
3397 if (log)
3398 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3399 }
3400 }
3401 return error;
3402}
3403
3404Error
Jim Inghamacff8952013-05-02 00:27:30 +00003405Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003407 EventSP exit_event_sp;
3408 Error error;
3409 m_destroy_in_process = true;
3410
3411 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003412
3413 if (error.Success())
3414 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003415 if (DetachRequiresHalt())
3416 {
3417 error = HaltForDestroyOrDetach (exit_event_sp);
3418 if (!error.Success())
3419 {
3420 m_destroy_in_process = false;
3421 return error;
3422 }
3423 else if (exit_event_sp)
3424 {
3425 // We shouldn't need to do anything else here. There's no process left to detach from...
3426 StopPrivateStateThread();
3427 m_destroy_in_process = false;
3428 return error;
3429 }
3430 }
3431
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003432 m_thread_list.DiscardThreadPlans();
3433 DisableAllBreakpointSites();
3434
Jim Inghamacff8952013-05-02 00:27:30 +00003435 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003436 if (error.Success())
3437 {
3438 DidDetach();
3439 StopPrivateStateThread();
3440 }
Jim Inghamacff8952013-05-02 00:27:30 +00003441 else
3442 {
3443 return error;
3444 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003445 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003446 m_destroy_in_process = false;
3447
3448 // If we exited when we were waiting for a process to stop, then
3449 // forward the event here so we don't lose the event
3450 if (exit_event_sp)
3451 {
3452 // Directly broadcast our exited event because we shut down our
3453 // private state thread above
3454 BroadcastEvent(exit_event_sp);
3455 }
3456
3457 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3458 // the last events through the event system, in which case we might strand the write lock. Unlock
3459 // it here so when we do to tear down the process we don't get an error destroying the lock.
3460
Ed Maste64fad602013-07-29 20:58:06 +00003461 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003462 return error;
3463}
3464
3465Error
3466Process::Destroy ()
3467{
Jim Ingham09437922013-03-01 20:04:25 +00003468
3469 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3470 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3471 // failed and the process stays around for some reason it won't be in a confused state.
3472
3473 m_destroy_in_process = true;
3474
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003475 Error error (WillDestroy());
3476 if (error.Success())
3477 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003478 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003479 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003480 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003481 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003482 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003483
Jim Inghamaacc3182012-06-06 00:29:30 +00003484 if (m_public_state.GetValue() != eStateRunning)
3485 {
3486 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3487 // kill it, we don't want it hitting a breakpoint...
3488 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3489 // we're not going to have much luck doing this now.
3490 m_thread_list.DiscardThreadPlans();
3491 DisableAllBreakpointSites();
3492 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003493
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003494 error = DoDestroy();
3495 if (error.Success())
3496 {
3497 DidDestroy();
3498 StopPrivateStateThread();
3499 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003500 m_stdio_communication.StopReadThread();
3501 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003502
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003503 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003504 {
3505 m_process_input_reader->SetIsDone(true);
3506 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003507 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003508 }
3509
Greg Clayton85fb1b92012-09-11 02:33:37 +00003510 // If we exited when we were waiting for a process to stop, then
3511 // forward the event here so we don't lose the event
3512 if (exit_event_sp)
3513 {
3514 // Directly broadcast our exited event because we shut down our
3515 // private state thread above
3516 BroadcastEvent(exit_event_sp);
3517 }
3518
Jim Inghamb1e2e842012-04-12 18:49:31 +00003519 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3520 // the last events through the event system, in which case we might strand the write lock. Unlock
3521 // 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 +00003522 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003523 }
Jim Ingham09437922013-03-01 20:04:25 +00003524
3525 m_destroy_in_process = false;
3526
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003527 return error;
3528}
3529
3530Error
3531Process::Signal (int signal)
3532{
3533 Error error (WillSignal());
3534 if (error.Success())
3535 {
3536 error = DoSignal(signal);
3537 if (error.Success())
3538 DidSignal();
3539 }
3540 return error;
3541}
3542
Greg Clayton514487e2011-02-15 21:59:32 +00003543lldb::ByteOrder
3544Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003545{
Greg Clayton514487e2011-02-15 21:59:32 +00003546 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003547}
3548
3549uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003550Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003551{
Greg Clayton514487e2011-02-15 21:59:32 +00003552 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003553}
3554
Greg Clayton514487e2011-02-15 21:59:32 +00003555
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003556bool
3557Process::ShouldBroadcastEvent (Event *event_ptr)
3558{
3559 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3560 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003561 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003563 switch (state)
3564 {
Greg Claytonb766a732011-02-04 01:58:07 +00003565 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003566 case eStateAttaching:
3567 case eStateLaunching:
3568 case eStateDetached:
3569 case eStateExited:
3570 case eStateUnloaded:
3571 // These events indicate changes in the state of the debugging session, always report them.
3572 return_value = true;
3573 break;
3574 case eStateInvalid:
3575 // We stopped for no apparent reason, don't report it.
3576 return_value = false;
3577 break;
3578 case eStateRunning:
3579 case eStateStepping:
3580 // If we've started the target running, we handle the cases where we
3581 // are already running and where there is a transition from stopped to
3582 // running differently.
3583 // running -> running: Automatically suppress extra running events
3584 // stopped -> running: Report except when there is one or more no votes
3585 // and no yes votes.
3586 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003587 if (m_force_next_event_delivery)
3588 return_value = true;
3589 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003590 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003591 switch (m_last_broadcast_state)
3592 {
3593 case eStateRunning:
3594 case eStateStepping:
3595 // We always suppress multiple runnings with no PUBLIC stop in between.
3596 return_value = false;
3597 break;
3598 default:
3599 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003600 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003601 // events. If I run the lldb/test/thread/a.out file and
3602 // break at main.cpp:58, run and hit the breakpoints on
3603 // multiple threads, then somehow during the stepping over
3604 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003605
Jim Ingham1460e4b2014-01-10 23:46:59 +00003606 // This is a transition from stop to run.
3607 switch (m_thread_list.ShouldReportRun (event_ptr))
3608 {
3609 case eVoteYes:
3610 case eVoteNoOpinion:
3611 return_value = true;
3612 break;
3613 case eVoteNo:
3614 return_value = false;
3615 break;
3616 }
3617 break;
3618 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003619 }
3620 break;
3621 case eStateStopped:
3622 case eStateCrashed:
3623 case eStateSuspended:
3624 {
3625 // We've stopped. First see if we're going to restart the target.
3626 // If we are going to stop, then we always broadcast the event.
3627 // 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 +00003628 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003629
Jim Inghamcb4ca112012-05-16 01:32:14 +00003630 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003631 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003633 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003634 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003635 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003636 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003637 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3638 // so they can properly set their state.
3639 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003640 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003641 }
3642 else
3643 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003644 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3645 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003646
Jim Ingham0161b492013-02-09 01:29:05 +00003647 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3648 // Asking the thread list is also not likely to go well, since we are running again.
3649 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003650
Jim Ingham0161b492013-02-09 01:29:05 +00003651 if (!was_restarted)
3652 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003653
Jim Ingham221d51c2013-05-08 00:35:16 +00003654 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003655 {
Jim Ingham0161b492013-02-09 01:29:05 +00003656 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3657 if (log)
3658 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003659 should_resume, StateAsCString(state),
3660 was_restarted, stop_vote);
3661
Jim Ingham0161b492013-02-09 01:29:05 +00003662 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003663 {
3664 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003665 return_value = true;
3666 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003667 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003668 case eVoteNo:
3669 return_value = false;
3670 break;
3671 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003672
Jim Inghamcb95f342012-09-05 21:13:56 +00003673 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003674 {
3675 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003676 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3677 static_cast<void*>(event_ptr),
3678 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003679 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003680 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003681 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683 }
3684 else
3685 {
3686 return_value = true;
3687 SynchronouslyNotifyStateChanged (state);
3688 }
3689 }
3690 }
Jim Ingham0161b492013-02-09 01:29:05 +00003691 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003692 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003693
Jim Ingham1460e4b2014-01-10 23:46:59 +00003694 // Forcing the next event delivery is a one shot deal. So reset it here.
3695 m_force_next_event_delivery = false;
3696
Jim Ingham0161b492013-02-09 01:29:05 +00003697 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3698 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3699 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3700 // because the PublicState reflects the last event pulled off the queue, and there may be several
3701 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3702 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003703
Jim Ingham0161b492013-02-09 01:29:05 +00003704 if (return_value)
3705 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003706
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003707 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003708 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003709 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003710 StateAsCString(m_last_broadcast_state),
3711 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712 return return_value;
3713}
3714
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003715
3716bool
Jim Ingham372787f2012-04-07 00:00:41 +00003717Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003718{
Greg Clayton5160ce52013-03-27 23:08:40 +00003719 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720
Greg Clayton8b82f082011-04-12 05:54:46 +00003721 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003723 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3724
Jim Ingham372787f2012-04-07 00:00:41 +00003725 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003726 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003727
3728 // Create a thread that watches our internal state and controls which
3729 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003730 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003731
3732 if (Host::MAX_THREAD_NAME_LENGTH <= 16)
3733 {
3734 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3735 if (already_running)
3736 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3737 else
3738 snprintf(thread_name, sizeof(thread_name), "intern-state");
3739 }
Jim Ingham372787f2012-04-07 00:00:41 +00003740 else
Todd Fiala17096d72014-07-16 19:03:16 +00003741 {
3742 if (already_running)
3743 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3744 else
3745 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3746 }
3747
Jim Ingham076b3042012-04-10 01:21:57 +00003748 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003749 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003750 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3751 if (success)
3752 {
3753 ResumePrivateStateThread();
3754 return true;
3755 }
3756 else
3757 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758}
3759
3760void
3761Process::PausePrivateStateThread ()
3762{
3763 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3764}
3765
3766void
3767Process::ResumePrivateStateThread ()
3768{
3769 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3770}
3771
3772void
3773Process::StopPrivateStateThread ()
3774{
Greg Clayton8b82f082011-04-12 05:54:46 +00003775 if (PrivateStateThreadIsValid ())
3776 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003777 else
3778 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003779 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003780 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003781 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003782 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783}
3784
3785void
3786Process::ControlPrivateStateThread (uint32_t signal)
3787{
Greg Clayton5160ce52013-03-27 23:08:40 +00003788 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789
3790 assert (signal == eBroadcastInternalStateControlStop ||
3791 signal == eBroadcastInternalStateControlPause ||
3792 signal == eBroadcastInternalStateControlResume);
3793
3794 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003795 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003796
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003797 // Signal the private state thread. First we should copy this is case the
3798 // thread starts exiting since the private state thread will NULL this out
3799 // when it exits
3800 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003801 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802 {
3803 TimeValue timeout_time;
3804 bool timed_out;
3805
3806 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3807
3808 timeout_time = TimeValue::Now();
3809 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003810 if (log)
3811 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003812 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3813 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3814
3815 if (signal == eBroadcastInternalStateControlStop)
3816 {
3817 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003818 {
3819 Error error;
3820 Host::ThreadCancel (private_state_thread, &error);
3821 if (log)
3822 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3823 }
3824 else
3825 {
3826 if (log)
3827 log->Printf ("The control event killed the private state thread without having to cancel.");
3828 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003829
3830 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003831 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003832 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003833 }
3834 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003835 else
3836 {
3837 if (log)
3838 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3839 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840}
3841
3842void
Jim Inghamcfc09352012-07-27 23:57:19 +00003843Process::SendAsyncInterrupt ()
3844{
3845 if (PrivateStateThreadIsValid())
3846 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3847 else
3848 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3849}
3850
3851void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003852Process::HandlePrivateEvent (EventSP &event_sp)
3853{
Greg Clayton5160ce52013-03-27 23:08:40 +00003854 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003855 m_resume_requested = false;
3856
Jim Inghamaacc3182012-06-06 00:29:30 +00003857 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003858
Greg Clayton414f5d32011-01-25 02:58:48 +00003859 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003860
3861 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003862 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003863 {
Jim Ingham754ab982011-01-29 04:05:41 +00003864 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003865 if (log)
3866 log->Printf ("Ran next event action, result was %d.", action_result);
3867
Jim Inghambb3a2832011-01-29 01:49:25 +00003868 switch (action_result)
3869 {
3870 case NextEventAction::eEventActionSuccess:
3871 SetNextEventAction(NULL);
3872 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003873
Jim Inghambb3a2832011-01-29 01:49:25 +00003874 case NextEventAction::eEventActionRetry:
3875 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003876
Jim Inghambb3a2832011-01-29 01:49:25 +00003877 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003878 // Handle Exiting Here. If we already got an exited event,
3879 // we should just propagate it. Otherwise, swallow this event,
3880 // and set our state to exit so the next event will kill us.
3881 if (new_state != eStateExited)
3882 {
3883 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003884 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003885 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003886 SetNextEventAction(NULL);
3887 return;
3888 }
3889 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003890 break;
3891 }
3892 }
3893
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003894 // See if we should broadcast this state to external clients?
3895 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896
3897 if (should_broadcast)
3898 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003899 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900 if (log)
3901 {
Daniel Malead01b2952012-11-29 21:49:15 +00003902 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003903 __FUNCTION__,
3904 GetID(),
3905 StateAsCString(new_state),
3906 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003907 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003908 }
Jim Ingham9575d842011-03-11 03:53:59 +00003909 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003910 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003911 {
3912 // Only push the input handler if we aren't fowarding events,
3913 // as this means the curses GUI is in use...
3914 if (!GetTarget().GetDebugger().IsForwardingEvents())
3915 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00003916 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00003917 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003918 else if (StateIsStoppedState(new_state, false))
3919 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00003920 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00003921 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3922 {
3923 // If the lldb_private::Debugger is handling the events, we don't
3924 // want to pop the process IOHandler here, we want to do it when
3925 // we receive the stopped event so we can carefully control when
3926 // the process IOHandler is popped because when we stop we want to
3927 // display some text stating how and why we stopped, then maybe some
3928 // process/thread/frame info, and then we want the "(lldb) " prompt
3929 // to show up. If we pop the process IOHandler here, then we will
3930 // cause the command interpreter to become the top IOHandler after
3931 // the process pops off and it will update its prompt right away...
3932 // See the Debugger.cpp file where it calls the function as
3933 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3934 // Otherwise we end up getting overlapping "(lldb) " prompts and
3935 // garbled output.
3936 //
3937 // If we aren't handling the events in the debugger (which is indicated
3938 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3939 // are hijacked, then we always pop the process IO handler manually.
3940 // Hijacking happens when the internal process state thread is running
3941 // thread plans, or when commands want to run in synchronous mode
3942 // and they call "process->WaitForProcessToStop()". An example of something
3943 // that will hijack the events is a simple expression:
3944 //
3945 // (lldb) expr (int)puts("hello")
3946 //
3947 // This will cause the internal process state thread to resume and halt
3948 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3949 // events) and we do need the IO handler to be pushed and popped
3950 // correctly.
3951
3952 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
3953 PopProcessIOHandler ();
3954 }
3955 }
Jim Ingham9575d842011-03-11 03:53:59 +00003956
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957 BroadcastEvent (event_sp);
3958 }
3959 else
3960 {
3961 if (log)
3962 {
Daniel Malead01b2952012-11-29 21:49:15 +00003963 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003964 __FUNCTION__,
3965 GetID(),
3966 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003967 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003968 }
3969 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003970 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971}
3972
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003973thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003974Process::PrivateStateThread (void *arg)
3975{
3976 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003977 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978 return result;
3979}
3980
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003981thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982Process::RunPrivateStateThread ()
3983{
Jim Ingham076b3042012-04-10 01:21:57 +00003984 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003985 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003986
Greg Clayton5160ce52013-03-27 23:08:40 +00003987 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003989 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3990 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991
3992 bool exit_now = false;
3993 while (!exit_now)
3994 {
3995 EventSP event_sp;
3996 WaitForEventsPrivate (NULL, event_sp, control_only);
3997 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3998 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003999 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004000 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4001 __FUNCTION__, static_cast<void*>(this), GetID(),
4002 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004003
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004004 switch (event_sp->GetType())
4005 {
4006 case eBroadcastInternalStateControlStop:
4007 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004008 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004009
4010 case eBroadcastInternalStateControlPause:
4011 control_only = true;
4012 break;
4013
4014 case eBroadcastInternalStateControlResume:
4015 control_only = false;
4016 break;
4017 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004018
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004019 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004020 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004021 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004022 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4023 {
4024 if (m_public_state.GetValue() == eStateAttaching)
4025 {
4026 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004027 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4028 __FUNCTION__, static_cast<void*>(this),
4029 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004030 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4031 }
4032 else
4033 {
4034 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004035 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4036 __FUNCTION__, static_cast<void*>(this),
4037 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004038 Halt();
4039 }
4040 continue;
4041 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042
4043 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4044
4045 if (internal_state != eStateInvalid)
4046 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004047 if (m_clear_thread_plans_on_stop &&
4048 StateIsStoppedState(internal_state, true))
4049 {
4050 m_clear_thread_plans_on_stop = false;
4051 m_thread_list.DiscardThreadPlans();
4052 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053 HandlePrivateEvent (event_sp);
4054 }
4055
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004056 if (internal_state == eStateInvalid ||
4057 internal_state == eStateExited ||
4058 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004059 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004060 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004061 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4062 __FUNCTION__, static_cast<void*>(this), GetID(),
4063 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004065 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004067 }
4068
Caroline Tice20ad3c42010-10-29 21:48:37 +00004069 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004070 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004071 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4072 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004073
Ed Maste64fad602013-07-29 20:58:06 +00004074 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004075 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4076 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004077 return NULL;
4078}
4079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004080//------------------------------------------------------------------
4081// Process Event Data
4082//------------------------------------------------------------------
4083
4084Process::ProcessEventData::ProcessEventData () :
4085 EventData (),
4086 m_process_sp (),
4087 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004088 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004089 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004090 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091{
4092}
4093
4094Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4095 EventData (),
4096 m_process_sp (process_sp),
4097 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004098 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004099 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004100 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004101{
4102}
4103
4104Process::ProcessEventData::~ProcessEventData()
4105{
4106}
4107
4108const ConstString &
4109Process::ProcessEventData::GetFlavorString ()
4110{
4111 static ConstString g_flavor ("Process::ProcessEventData");
4112 return g_flavor;
4113}
4114
4115const ConstString &
4116Process::ProcessEventData::GetFlavor () const
4117{
4118 return ProcessEventData::GetFlavorString ();
4119}
4120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121void
4122Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4123{
4124 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004125 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4126 // the public event queue, then other times when we're pretending that this is where we stopped at the
4127 // end of expression evaluation. m_update_state is used to distinguish these
4128 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004129 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004130 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004132
Jim Ingham221d51c2013-05-08 00:35:16 +00004133 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004134
4135 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4136 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4137 // end up restarting the process.
4138 if (m_interrupted)
4139 return;
4140
4141 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004142 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004143 {
4144 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004145 uint32_t num_threads = curr_thread_list.GetSize();
4146 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004147
Jim Ingham4b536182011-08-09 02:12:22 +00004148 // The actions might change one of the thread's stop_info's opinions about whether we should
4149 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004150
4151 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4152 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4153 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4154 // 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
4155 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004156 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004157 for (idx = 0; idx < num_threads; ++idx)
4158 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4159
Jim Inghamc7078c22012-12-13 22:24:15 +00004160 // Use this to track whether we should continue from here. We will only continue the target running if
4161 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4162 // then it doesn't matter what the other threads say...
4163
4164 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004165
Jim Ingham0ad7e052013-04-25 02:04:59 +00004166 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4167 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4168 // thing to do is, and it's better to let the user decide than continue behind their backs.
4169
4170 bool does_anybody_have_an_opinion = false;
4171
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004172 for (idx = 0; idx < num_threads; ++idx)
4173 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004174 curr_thread_list = m_process_sp->GetThreadList();
4175 if (curr_thread_list.GetSize() != num_threads)
4176 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004177 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004178 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004179 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 +00004180 break;
4181 }
4182
4183 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4184
4185 if (thread_sp->GetIndexID() != thread_index_array[idx])
4186 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004187 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004188 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004189 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004190 idx,
4191 thread_index_array[idx],
4192 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004193 break;
4194 }
4195
Jim Inghamb15bfc72010-10-20 00:39:53 +00004196 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004197 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004198 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004199 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004200 bool this_thread_wants_to_stop;
4201 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004202 {
Jim Ingham0161b492013-02-09 01:29:05 +00004203 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4204 }
4205 else
4206 {
4207 stop_info_sp->PerformAction(event_ptr);
4208 // The stop action might restart the target. If it does, then we want to mark that in the
4209 // event so that whoever is receiving it will know to wait for the running event and reflect
4210 // that state appropriately.
4211 // We also need to stop processing actions, since they aren't expecting the target to be running.
4212
4213 // FIXME: we might have run.
4214 if (stop_info_sp->HasTargetRunSinceMe())
4215 {
4216 SetRestarted (true);
4217 break;
4218 }
4219
4220 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004221 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004222
Jim Inghamc7078c22012-12-13 22:24:15 +00004223 if (still_should_stop == false)
4224 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225 }
4226 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004227
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004228
Jim Inghama8ca6e22013-05-03 23:04:37 +00004229 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004230 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004231 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004232 {
4233 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004234 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004235 // Use the public resume method here, since this is just
4236 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004237 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004238 }
4239 else
4240 {
4241 // If we didn't restart, run the Stop Hooks here:
4242 // They might also restart the target, so watch for that.
4243 m_process_sp->GetTarget().RunStopHooks();
4244 if (m_process_sp->GetPrivateState() == eStateRunning)
4245 SetRestarted(true);
4246 }
Jim Ingham9575d842011-03-11 03:53:59 +00004247 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004248 }
4249}
4250
4251void
4252Process::ProcessEventData::Dump (Stream *s) const
4253{
4254 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004255 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4256 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004257
Greg Clayton8b82f082011-04-12 05:54:46 +00004258 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004259}
4260
4261const Process::ProcessEventData *
4262Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4263{
4264 if (event_ptr)
4265 {
4266 const EventData *event_data = event_ptr->GetData();
4267 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4268 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4269 }
4270 return NULL;
4271}
4272
4273ProcessSP
4274Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4275{
4276 ProcessSP process_sp;
4277 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4278 if (data)
4279 process_sp = data->GetProcessSP();
4280 return process_sp;
4281}
4282
4283StateType
4284Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4285{
4286 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4287 if (data == NULL)
4288 return eStateInvalid;
4289 else
4290 return data->GetState();
4291}
4292
4293bool
4294Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4295{
4296 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4297 if (data == NULL)
4298 return false;
4299 else
4300 return data->GetRestarted();
4301}
4302
4303void
4304Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4305{
4306 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4307 if (data != NULL)
4308 data->SetRestarted(new_value);
4309}
4310
Jim Ingham0161b492013-02-09 01:29:05 +00004311size_t
4312Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4313{
4314 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4315 if (data != NULL)
4316 return data->GetNumRestartedReasons();
4317 else
4318 return 0;
4319}
4320
4321const char *
4322Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4323{
4324 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4325 if (data != NULL)
4326 return data->GetRestartedReasonAtIndex(idx);
4327 else
4328 return NULL;
4329}
4330
4331void
4332Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4333{
4334 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4335 if (data != NULL)
4336 data->AddRestartedReason(reason);
4337}
4338
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004339bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004340Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4341{
4342 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4343 if (data == NULL)
4344 return false;
4345 else
4346 return data->GetInterrupted ();
4347}
4348
4349void
4350Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4351{
4352 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4353 if (data != NULL)
4354 data->SetInterrupted(new_value);
4355}
4356
4357bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004358Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4359{
4360 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4361 if (data)
4362 {
4363 data->SetUpdateStateOnRemoval();
4364 return true;
4365 }
4366 return false;
4367}
4368
Greg Claytond9e416c2012-02-18 05:35:26 +00004369lldb::TargetSP
4370Process::CalculateTarget ()
4371{
4372 return m_target.shared_from_this();
4373}
4374
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004375void
Greg Clayton0603aa92010-10-04 01:05:56 +00004376Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004377{
Greg Claytonc14ee322011-09-22 04:58:26 +00004378 exe_ctx.SetTargetPtr (&m_target);
4379 exe_ctx.SetProcessPtr (this);
4380 exe_ctx.SetThreadPtr(NULL);
4381 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004382}
4383
Greg Claytone996fd32011-03-08 22:40:15 +00004384//uint32_t
4385//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4386//{
4387// return 0;
4388//}
4389//
4390//ArchSpec
4391//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4392//{
4393// return Host::GetArchSpecForExistingProcess (pid);
4394//}
4395//
4396//ArchSpec
4397//Process::GetArchSpecForExistingProcess (const char *process_name)
4398//{
4399// return Host::GetArchSpecForExistingProcess (process_name);
4400//}
4401//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004402void
4403Process::AppendSTDOUT (const char * s, size_t len)
4404{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004405 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004406 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004407 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004408}
4409
4410void
Greg Clayton93e86192011-11-13 04:45:22 +00004411Process::AppendSTDERR (const char * s, size_t len)
4412{
4413 Mutex::Locker locker (m_stdio_communication_mutex);
4414 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004415 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004416}
4417
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004418void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004419Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004420{
4421 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004422 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004423 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4424}
4425
4426size_t
4427Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4428{
4429 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004430 if (m_profile_data.empty())
4431 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004432
4433 std::string &one_profile_data = m_profile_data.front();
4434 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004435 if (bytes_available > 0)
4436 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004437 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004438 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004439 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4440 static_cast<void*>(buf),
4441 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004442 if (bytes_available > buf_size)
4443 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004444 memcpy(buf, one_profile_data.c_str(), buf_size);
4445 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004446 bytes_available = buf_size;
4447 }
4448 else
4449 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004450 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004451 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004452 }
4453 }
4454 return bytes_available;
4455}
4456
4457
Greg Clayton93e86192011-11-13 04:45:22 +00004458//------------------------------------------------------------------
4459// Process STDIO
4460//------------------------------------------------------------------
4461
4462size_t
4463Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4464{
4465 Mutex::Locker locker(m_stdio_communication_mutex);
4466 size_t bytes_available = m_stdout_data.size();
4467 if (bytes_available > 0)
4468 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004469 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004470 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004471 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4472 static_cast<void*>(buf),
4473 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004474 if (bytes_available > buf_size)
4475 {
4476 memcpy(buf, m_stdout_data.c_str(), buf_size);
4477 m_stdout_data.erase(0, buf_size);
4478 bytes_available = buf_size;
4479 }
4480 else
4481 {
4482 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4483 m_stdout_data.clear();
4484 }
4485 }
4486 return bytes_available;
4487}
4488
4489
4490size_t
4491Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4492{
4493 Mutex::Locker locker(m_stdio_communication_mutex);
4494 size_t bytes_available = m_stderr_data.size();
4495 if (bytes_available > 0)
4496 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004497 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004498 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004499 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4500 static_cast<void*>(buf),
4501 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004502 if (bytes_available > buf_size)
4503 {
4504 memcpy(buf, m_stderr_data.c_str(), buf_size);
4505 m_stderr_data.erase(0, buf_size);
4506 bytes_available = buf_size;
4507 }
4508 else
4509 {
4510 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4511 m_stderr_data.clear();
4512 }
4513 }
4514 return bytes_available;
4515}
4516
4517void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004518Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4519{
4520 Process *process = (Process *) baton;
4521 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4522}
4523
Greg Clayton44d93782014-01-27 23:43:24 +00004524class IOHandlerProcessSTDIO :
4525 public IOHandler
4526{
4527public:
4528 IOHandlerProcessSTDIO (Process *process,
4529 int write_fd) :
4530 IOHandler(process->GetTarget().GetDebugger()),
4531 m_process (process),
4532 m_read_file (),
4533 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004534 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004535 {
4536 m_read_file.SetDescriptor(GetInputFD(), false);
4537 }
4538
4539 virtual
4540 ~IOHandlerProcessSTDIO ()
4541 {
4542
4543 }
4544
4545 bool
4546 OpenPipes ()
4547 {
Greg Clayton100eb932014-07-02 21:10:39 +00004548 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004549 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004550 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004551 }
4552
4553 void
4554 ClosePipes()
4555 {
Greg Clayton100eb932014-07-02 21:10:39 +00004556 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004557 }
4558
4559 // Each IOHandler gets to run until it is done. It should read data
4560 // from the "in" and place output into "out" and "err and return
4561 // when done.
4562 virtual void
4563 Run ()
4564 {
4565 if (m_read_file.IsValid() && m_write_file.IsValid())
4566 {
4567 SetIsDone(false);
4568 if (OpenPipes())
4569 {
4570 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004571 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004572 TerminalState terminal_state;
4573 terminal_state.Save (read_fd, false);
4574 Terminal terminal(read_fd);
4575 terminal.SetCanonical(false);
4576 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004577// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004578#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004579 while (!GetIsDone())
4580 {
4581 fd_set read_fdset;
4582 FD_ZERO (&read_fdset);
4583 FD_SET (read_fd, &read_fdset);
4584 FD_SET (pipe_read_fd, &read_fdset);
4585 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4586 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4587 if (num_set_fds < 0)
4588 {
4589 const int select_errno = errno;
4590
4591 if (select_errno != EINTR)
4592 SetIsDone(true);
4593 }
4594 else if (num_set_fds > 0)
4595 {
4596 char ch = 0;
4597 size_t n;
4598 if (FD_ISSET (read_fd, &read_fdset))
4599 {
4600 n = 1;
4601 if (m_read_file.Read(&ch, n).Success() && n == 1)
4602 {
4603 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4604 SetIsDone(true);
4605 }
4606 else
4607 SetIsDone(true);
4608 }
4609 if (FD_ISSET (pipe_read_fd, &read_fdset))
4610 {
4611 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004612 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004613 {
Greg Clayton100eb932014-07-02 21:10:39 +00004614 switch (ch)
4615 {
4616 case 'q':
4617 SetIsDone(true);
4618 break;
4619 case 'i':
4620 if (StateIsRunningState(m_process->GetState()))
4621 m_process->Halt();
4622 break;
4623 }
Greg Clayton19e11352014-02-26 22:47:33 +00004624 }
Greg Clayton44d93782014-01-27 23:43:24 +00004625 }
4626 }
4627 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004628#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004629 terminal_state.Restore();
4630
4631 }
4632 else
4633 SetIsDone(true);
4634 }
4635 else
4636 SetIsDone(true);
4637 }
4638
4639 // Hide any characters that have been displayed so far so async
4640 // output can be displayed. Refresh() will be called after the
4641 // output has been displayed.
4642 virtual void
4643 Hide ()
4644 {
4645
4646 }
4647 // Called when the async output has been received in order to update
4648 // the input reader (refresh the prompt and redisplay any current
4649 // line(s) that are being edited
4650 virtual void
4651 Refresh ()
4652 {
4653
4654 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004655
Greg Clayton44d93782014-01-27 23:43:24 +00004656 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004657 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004658 {
Greg Clayton19e11352014-02-26 22:47:33 +00004659 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004660 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004661 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004662
Greg Claytonf0066ad2014-05-02 00:45:31 +00004663 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004664 Interrupt ()
4665 {
Greg Clayton19e11352014-02-26 22:47:33 +00004666 // Do only things that are safe to do in an interrupt context (like in
4667 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4668 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4669 // that was written to the pipe and then call m_process->Halt() from a
4670 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004671 if (m_active)
4672 {
4673 char ch = 'i'; // Send 'i' for interrupt
4674 return m_pipe.Write (&ch, 1) == 1;
4675 }
4676 else
4677 {
4678 // This IOHandler might be pushed on the stack, but not being run currently
4679 // so do the right thing if we aren't actively watching for STDIN by sending
4680 // the interrupt to the process. Otherwise the write to the pipe above would
4681 // do nothing. This can happen when the command interpreter is running and
4682 // gets a "expression ...". It will be on the IOHandler thread and sending
4683 // the input is complete to the delegate which will cause the expression to
4684 // run, which will push the process IO handler, but not run it.
4685
4686 if (StateIsRunningState(m_process->GetState()))
4687 {
4688 m_process->SendAsyncInterrupt();
4689 return true;
4690 }
4691 }
4692 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004693 }
Greg Clayton44d93782014-01-27 23:43:24 +00004694
4695 virtual void
4696 GotEOF()
4697 {
4698
4699 }
4700
4701protected:
4702 Process *m_process;
4703 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4704 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004705 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004706};
4707
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004708void
Greg Clayton44d93782014-01-27 23:43:24 +00004709Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004710{
4711 // First set up the Read Thread for reading/handling process I/O
4712
Greg Clayton44d93782014-01-27 23:43:24 +00004713 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004714
4715 if (conn_ap.get())
4716 {
4717 m_stdio_communication.SetConnection (conn_ap.release());
4718 if (m_stdio_communication.IsConnected())
4719 {
4720 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4721 m_stdio_communication.StartReadThread();
4722
4723 // Now read thread is set up, set up input reader.
4724
4725 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004726 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004727 }
4728 }
4729}
4730
Greg Claytonb4874f12014-02-28 18:22:24 +00004731bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004732Process::ProcessIOHandlerIsActive ()
4733{
4734 IOHandlerSP io_handler_sp (m_process_input_reader);
4735 if (io_handler_sp)
4736 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4737 return false;
4738}
4739bool
Greg Clayton44d93782014-01-27 23:43:24 +00004740Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004741{
Greg Clayton44d93782014-01-27 23:43:24 +00004742 IOHandlerSP io_handler_sp (m_process_input_reader);
4743 if (io_handler_sp)
4744 {
4745 io_handler_sp->SetIsDone(false);
4746 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004747 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004748 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004749 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004750}
4751
Greg Claytonb4874f12014-02-28 18:22:24 +00004752bool
Greg Clayton44d93782014-01-27 23:43:24 +00004753Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004754{
Greg Clayton44d93782014-01-27 23:43:24 +00004755 IOHandlerSP io_handler_sp (m_process_input_reader);
4756 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004757 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4758 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004759}
4760
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004761// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004762void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004763Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004764{
Greg Clayton6920b522012-08-22 18:39:03 +00004765 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004766}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004767
Greg Clayton99d0faf2010-11-18 23:32:35 +00004768void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004769Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004770{
Greg Clayton6920b522012-08-22 18:39:03 +00004771 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004772}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004773
Jim Ingham1624a2d2014-05-05 02:26:40 +00004774ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004775Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004776 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004777 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004778 Stream &errors)
4779{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004780 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004781
Jim Ingham77787032011-01-20 02:03:18 +00004782 if (thread_plan_sp.get() == NULL)
4783 {
4784 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004785 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004786 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004787
Jim Ingham7d7931d2013-03-28 00:05:34 +00004788 if (!thread_plan_sp->ValidatePlan(NULL))
4789 {
4790 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004791 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004792 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004793
Greg Claytonc14ee322011-09-22 04:58:26 +00004794 if (exe_ctx.GetProcessPtr() != this)
4795 {
4796 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004797 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004798 }
4799
4800 Thread *thread = exe_ctx.GetThreadPtr();
4801 if (thread == NULL)
4802 {
4803 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004804 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004805 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004806
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004807 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4808 // For that to be true the plan can't be private - since private plans suppress themselves in the
4809 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004810
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004811 bool orig_plan_private = thread_plan_sp->GetPrivate();
4812 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004813
Jim Ingham444586b2011-01-24 06:34:17 +00004814 if (m_private_state.GetValue() != eStateStopped)
4815 {
4816 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004817 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004818 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004819
Jim Ingham66243842011-08-13 00:56:10 +00004820 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004821 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004822 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004823 if (!selected_frame_sp)
4824 {
4825 thread->SetSelectedFrame(0);
4826 selected_frame_sp = thread->GetSelectedFrame();
4827 if (!selected_frame_sp)
4828 {
4829 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004830 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004831 }
4832 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004833
Jim Ingham11b0e052013-02-19 23:22:45 +00004834 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004835
4836 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4837 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004838
Greg Claytonc14ee322011-09-22 04:58:26 +00004839 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004840
Jim Ingham66243842011-08-13 00:56:10 +00004841 uint32_t selected_tid;
4842 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004843 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004844 {
4845 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004846 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004847 }
4848 else
4849 {
4850 selected_tid = LLDB_INVALID_THREAD_ID;
4851 }
4852
Jim Ingham372787f2012-04-07 00:00:41 +00004853 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004854 lldb::StateType old_state;
4855 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004856
Greg Clayton5160ce52013-03-27 23:08:40 +00004857 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004858 if (Host::GetCurrentThread() == m_private_state_thread)
4859 {
Jim Ingham076b3042012-04-10 01:21:57 +00004860 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4861 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004862 // 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 +00004863 // we are fielding public events here.
4864 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004865 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 +00004866
Jim Ingham372787f2012-04-07 00:00:41 +00004867 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004868
4869 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4870 // returning control here.
4871 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4872 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4873 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4874 // do just what we want.
4875 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4876 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4877 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4878 old_state = m_public_state.GetValue();
4879 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004880
Jim Ingham076b3042012-04-10 01:21:57 +00004881 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004882 StartPrivateStateThread(true);
4883 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004884
Jim Ingham372787f2012-04-07 00:00:41 +00004885 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004886
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004887 if (options.GetDebug())
4888 {
4889 // In this case, we aren't actually going to run, we just want to stop right away.
4890 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4891 // FIXME: To make this prettier we should invent some stop reason for this, but that
4892 // is only cosmetic, and this functionality is only of use to lldb developers who can
4893 // live with not pretty...
4894 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004895 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004896 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004897
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004898 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004899
Sean Callanana46ec452012-07-11 21:31:24 +00004900 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004901
Jim Ingham77787032011-01-20 02:03:18 +00004902 {
Sean Callanana46ec452012-07-11 21:31:24 +00004903 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4904 // restored on exit to the function.
4905 //
4906 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4907 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004908
Sean Callanana46ec452012-07-11 21:31:24 +00004909 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004910
Jim Inghamf48169b2010-11-30 02:22:11 +00004911 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004912 {
4913 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004914 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004915 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004916 thread->GetIndexID(),
4917 thread->GetID(),
4918 s.GetData());
4919 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004920
Sean Callanana46ec452012-07-11 21:31:24 +00004921 bool got_event;
4922 lldb::EventSP event_sp;
4923 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004924
Sean Callanana46ec452012-07-11 21:31:24 +00004925 TimeValue* timeout_ptr = NULL;
4926 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004927
Jim Ingham0161b492013-02-09 01:29:05 +00004928 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 +00004929 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004930 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004931 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004932
Jim Ingham0161b492013-02-09 01:29:05 +00004933 // This is just for accounting:
4934 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004935
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004936 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00004937 uint32_t one_thread_timeout_usec;
4938 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00004939
4940 // If we are going to run all threads the whole time, or if we are only going to run one thread,
4941 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
4942 // first timeout already.
4943
4944 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00004945 {
4946 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00004947 one_thread_timeout_usec = 0;
4948 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00004949 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004950 else
Jim Ingham0161b492013-02-09 01:29:05 +00004951 {
Jim Inghamfd95f892014-04-22 01:41:52 +00004952 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004953
Jim Ingham914f4e72014-03-28 21:58:28 +00004954 // If the overall wait is forever, then we only need to set the one thread timeout:
4955 if (timeout_usec == 0)
4956 {
Ed Maste801335c2014-03-31 19:28:14 +00004957 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00004958 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00004959 else
Jim Inghamfd95f892014-04-22 01:41:52 +00004960 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00004961 }
Jim Ingham0161b492013-02-09 01:29:05 +00004962 else
4963 {
Jim Ingham914f4e72014-03-28 21:58:28 +00004964 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
4965 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
4966 uint64_t computed_one_thread_timeout;
4967 if (option_one_thread_timeout != 0)
4968 {
4969 if (timeout_usec < option_one_thread_timeout)
4970 {
4971 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004972 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00004973 }
4974 computed_one_thread_timeout = option_one_thread_timeout;
4975 }
4976 else
4977 {
4978 computed_one_thread_timeout = timeout_usec / 2;
4979 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
4980 computed_one_thread_timeout = default_one_thread_timeout_usec;
4981 }
Jim Inghamfd95f892014-04-22 01:41:52 +00004982 one_thread_timeout_usec = computed_one_thread_timeout;
4983 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
4984
Jim Ingham0161b492013-02-09 01:29:05 +00004985 }
Jim Ingham0161b492013-02-09 01:29:05 +00004986 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004987
4988 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00004989 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 +00004990 options.GetStopOthers(),
4991 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00004992 before_first_timeout,
4993 one_thread_timeout_usec,
4994 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00004995
Jim Ingham1460e4b2014-01-10 23:46:59 +00004996 // This isn't going to work if there are unfetched events on the queue.
4997 // Are there cases where we might want to run the remaining events here, and then try to
4998 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004999
Jim Ingham1460e4b2014-01-10 23:46:59 +00005000 Event *other_events = listener.PeekAtNextEvent();
5001 if (other_events != NULL)
5002 {
5003 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005004 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005005 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005006
Jim Ingham1460e4b2014-01-10 23:46:59 +00005007 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5008 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5009 // event coalescing to cause us to lose OUR running event...
5010 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005011
Jim Ingham8559a352012-11-26 23:52:18 +00005012 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5013 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005014
5015#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5016 // It's pretty much impossible to write test cases for things like:
5017 // One thread timeout expires, I go to halt, but the process already stopped
5018 // on the function call stop breakpoint. Turning on this define will make us not
5019 // fetch the first event till after the halt. So if you run a quick function, it will have
5020 // completed, and the completion event will be waiting, when you interrupt for halt.
5021 // The expression evaluation should still succeed.
5022 bool miss_first_event = true;
5023#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005024 TimeValue one_thread_timeout;
5025 TimeValue final_timeout;
5026
Jim Ingham35878c42014-04-08 21:33:21 +00005027
Sean Callanana46ec452012-07-11 21:31:24 +00005028 while (1)
5029 {
5030 // We usually want to resume the process if we get to the top of the loop.
5031 // The only exception is if we get two running events with no intervening
5032 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005033 if (log)
5034 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5035 do_resume,
5036 handle_running_event,
5037 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005038
Jim Ingham184e9812013-01-15 02:47:48 +00005039 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005040 {
5041 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005042
Jim Ingham184e9812013-01-15 02:47:48 +00005043 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005044 {
Jim Ingham0161b492013-02-09 01:29:05 +00005045 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005046 Error resume_error = PrivateResume ();
5047 if (!resume_error.Success())
5048 {
Jim Ingham0161b492013-02-09 01:29:05 +00005049 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5050 num_resumes,
5051 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005052 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005053 break;
5054 }
Sean Callanana46ec452012-07-11 21:31:24 +00005055 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005056
Jim Ingham0161b492013-02-09 01:29:05 +00005057 TimeValue resume_timeout = TimeValue::Now();
5058 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005059
Jim Ingham0161b492013-02-09 01:29:05 +00005060 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005061 if (!got_event)
5062 {
5063 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005064 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5065 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005066
Jim Ingham0161b492013-02-09 01:29:05 +00005067 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005068 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005069 break;
5070 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005071
Sean Callanana46ec452012-07-11 21:31:24 +00005072 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005073
Sean Callanana46ec452012-07-11 21:31:24 +00005074 if (stop_state != eStateRunning)
5075 {
Jim Ingham0161b492013-02-09 01:29:05 +00005076 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005077
Jim Ingham0161b492013-02-09 01:29:05 +00005078 if (stop_state == eStateStopped)
5079 {
5080 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5081 if (log)
5082 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5083 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5084 num_resumes,
5085 StateAsCString(stop_state),
5086 restarted,
5087 do_resume,
5088 handle_running_event);
5089 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005090
Jim Ingham0161b492013-02-09 01:29:05 +00005091 if (restarted)
5092 {
5093 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5094 // event here. But if I do, the best thing is to Halt and then get out of here.
5095 Halt();
5096 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005097
Jim Ingham35e1bda2012-10-16 21:41:58 +00005098 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5099 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005100 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005101 break;
5102 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005103
Sean Callanana46ec452012-07-11 21:31:24 +00005104 if (log)
5105 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5106 // We need to call the function synchronously, so spin waiting for it to return.
5107 // If we get interrupted while executing, we're going to lose our context, and
5108 // won't be able to gather the result at this point.
5109 // We set the timeout AFTER the resume, since the resume takes some time and we
5110 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005111 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005112 else
5113 {
Sean Callanana46ec452012-07-11 21:31:24 +00005114 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005115 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005116 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005117
Jim Ingham0161b492013-02-09 01:29:05 +00005118 if (before_first_timeout)
5119 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005120 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005121 {
5122 one_thread_timeout = TimeValue::Now();
5123 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005124 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005125 }
Jim Ingham0161b492013-02-09 01:29:05 +00005126 else
5127 {
5128 if (timeout_usec == 0)
5129 timeout_ptr = NULL;
5130 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005131 {
5132 final_timeout = TimeValue::Now();
5133 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005134 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005135 }
Jim Ingham0161b492013-02-09 01:29:05 +00005136 }
5137 }
5138 else
5139 {
5140 if (timeout_usec == 0)
5141 timeout_ptr = NULL;
5142 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005143 {
5144 final_timeout = TimeValue::Now();
5145 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005146 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005147 }
Jim Ingham0161b492013-02-09 01:29:05 +00005148 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005149
Jim Ingham0161b492013-02-09 01:29:05 +00005150 do_resume = true;
5151 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005152
Sean Callanana46ec452012-07-11 21:31:24 +00005153 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005154 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005155
Jim Ingham0f16e732011-02-08 05:20:59 +00005156 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005157 {
Sean Callanana46ec452012-07-11 21:31:24 +00005158 if (timeout_ptr)
5159 {
Matt Kopec676a4872013-02-21 23:55:31 +00005160 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005161 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5162 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005163 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005164 else
Sean Callanana46ec452012-07-11 21:31:24 +00005165 {
5166 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5167 }
5168 }
Jim Ingham35878c42014-04-08 21:33:21 +00005169
5170#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5171 // See comment above...
5172 if (miss_first_event)
5173 {
5174 usleep(1000);
5175 miss_first_event = false;
5176 got_event = false;
5177 }
5178 else
5179#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005180 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005181
Sean Callanana46ec452012-07-11 21:31:24 +00005182 if (got_event)
5183 {
5184 if (event_sp.get())
5185 {
5186 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005187 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005188 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005189 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005190 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005191 errors.Printf ("Execution halted by user interrupt.");
5192 if (log)
5193 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005194 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005195 }
5196 else
5197 {
5198 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5199 if (log)
5200 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005201
Jim Inghamcfc09352012-07-27 23:57:19 +00005202 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005203 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005204 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005205 {
Jim Ingham0161b492013-02-09 01:29:05 +00005206 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005207 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5208 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005209 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005210 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005211 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005212 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005213 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005214 }
5215 else
5216 {
Jim Ingham0161b492013-02-09 01:29:05 +00005217 // If we were restarted, we just need to go back up to fetch another event.
5218 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005219 {
5220 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005221 {
5222 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5223 }
5224 keep_going = true;
5225 do_resume = false;
5226 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005227
Jim Inghamcfc09352012-07-27 23:57:19 +00005228 }
5229 else
5230 {
Jim Ingham0161b492013-02-09 01:29:05 +00005231 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5232 StopReason stop_reason = eStopReasonInvalid;
5233 if (stop_info_sp)
5234 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005235
Jim Ingham0161b492013-02-09 01:29:05 +00005236 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5237 // it is OUR plan that is complete?
5238 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005239 {
5240 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005241 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5242 // Now mark this plan as private so it doesn't get reported as the stop reason
5243 // after this point.
5244 if (thread_plan_sp)
5245 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005246 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005247 }
5248 else
5249 {
Jim Ingham0161b492013-02-09 01:29:05 +00005250 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005251 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005252 {
5253 if (log)
5254 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005255 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005256 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005257 {
5258 event_to_broadcast_sp = event_sp;
5259 }
Jim Ingham0161b492013-02-09 01:29:05 +00005260 }
Jim Ingham184e9812013-01-15 02:47:48 +00005261 else
Jim Ingham0161b492013-02-09 01:29:05 +00005262 {
5263 if (log)
5264 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005265 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005266 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005267 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005268 }
Jim Ingham184e9812013-01-15 02:47:48 +00005269 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005270 }
Sean Callanana46ec452012-07-11 21:31:24 +00005271 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005272 }
5273 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005274
Jim Inghamcfc09352012-07-27 23:57:19 +00005275 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005276 // This shouldn't really happen, but sometimes we do get two running events without an
5277 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005278 do_resume = false;
5279 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005280 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005281 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005282
Jim Inghamcfc09352012-07-27 23:57:19 +00005283 default:
5284 if (log)
5285 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005286
Jim Inghamcfc09352012-07-27 23:57:19 +00005287 if (stop_state == eStateExited)
5288 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005289
Sean Callananbf154da2012-08-08 17:35:10 +00005290 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005291 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005292 break;
5293 }
Sean Callanana46ec452012-07-11 21:31:24 +00005294 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005295
Sean Callanana46ec452012-07-11 21:31:24 +00005296 if (keep_going)
5297 continue;
5298 else
5299 break;
5300 }
5301 else
5302 {
5303 if (log)
5304 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005305 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005306 break;
5307 }
5308 }
5309 else
5310 {
5311 // If we didn't get an event that means we've timed out...
5312 // We will interrupt the process here. Depending on what we were asked to do we will
5313 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005314
Sean Callanana46ec452012-07-11 21:31:24 +00005315 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005316 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005317 {
Jim Ingham0161b492013-02-09 01:29:05 +00005318 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005319 {
5320 if (timeout_usec != 0)
5321 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005322 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005323 "running for %" PRIu32 " usec with all threads enabled.",
5324 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005325 }
5326 else
5327 {
5328 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005329 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005330 }
5331 }
Sean Callanana46ec452012-07-11 21:31:24 +00005332 else
5333 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005334 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005335 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005336 }
5337 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005338 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005339 "abandoning execution.",
5340 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005341 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005342
Jim Ingham0161b492013-02-09 01:29:05 +00005343 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5344 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5345 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5346 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5347 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005348
Jim Ingham0161b492013-02-09 01:29:05 +00005349 bool back_to_top = true;
5350 uint32_t try_halt_again = 0;
5351 bool do_halt = true;
5352 const uint32_t num_retries = 5;
5353 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005354 {
Jim Ingham0161b492013-02-09 01:29:05 +00005355 Error halt_error;
5356 if (do_halt)
5357 {
5358 if (log)
5359 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5360 halt_error = Halt();
5361 }
5362 if (halt_error.Success())
5363 {
5364 if (log)
5365 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005366
Jim Ingham0161b492013-02-09 01:29:05 +00005367 real_timeout = TimeValue::Now();
5368 real_timeout.OffsetWithMicroSeconds(500000);
5369
5370 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005371
Jim Ingham0161b492013-02-09 01:29:05 +00005372 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005373 {
Jim Ingham0161b492013-02-09 01:29:05 +00005374 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5375 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005376 {
Jim Ingham0161b492013-02-09 01:29:05 +00005377 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5378 if (stop_state == lldb::eStateStopped
5379 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5380 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005381 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005382
Jim Ingham0161b492013-02-09 01:29:05 +00005383 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005384 {
Jim Ingham0161b492013-02-09 01:29:05 +00005385 // Between the time we initiated the Halt and the time we delivered it, the process could have
5386 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005387
Jim Ingham0161b492013-02-09 01:29:05 +00005388 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5389 {
5390 if (log)
5391 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5392 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005393 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005394 back_to_top = false;
5395 break;
5396 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005397
Jim Ingham0161b492013-02-09 01:29:05 +00005398 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5399 {
5400 if (log)
5401 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5402 "Exiting wait loop.");
5403 try_halt_again++;
5404 do_halt = false;
5405 continue;
5406 }
Sean Callanana46ec452012-07-11 21:31:24 +00005407
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005408 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005409 {
5410 if (log)
5411 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005412 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005413 back_to_top = false;
5414 break;
5415 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005416
Jim Ingham0161b492013-02-09 01:29:05 +00005417 if (before_first_timeout)
5418 {
5419 // Set all the other threads to run, and return to the top of the loop, which will continue;
5420 before_first_timeout = false;
5421 thread_plan_sp->SetStopOthers (false);
5422 if (log)
5423 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005424
Jim Ingham0161b492013-02-09 01:29:05 +00005425 back_to_top = true;
5426 break;
5427 }
5428 else
5429 {
5430 // Running all threads failed, so return Interrupted.
5431 if (log)
5432 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005433 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005434 back_to_top = false;
5435 break;
5436 }
Sean Callanana46ec452012-07-11 21:31:24 +00005437 }
5438 }
5439 else
Jim Ingham0161b492013-02-09 01:29:05 +00005440 { if (log)
5441 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5442 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005443 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005444 back_to_top = false;
5445 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005446 }
5447 }
Jim Ingham0161b492013-02-09 01:29:05 +00005448 else
5449 {
5450 try_halt_again++;
5451 continue;
5452 }
Sean Callanana46ec452012-07-11 21:31:24 +00005453 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005454
Jim Ingham0161b492013-02-09 01:29:05 +00005455 if (!back_to_top || try_halt_again > num_retries)
5456 break;
5457 else
5458 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005459 }
Sean Callanana46ec452012-07-11 21:31:24 +00005460 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005461
Sean Callanana46ec452012-07-11 21:31:24 +00005462 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5463 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5464 {
5465 StopPrivateStateThread();
5466 Error error;
5467 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005468 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005469 {
5470 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5471 }
5472 m_public_state.SetValueNoLock(old_state);
5473
5474 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005475
Jim Ingham184e9812013-01-15 02:47:48 +00005476 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5477 // could happen:
5478 // 1) The execution successfully completed
5479 // 2) We hit a breakpoint, and ignore_breakpoints was true
5480 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005481 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5482 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005483
Jim Ingham8646d3c2014-05-05 02:47:44 +00005484 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005485 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005486 {
5487 thread_plan_sp->RestoreThreadState();
5488 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005489
Sean Callanana46ec452012-07-11 21:31:24 +00005490 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005491 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005492 {
5493 if (log)
5494 {
5495 StreamString s;
5496 if (event_sp)
5497 event_sp->Dump (&s);
5498 else
5499 {
5500 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5501 }
5502
5503 StreamString ts;
5504
5505 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005506
Sean Callanana46ec452012-07-11 21:31:24 +00005507 do
5508 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005509 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005510 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005511 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005512 break;
5513 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005514 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005515 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005516 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005517 break;
5518 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005519 else
Sean Callanana46ec452012-07-11 21:31:24 +00005520 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005521 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5522
5523 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005524 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005525 event_explanation = "<no event data>";
5526 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005527 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005528
Jim Inghamcfc09352012-07-27 23:57:19 +00005529 Process *process = event_data->GetProcessSP().get();
5530
5531 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005532 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005533 event_explanation = "<no process>";
5534 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005535 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005536
Jim Inghamcfc09352012-07-27 23:57:19 +00005537 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005538
Jim Inghamcfc09352012-07-27 23:57:19 +00005539 uint32_t num_threads = thread_list.GetSize();
5540 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005541
Jim Inghamcfc09352012-07-27 23:57:19 +00005542 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005543
Jim Inghamcfc09352012-07-27 23:57:19 +00005544 for (thread_index = 0;
5545 thread_index < num_threads;
5546 ++thread_index)
5547 {
5548 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005549
Jim Inghamcfc09352012-07-27 23:57:19 +00005550 if (!thread)
5551 {
5552 ts.Printf("<?> ");
5553 continue;
5554 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005555
Daniel Malead01b2952012-11-29 21:49:15 +00005556 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005557 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005558
Jim Inghamcfc09352012-07-27 23:57:19 +00005559 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005560 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005561 else
5562 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005563
Jim Inghamcfc09352012-07-27 23:57:19 +00005564 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5565 if (stop_info_sp)
5566 {
5567 const char *stop_desc = stop_info_sp->GetDescription();
5568 if (stop_desc)
5569 ts.PutCString (stop_desc);
5570 }
5571 ts.Printf(">");
5572 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005573
Jim Inghamcfc09352012-07-27 23:57:19 +00005574 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005575 }
Sean Callanana46ec452012-07-11 21:31:24 +00005576 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005577
Jim Inghamcfc09352012-07-27 23:57:19 +00005578 if (event_explanation)
5579 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005580 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005581 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5582 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005583
Jim Inghame4483cf2013-09-27 01:13:01 +00005584 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005585 {
5586 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005587 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5588 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005589 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5590 thread_plan_sp->SetPrivate (orig_plan_private);
5591 }
5592 else
5593 {
5594 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005595 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5596 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005597 }
5598 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005599 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005600 {
5601 if (log)
5602 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005603
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005604 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005605 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005606 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005607 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005608 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005609 }
5610 else
5611 {
Sean Callanana46ec452012-07-11 21:31:24 +00005612 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005613 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005614 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005615 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005616 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005617 }
5618 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5619 {
5620 if (log)
5621 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005622 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005623 }
5624 else
5625 {
5626 if (log)
5627 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005628 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005629 {
5630 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005631 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005632 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5633 thread_plan_sp->SetPrivate (orig_plan_private);
5634 }
5635 }
5636 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005637
Sean Callanana46ec452012-07-11 21:31:24 +00005638 // Thread we ran the function in may have gone away because we ran the target
5639 // Check that it's still there, and if it is put it back in the context. Also restore the
5640 // frame in the context if it is still present.
5641 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5642 if (thread)
5643 {
5644 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5645 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005646
Sean Callanana46ec452012-07-11 21:31:24 +00005647 // Also restore the current process'es selected frame & thread, since this function calling may
5648 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005649
Sean Callanana46ec452012-07-11 21:31:24 +00005650 if (selected_tid != LLDB_INVALID_THREAD_ID)
5651 {
5652 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5653 {
5654 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005655 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005656 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005657 if (old_frame_sp)
5658 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005659 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005660 }
5661 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005662
Sean Callanana46ec452012-07-11 21:31:24 +00005663 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005664
Sean Callanana46ec452012-07-11 21:31:24 +00005665 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005666 {
Sean Callanana46ec452012-07-11 21:31:24 +00005667 if (log)
5668 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5669 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005670 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005671
Jim Inghamf48169b2010-11-30 02:22:11 +00005672 return return_value;
5673}
5674
5675const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005676Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005677{
5678 const char *result_name;
5679
5680 switch (result)
5681 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005682 case eExpressionCompleted:
5683 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005684 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005685 case eExpressionDiscarded:
5686 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005687 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005688 case eExpressionInterrupted:
5689 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005690 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005691 case eExpressionHitBreakpoint:
5692 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005693 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005694 case eExpressionSetupError:
5695 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005696 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005697 case eExpressionParseError:
5698 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005699 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005700 case eExpressionResultUnavailable:
5701 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005702 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005703 case eExpressionTimedOut:
5704 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005705 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005706 case eExpressionStoppedForDebug:
5707 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005708 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005709 }
5710 return result_name;
5711}
5712
Greg Clayton7260f622011-04-18 08:33:37 +00005713void
5714Process::GetStatus (Stream &strm)
5715{
5716 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005717 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005718 {
5719 if (state == eStateExited)
5720 {
5721 int exit_status = GetExitStatus();
5722 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005723 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005724 GetID(),
5725 exit_status,
5726 exit_status,
5727 exit_description ? exit_description : "");
5728 }
5729 else
5730 {
5731 if (state == eStateConnected)
5732 strm.Printf ("Connected to remote target.\n");
5733 else
Daniel Malead01b2952012-11-29 21:49:15 +00005734 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005735 }
5736 }
5737 else
5738 {
Daniel Malead01b2952012-11-29 21:49:15 +00005739 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005740 }
5741}
5742
5743size_t
5744Process::GetThreadStatus (Stream &strm,
5745 bool only_threads_with_stop_reason,
5746 uint32_t start_frame,
5747 uint32_t num_frames,
5748 uint32_t num_frames_with_source)
5749{
5750 size_t num_thread_infos_dumped = 0;
5751
Jim Ingham4a65fb12014-03-07 11:20:03 +00005752 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5753 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5754 // ID's, and look them up one by one:
5755
5756 uint32_t num_threads;
5757 std::vector<uint32_t> thread_index_array;
5758 //Scope for thread list locker;
5759 {
5760 Mutex::Locker locker (GetThreadList().GetMutex());
5761 ThreadList &curr_thread_list = GetThreadList();
5762 num_threads = curr_thread_list.GetSize();
5763 uint32_t idx;
5764 thread_index_array.resize(num_threads);
5765 for (idx = 0; idx < num_threads; ++idx)
5766 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5767 }
5768
Greg Clayton7260f622011-04-18 08:33:37 +00005769 for (uint32_t i = 0; i < num_threads; i++)
5770 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005771 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5772 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005773 {
5774 if (only_threads_with_stop_reason)
5775 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005776 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005777 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005778 continue;
5779 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005780 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005781 start_frame,
5782 num_frames,
5783 num_frames_with_source);
5784 ++num_thread_infos_dumped;
5785 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005786 else
5787 {
5788 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5789 if (log)
5790 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5791
5792 }
Greg Clayton7260f622011-04-18 08:33:37 +00005793 }
5794 return num_thread_infos_dumped;
5795}
5796
Greg Claytona9f40ad2012-02-22 04:37:26 +00005797void
5798Process::AddInvalidMemoryRegion (const LoadRange &region)
5799{
5800 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5801}
5802
5803bool
5804Process::RemoveInvalidMemoryRange (const LoadRange &region)
5805{
5806 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5807}
5808
Jim Ingham372787f2012-04-07 00:00:41 +00005809void
5810Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5811{
5812 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5813}
5814
5815bool
5816Process::RunPreResumeActions ()
5817{
5818 bool result = true;
5819 while (!m_pre_resume_actions.empty())
5820 {
5821 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5822 m_pre_resume_actions.pop_back();
5823 bool this_result = action.callback (action.baton);
5824 if (result == true) result = this_result;
5825 }
5826 return result;
5827}
5828
5829void
5830Process::ClearPreResumeActions ()
5831{
5832 m_pre_resume_actions.clear();
5833}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005834
Greg Claytonfa559e52012-05-18 02:38:05 +00005835void
5836Process::Flush ()
5837{
5838 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005839 m_extended_thread_list.Flush();
5840 m_extended_thread_stop_id = 0;
5841 m_queue_list.Clear();
5842 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005843}
Greg Clayton90ba8112012-12-05 00:16:59 +00005844
5845void
5846Process::DidExec ()
5847{
5848 Target &target = GetTarget();
5849 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005850 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005851 m_dynamic_checkers_ap.reset();
5852 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005853 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005854 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005855 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005856 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005857 m_image_tokens.clear();
5858 m_allocated_memory_cache.Clear();
5859 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005860 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005861 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005862 DoDidExec();
5863 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005864 // Flush the process (threads and all stack frames) after running CompleteAttach()
5865 // in case the dynamic loader loaded things in new locations.
5866 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005867
5868 // After we figure out what was loaded/unloaded in CompleteAttach,
5869 // we need to let the target know so it can do any cleanup it needs to.
5870 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005871}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005872
Jim Ingham1460e4b2014-01-10 23:46:59 +00005873addr_t
5874Process::ResolveIndirectFunction(const Address *address, Error &error)
5875{
5876 if (address == nullptr)
5877 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005878 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005879 return LLDB_INVALID_ADDRESS;
5880 }
5881
5882 addr_t function_addr = LLDB_INVALID_ADDRESS;
5883
5884 addr_t addr = address->GetLoadAddress(&GetTarget());
5885 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5886 if (iter != m_resolved_indirect_addresses.end())
5887 {
5888 function_addr = (*iter).second;
5889 }
5890 else
5891 {
5892 if (!InferiorCall(this, address, function_addr))
5893 {
5894 Symbol *symbol = address->CalculateSymbolContextSymbol();
5895 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5896 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5897 function_addr = LLDB_INVALID_ADDRESS;
5898 }
5899 else
5900 {
5901 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5902 }
5903 }
5904 return function_addr;
5905}
5906
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005907void
5908Process::ModulesDidLoad (ModuleList &module_list)
5909{
5910 SystemRuntime *sys_runtime = GetSystemRuntime();
5911 if (sys_runtime)
5912 {
5913 sys_runtime->ModulesDidLoad (module_list);
5914 }
5915
5916 GetJITLoaders().ModulesDidLoad (module_list);
5917}