blob: bb7b6c01ce4d5861829784691cf938e2fdcbeefa [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 {
Jim Ingham368ac222014-08-15 17:05:27 +0000322 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
323 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000324 }
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 {
Jim Ingham368ac222014-08-15 17:05:27 +0000365 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000366 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000367 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000368 }
369
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000371 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 if (argc > 0)
374 {
375 for (uint32_t i=0; i<argc; i++)
376 {
377 if (i > 0)
378 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000379 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000380 }
381 }
382 }
383 else
384 {
385 s.PutCString (GetName());
386 }
387
388 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000389 }
390}
391
Greg Clayton8b82f082011-04-12 05:54:46 +0000392Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000393ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000394{
395 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000396 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000397
398 switch (short_option)
399 {
400 case 's': // Stop at program entry point
401 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
402 break;
403
Greg Clayton8b82f082011-04-12 05:54:46 +0000404 case 'i': // STDIN for read only
405 {
Zachary Turner696b5282014-08-14 16:01:25 +0000406 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000407 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000408 launch_info.AppendFileAction (action);
409 }
410 break;
411
412 case 'o': // Open STDOUT for write only
413 {
Zachary Turner696b5282014-08-14 16:01:25 +0000414 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000415 if (action.Open (STDOUT_FILENO, option_arg, false, true))
416 launch_info.AppendFileAction (action);
417 }
418 break;
419
420 case 'e': // STDERR for write only
421 {
Zachary Turner696b5282014-08-14 16:01:25 +0000422 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000423 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000424 launch_info.AppendFileAction (action);
425 }
426 break;
427
Greg Clayton9845a8d2012-03-06 04:01:04 +0000428
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 case 'p': // Process plug-in name
430 launch_info.SetProcessPluginName (option_arg);
431 break;
432
433 case 'n': // Disable STDIO
434 {
Zachary Turner696b5282014-08-14 16:01:25 +0000435 FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000436 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000437 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000438 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000439 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000440 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000441 launch_info.AppendFileAction (action);
442 }
443 break;
444
445 case 'w':
446 launch_info.SetWorkingDirectory (option_arg);
447 break;
448
449 case 't': // Open process in new terminal window
450 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
451 break;
452
453 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000454 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
455 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000456 break;
457
458 case 'A':
459 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
460 break;
461
Greg Clayton982c9762011-11-03 21:22:33 +0000462 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000463 if (option_arg && option_arg[0])
464 launch_info.SetShell (option_arg);
465 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000466 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000467 break;
468
Greg Clayton8b82f082011-04-12 05:54:46 +0000469 case 'v':
470 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
471 break;
472
473 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000474 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 break;
476
477 }
478 return error;
479}
480
481OptionDefinition
482ProcessLaunchCommandOptions::g_option_table[] =
483{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000484{ 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."},
485{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
486{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
487{ 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."},
488{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
489{ 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."},
490{ 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 +0000491
Zachary Turnerd37221d2014-07-09 16:31:49 +0000492{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
493{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
494{ 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 +0000495
Zachary Turnerd37221d2014-07-09 16:31:49 +0000496{ 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 +0000497
Zachary Turnerd37221d2014-07-09 16:31:49 +0000498{ 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 +0000499
Zachary Turnerd37221d2014-07-09 16:31:49 +0000500{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000501};
502
503
504
505bool
506ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000507{
508 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
509 return true;
510 const char *match_name = m_match_info.GetName();
511 if (!match_name)
512 return true;
513
514 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
515}
516
517bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000518ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000519{
520 if (!NameMatches (proc_info.GetName()))
521 return false;
522
523 if (m_match_info.ProcessIDIsValid() &&
524 m_match_info.GetProcessID() != proc_info.GetProcessID())
525 return false;
526
527 if (m_match_info.ParentProcessIDIsValid() &&
528 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
529 return false;
530
Greg Clayton8b82f082011-04-12 05:54:46 +0000531 if (m_match_info.UserIDIsValid () &&
532 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000533 return false;
534
Greg Clayton8b82f082011-04-12 05:54:46 +0000535 if (m_match_info.GroupIDIsValid () &&
536 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000537 return false;
538
539 if (m_match_info.EffectiveUserIDIsValid () &&
540 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
541 return false;
542
543 if (m_match_info.EffectiveGroupIDIsValid () &&
544 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
545 return false;
546
547 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000548 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000549 return false;
550 return true;
551}
552
553bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000554ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000555{
556 if (m_name_match_type != eNameMatchIgnore)
557 return false;
558
559 if (m_match_info.ProcessIDIsValid())
560 return false;
561
562 if (m_match_info.ParentProcessIDIsValid())
563 return false;
564
Greg Clayton8b82f082011-04-12 05:54:46 +0000565 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000566 return false;
567
Greg Clayton8b82f082011-04-12 05:54:46 +0000568 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000569 return false;
570
571 if (m_match_info.EffectiveUserIDIsValid ())
572 return false;
573
574 if (m_match_info.EffectiveGroupIDIsValid ())
575 return false;
576
577 if (m_match_info.GetArchitecture().IsValid())
578 return false;
579
580 if (m_match_all_users)
581 return false;
582
583 return true;
584
585}
586
587void
Greg Clayton8b82f082011-04-12 05:54:46 +0000588ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000589{
590 m_match_info.Clear();
591 m_name_match_type = eNameMatchIgnore;
592 m_match_all_users = false;
593}
Greg Clayton58be07b2011-01-07 06:08:19 +0000594
Greg Claytonc3776bf2012-02-09 06:16:32 +0000595ProcessSP
596Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597{
Greg Clayton949e8222013-01-16 17:29:04 +0000598 static uint32_t g_process_unique_id = 0;
599
Greg Claytonc3776bf2012-02-09 06:16:32 +0000600 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601 ProcessCreateInstance create_callback = NULL;
602 if (plugin_name)
603 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000604 ConstString const_plugin_name(plugin_name);
605 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606 if (create_callback)
607 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000608 process_sp = create_callback(target, listener, crash_file_path);
609 if (process_sp)
610 {
Greg Clayton949e8222013-01-16 17:29:04 +0000611 if (process_sp->CanDebug(target, true))
612 {
613 process_sp->m_process_unique_id = ++g_process_unique_id;
614 }
615 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000616 process_sp.reset();
617 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 }
619 }
620 else
621 {
Greg Claytonc982c762010-07-09 20:39:50 +0000622 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000624 process_sp = create_callback(target, listener, crash_file_path);
625 if (process_sp)
626 {
Greg Clayton949e8222013-01-16 17:29:04 +0000627 if (process_sp->CanDebug(target, false))
628 {
629 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000630 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000631 }
632 else
633 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000634 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000635 }
636 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000637 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000638}
639
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000640ConstString &
641Process::GetStaticBroadcasterClass ()
642{
643 static ConstString class_name ("lldb.process");
644 return class_name;
645}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646
647//----------------------------------------------------------------------
648// Process constructor
649//----------------------------------------------------------------------
650Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000651 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000653 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655 m_public_state (eStateUnloaded),
656 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000657 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
658 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 m_private_state_listener ("lldb.process.internal_state_listener"),
660 m_private_state_control_wait(),
661 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000662 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000663 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000665 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666 m_exit_status (-1),
667 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000668 m_thread_mutex (Mutex::eMutexTypeRecursive),
669 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000671 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000672 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000673 m_queue_list (this),
674 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000676 m_image_tokens (),
677 m_listener (listener),
678 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000679 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000680 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000681 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000682 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000683 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000684 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000685 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000686 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000687 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
688 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000689 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000690 m_memory_cache (*this),
691 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000692 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000693 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000694 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000695 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000696 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000697 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000698 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000699 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000700 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000701 m_destroy_in_process (false),
702 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000703{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000704 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000705
Greg Clayton5160ce52013-03-27 23:08:40 +0000706 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000708 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000709
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000710 SetEventName (eBroadcastBitStateChanged, "state-changed");
711 SetEventName (eBroadcastBitInterrupt, "interrupt");
712 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
713 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000714 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000715
Greg Clayton35a4cc52012-10-29 20:52:08 +0000716 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
717 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
718 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
719
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720 listener.StartListeningForEvents (this,
721 eBroadcastBitStateChanged |
722 eBroadcastBitInterrupt |
723 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000724 eBroadcastBitSTDERR |
725 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726
727 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000728 eBroadcastBitStateChanged |
729 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730
731 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
732 eBroadcastInternalStateControlStop |
733 eBroadcastInternalStateControlPause |
734 eBroadcastInternalStateControlResume);
735}
736
737//----------------------------------------------------------------------
738// Destructor
739//----------------------------------------------------------------------
740Process::~Process()
741{
Greg Clayton5160ce52013-03-27 23:08:40 +0000742 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000744 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000745 StopPrivateStateThread();
746}
747
Greg Clayton67cc0632012-08-22 17:17:09 +0000748const ProcessPropertiesSP &
749Process::GetGlobalProperties()
750{
751 static ProcessPropertiesSP g_settings_sp;
752 if (!g_settings_sp)
753 g_settings_sp.reset (new ProcessProperties (true));
754 return g_settings_sp;
755}
756
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757void
758Process::Finalize()
759{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000760 switch (GetPrivateState())
761 {
762 case eStateConnected:
763 case eStateAttaching:
764 case eStateLaunching:
765 case eStateStopped:
766 case eStateRunning:
767 case eStateStepping:
768 case eStateCrashed:
769 case eStateSuspended:
770 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000771 {
772 // FIXME: This will have to be a process setting:
773 bool keep_stopped = false;
774 Detach(keep_stopped);
775 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000776 else
777 Destroy();
778 break;
779
780 case eStateInvalid:
781 case eStateUnloaded:
782 case eStateDetached:
783 case eStateExited:
784 break;
785 }
786
Greg Clayton1ed54f52011-10-01 00:45:15 +0000787 // Clear our broadcaster before we proceed with destroying
788 Broadcaster::Clear();
789
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790 // Do any cleanup needed prior to being destructed... Subclasses
791 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000792
793 // We need to destroy the loader before the derived Process class gets destroyed
794 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000795 m_dynamic_checkers_ap.reset();
796 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000797 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000798 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000799 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000800 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000801 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000802 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000803 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000804 m_queue_list.Clear();
805 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000806 std::vector<Notifications> empty_notifications;
807 m_notifications.swap(empty_notifications);
808 m_image_tokens.clear();
809 m_memory_cache.Clear();
810 m_allocated_memory_cache.Clear();
811 m_language_runtimes.clear();
812 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000813//#ifdef LLDB_CONFIGURATION_DEBUG
814// StreamFile s(stdout, false);
815// EventSP event_sp;
816// while (m_private_state_listener.GetNextEvent(event_sp))
817// {
818// event_sp->Dump (&s);
819// s.EOL();
820// }
821//#endif
822 // We have to be very careful here as the m_private_state_listener might
823 // contain events that have ProcessSP values in them which can keep this
824 // process around forever. These events need to be cleared out.
825 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000826 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
827 m_public_run_lock.SetStopped();
828 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
829 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000830 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831}
832
833void
834Process::RegisterNotificationCallbacks (const Notifications& callbacks)
835{
836 m_notifications.push_back(callbacks);
837 if (callbacks.initialize != NULL)
838 callbacks.initialize (callbacks.baton, this);
839}
840
841bool
842Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
843{
844 std::vector<Notifications>::iterator pos, end = m_notifications.end();
845 for (pos = m_notifications.begin(); pos != end; ++pos)
846 {
847 if (pos->baton == callbacks.baton &&
848 pos->initialize == callbacks.initialize &&
849 pos->process_state_changed == callbacks.process_state_changed)
850 {
851 m_notifications.erase(pos);
852 return true;
853 }
854 }
855 return false;
856}
857
858void
859Process::SynchronouslyNotifyStateChanged (StateType state)
860{
861 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
862 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
863 {
864 if (notification_pos->process_state_changed)
865 notification_pos->process_state_changed (notification_pos->baton, this, state);
866 }
867}
868
869// FIXME: We need to do some work on events before the general Listener sees them.
870// For instance if we are continuing from a breakpoint, we need to ensure that we do
871// the little "insert real insn, step & stop" trick. But we can't do that when the
872// event is delivered by the broadcaster - since that is done on the thread that is
873// waiting for new events, so if we needed more than one event for our handling, we would
874// stall. So instead we do it when we fetch the event off of the queue.
875//
876
877StateType
878Process::GetNextEvent (EventSP &event_sp)
879{
880 StateType state = eStateInvalid;
881
882 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
883 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
884
885 return state;
886}
887
Todd Fialaa3b89e22014-08-12 14:33:19 +0000888bool
889Process::SyncIOHandler (uint64_t timeout_msec)
890{
891 bool timed_out = false;
892
893 // don't sync (potentially context switch) in case where there is no process IO
894 if (m_process_input_reader)
895 {
896 TimeValue timeout = TimeValue::Now();
897 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
898
899 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
900
901 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
902 if(log)
903 {
904 if(timed_out)
905 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
906 else
907 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
908 }
909
910 // reset sync one-shot so it will be ready for next time
911 m_iohandler_sync.SetValue(false, eBroadcastNever);
912 }
913
914 return !timed_out;
915}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916
917StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000918Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000919{
Jim Ingham4b536182011-08-09 02:12:22 +0000920 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
921 // We have to actually check each event, and in the case of a stopped event check the restarted flag
922 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000923 if (event_sp_ptr)
924 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000925 StateType state = GetState();
926 // If we are exited or detached, we won't ever get back to any
927 // other valid state...
928 if (state == eStateDetached || state == eStateExited)
929 return state;
930
Daniel Malea9e9919f2013-10-09 16:56:28 +0000931 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
932 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000933 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
934 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000935
936 if (!wait_always &&
937 StateIsStoppedState(state, true) &&
938 StateIsStoppedState(GetPrivateState(), true)) {
939 if (log)
940 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
941 __FUNCTION__);
942 return state;
943 }
944
Jim Ingham4b536182011-08-09 02:12:22 +0000945 while (state != eStateInvalid)
946 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000947 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000948 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000949 if (event_sp_ptr && event_sp)
950 *event_sp_ptr = event_sp;
951
Jim Ingham4b536182011-08-09 02:12:22 +0000952 switch (state)
953 {
954 case eStateCrashed:
955 case eStateDetached:
956 case eStateExited:
957 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000958 // We need to toggle the run lock as this won't get done in
959 // SetPublicState() if the process is hijacked.
960 if (hijack_listener)
961 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000962 return state;
963 case eStateStopped:
964 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
965 continue;
966 else
Greg Clayton44d93782014-01-27 23:43:24 +0000967 {
968 // We need to toggle the run lock as this won't get done in
969 // SetPublicState() if the process is hijacked.
970 if (hijack_listener)
971 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000972 return state;
Greg Clayton44d93782014-01-27 23:43:24 +0000973 }
Jim Ingham4b536182011-08-09 02:12:22 +0000974 default:
975 continue;
976 }
977 }
978 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979}
980
981
982StateType
983Process::WaitForState
984(
985 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +0000986 const StateType *match_states,
987 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000988)
989{
990 EventSP event_sp;
991 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000992 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993 while (state != eStateInvalid)
994 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000995 // If we are exited or detached, we won't ever get back to any
996 // other valid state...
997 if (state == eStateDetached || state == eStateExited)
998 return state;
999
Greg Clayton44d93782014-01-27 23:43:24 +00001000 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001
1002 for (i=0; i<num_match_states; ++i)
1003 {
1004 if (match_states[i] == state)
1005 return state;
1006 }
1007 }
1008 return state;
1009}
1010
Jim Ingham30f9b212010-10-11 23:53:14 +00001011bool
1012Process::HijackProcessEvents (Listener *listener)
1013{
1014 if (listener != NULL)
1015 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001016 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001017 }
1018 else
1019 return false;
1020}
1021
1022void
1023Process::RestoreProcessEvents ()
1024{
1025 RestoreBroadcaster();
1026}
1027
Jim Ingham0f16e732011-02-08 05:20:59 +00001028bool
1029Process::HijackPrivateProcessEvents (Listener *listener)
1030{
1031 if (listener != NULL)
1032 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001033 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001034 }
1035 else
1036 return false;
1037}
1038
1039void
1040Process::RestorePrivateProcessEvents ()
1041{
1042 m_private_state_broadcaster.RestoreBroadcaster();
1043}
1044
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001046Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047{
Greg Clayton5160ce52013-03-27 23:08:40 +00001048 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049
1050 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001051 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1052 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053
Greg Clayton44d93782014-01-27 23:43:24 +00001054 Listener *listener = hijack_listener;
1055 if (listener == NULL)
1056 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001057
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001059 if (listener->WaitForEventForBroadcasterWithType (timeout,
1060 this,
1061 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1062 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001063 {
1064 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1065 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1066 else if (log)
1067 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1068 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069
1070 if (log)
1071 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001072 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073 StateAsCString(state));
1074 return state;
1075}
1076
1077Event *
1078Process::PeekAtStateChangedEvents ()
1079{
Greg Clayton5160ce52013-03-27 23:08:40 +00001080 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081
1082 if (log)
1083 log->Printf ("Process::%s...", __FUNCTION__);
1084
1085 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001086 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1087 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088 if (log)
1089 {
1090 if (event_ptr)
1091 {
1092 log->Printf ("Process::%s (event_ptr) => %s",
1093 __FUNCTION__,
1094 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1095 }
1096 else
1097 {
1098 log->Printf ("Process::%s no events found",
1099 __FUNCTION__);
1100 }
1101 }
1102 return event_ptr;
1103}
1104
1105StateType
1106Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1107{
Greg Clayton5160ce52013-03-27 23:08:40 +00001108 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109
1110 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001111 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1112 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113
1114 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001115 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1116 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001117 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001118 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001119 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1120 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121
1122 // This is a bit of a hack, but when we wait here we could very well return
1123 // to the command-line, and that could disable the log, which would render the
1124 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001125 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001126 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1127 __FUNCTION__, static_cast<const void *>(timeout),
1128 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129 return state;
1130}
1131
1132bool
1133Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1134{
Greg Clayton5160ce52013-03-27 23:08:40 +00001135 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136
1137 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001138 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1139 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140
1141 if (control_only)
1142 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1143 else
1144 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1145}
1146
1147bool
1148Process::IsRunning () const
1149{
1150 return StateIsRunningState (m_public_state.GetValue());
1151}
1152
1153int
1154Process::GetExitStatus ()
1155{
1156 if (m_public_state.GetValue() == eStateExited)
1157 return m_exit_status;
1158 return -1;
1159}
1160
Greg Clayton85851dd2010-12-04 00:10:17 +00001161
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162const char *
1163Process::GetExitDescription ()
1164{
1165 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1166 return m_exit_string.c_str();
1167 return NULL;
1168}
1169
Greg Clayton6779606a2011-01-22 23:43:18 +00001170bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001171Process::SetExitStatus (int status, const char *cstr)
1172{
Greg Clayton5160ce52013-03-27 23:08:40 +00001173 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001174 if (log)
1175 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1176 status, status,
1177 cstr ? "\"" : "",
1178 cstr ? cstr : "NULL",
1179 cstr ? "\"" : "");
1180
Greg Clayton6779606a2011-01-22 23:43:18 +00001181 // We were already in the exited state
1182 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001183 {
Greg Clayton385d6032011-01-26 23:47:29 +00001184 if (log)
1185 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001186 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001187 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001188
1189 m_exit_status = status;
1190 if (cstr)
1191 m_exit_string = cstr;
1192 else
1193 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194
Greg Clayton6779606a2011-01-22 23:43:18 +00001195 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001196
Greg Clayton6779606a2011-01-22 23:43:18 +00001197 SetPrivateState (eStateExited);
1198 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199}
1200
1201// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001202// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203// found in the global target list (we want to be completely sure that the
1204// lldb_private::Process doesn't go away before we can deliver the signal.
1205bool
Greg Claytone4e45922011-11-16 05:37:56 +00001206Process::SetProcessExitStatus (void *callback_baton,
1207 lldb::pid_t pid,
1208 bool exited,
1209 int signo, // Zero for no signal
1210 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001211)
1212{
Greg Clayton5160ce52013-03-27 23:08:40 +00001213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001214 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001215 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001216 callback_baton,
1217 pid,
1218 exited,
1219 signo,
1220 exit_status);
1221
1222 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001223 {
Greg Clayton66111032010-06-23 01:19:29 +00001224 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001225 if (target_sp)
1226 {
1227 ProcessSP process_sp (target_sp->GetProcessSP());
1228 if (process_sp)
1229 {
1230 const char *signal_cstr = NULL;
1231 if (signo)
1232 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1233
1234 process_sp->SetExitStatus (exit_status, signal_cstr);
1235 }
1236 }
1237 return true;
1238 }
1239 return false;
1240}
1241
1242
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001243void
1244Process::UpdateThreadListIfNeeded ()
1245{
1246 const uint32_t stop_id = GetStopID();
1247 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1248 {
Greg Clayton2637f822011-11-17 01:23:07 +00001249 const StateType state = GetPrivateState();
1250 if (StateIsStoppedState (state, true))
1251 {
1252 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001253 // m_thread_list does have its own mutex, but we need to
1254 // hold onto the mutex between the call to UpdateThreadList(...)
1255 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001256 ThreadList &old_thread_list = m_thread_list;
1257 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001258 ThreadList new_thread_list(this);
1259 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001260 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001261 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001262 {
Jim Ingham09437922013-03-01 20:04:25 +00001263 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1264 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1265 // shutting us down, causing a deadlock.
1266 if (!m_destroy_in_process)
1267 {
1268 OperatingSystem *os = GetOperatingSystem ();
1269 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001270 {
1271 // Clear any old backing threads where memory threads might have been
1272 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001273 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001274 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001275 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001276
1277 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001278 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1279 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1280 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 +00001281 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001282 else
1283 {
1284 // No OS plug-in, the new thread list is the same as the real thread list
1285 new_thread_list = real_thread_list;
1286 }
Jim Ingham09437922013-03-01 20:04:25 +00001287 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001288
1289 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001290 m_thread_list.Update (new_thread_list);
1291 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001292
Jason Molenda4ff13262013-11-20 00:31:38 +00001293 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1294 {
1295 // Clear any extended threads that we may have accumulated previously
1296 m_extended_thread_list.Clear();
1297 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001298
1299 m_queue_list.Clear();
1300 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001301 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001302 }
Greg Clayton2637f822011-11-17 01:23:07 +00001303 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001304 }
1305}
1306
Jason Molenda5e8dce42013-12-13 00:29:16 +00001307void
1308Process::UpdateQueueListIfNeeded ()
1309{
1310 if (m_system_runtime_ap.get())
1311 {
1312 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1313 {
1314 const StateType state = GetPrivateState();
1315 if (StateIsStoppedState (state, true))
1316 {
1317 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1318 m_queue_list_stop_id = GetLastNaturalStopID();
1319 }
1320 }
1321 }
1322}
1323
Greg Claytona4d87472013-01-18 23:41:08 +00001324ThreadSP
1325Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1326{
1327 OperatingSystem *os = GetOperatingSystem ();
1328 if (os)
1329 return os->CreateThread(tid, context);
1330 return ThreadSP();
1331}
1332
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001333uint32_t
1334Process::GetNextThreadIndexID (uint64_t thread_id)
1335{
1336 return AssignIndexIDToThread(thread_id);
1337}
1338
1339bool
1340Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1341{
1342 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1343 if (iterator == m_thread_id_to_index_id_map.end())
1344 {
1345 return false;
1346 }
1347 else
1348 {
1349 return true;
1350 }
1351}
1352
1353uint32_t
1354Process::AssignIndexIDToThread(uint64_t thread_id)
1355{
1356 uint32_t result = 0;
1357 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1358 if (iterator == m_thread_id_to_index_id_map.end())
1359 {
1360 result = ++m_thread_index_id;
1361 m_thread_id_to_index_id_map[thread_id] = result;
1362 }
1363 else
1364 {
1365 result = iterator->second;
1366 }
1367
1368 return result;
1369}
1370
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371StateType
1372Process::GetState()
1373{
1374 // If any other threads access this we will need a mutex for it
1375 return m_public_state.GetValue ();
1376}
1377
1378void
Jim Ingham221d51c2013-05-08 00:35:16 +00001379Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380{
Greg Clayton5160ce52013-03-27 23:08:40 +00001381 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001382 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001383 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001384 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001385 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001386
1387 // On the transition from Run to Stopped, we unlock the writer end of the
1388 // run lock. The lock gets locked in Resume, which is the public API
1389 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001390 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1391 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001392 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001393 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001394 if (log)
1395 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001396 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001397 }
1398 else
1399 {
1400 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1401 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001402 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001403 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001404 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001405 {
1406 if (log)
1407 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001408 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001409 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001410 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001411 }
1412 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413}
1414
Jim Ingham3b8285d2012-04-19 01:40:33 +00001415Error
1416Process::Resume ()
1417{
Greg Clayton5160ce52013-03-27 23:08:40 +00001418 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001419 if (log)
1420 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001421 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001422 {
1423 Error error("Resume request failed - process still running.");
1424 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001425 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001426 return error;
1427 }
1428 return PrivateResume();
1429}
1430
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001431StateType
1432Process::GetPrivateState ()
1433{
1434 return m_private_state.GetValue();
1435}
1436
1437void
1438Process::SetPrivateState (StateType new_state)
1439{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001440 if (m_finalize_called)
1441 return;
1442
Greg Clayton5160ce52013-03-27 23:08:40 +00001443 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444 bool state_changed = false;
1445
1446 if (log)
1447 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1448
Andrew Kaylor29d65742013-05-10 17:19:04 +00001449 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001450 Mutex::Locker locker(m_private_state.GetMutex());
1451
1452 const StateType old_state = m_private_state.GetValueNoLock ();
1453 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001454
Greg Claytonaa49c832013-05-03 22:25:56 +00001455 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1456 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1457 if (old_state_is_stopped != new_state_is_stopped)
1458 {
1459 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001460 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001461 else
Ed Maste64fad602013-07-29 20:58:06 +00001462 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001463 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001464
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465 if (state_changed)
1466 {
1467 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001468 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001470 // Note, this currently assumes that all threads in the list
1471 // stop when the process stops. In the future we will want to
1472 // support a debugging model where some threads continue to run
1473 // while others are stopped. When that happens we will either need
1474 // a way for the thread list to identify which threads are stopping
1475 // or create a special thread list containing only threads which
1476 // actually stopped.
1477 //
1478 // The process plugin is responsible for managing the actual
1479 // behavior of the threads and should have stopped any threads
1480 // that are going to stop before we get here.
1481 m_thread_list.DidStop();
1482
Jim Ingham4b536182011-08-09 02:12:22 +00001483 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001484 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001486 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001487 }
1488 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001489 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1490 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1491 else
1492 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493 }
1494 else
1495 {
1496 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001497 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 }
1499}
1500
Jim Ingham0faa43f2011-11-08 03:00:11 +00001501void
1502Process::SetRunningUserExpression (bool on)
1503{
1504 m_mod_id.SetRunningUserExpression (on);
1505}
1506
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001507addr_t
1508Process::GetImageInfoAddress()
1509{
1510 return LLDB_INVALID_ADDRESS;
1511}
1512
Greg Clayton8f343b02010-11-04 01:54:29 +00001513//----------------------------------------------------------------------
1514// LoadImage
1515//
1516// This function provides a default implementation that works for most
1517// unix variants. Any Process subclasses that need to do shared library
1518// loading differently should override LoadImage and UnloadImage and
1519// do what is needed.
1520//----------------------------------------------------------------------
1521uint32_t
1522Process::LoadImage (const FileSpec &image_spec, Error &error)
1523{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001524 char path[PATH_MAX];
1525 image_spec.GetPath(path, sizeof(path));
1526
Greg Clayton8f343b02010-11-04 01:54:29 +00001527 DynamicLoader *loader = GetDynamicLoader();
1528 if (loader)
1529 {
1530 error = loader->CanLoadImage();
1531 if (error.Fail())
1532 return LLDB_INVALID_IMAGE_TOKEN;
1533 }
1534
1535 if (error.Success())
1536 {
1537 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001538
1539 if (thread_sp)
1540 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001541 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001542
1543 if (frame_sp)
1544 {
1545 ExecutionContext exe_ctx;
1546 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001547 EvaluateExpressionOptions expr_options;
1548 expr_options.SetUnwindOnError(true);
1549 expr_options.SetIgnoreBreakpoints(true);
1550 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001551 expr_options.SetResultIsInternal(true);
1552
Greg Clayton8f343b02010-11-04 01:54:29 +00001553 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001554 expr.Printf(R"(
1555 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1556 the_result.image_ptr = dlopen ("%s", 2);
1557 if (the_result.image_ptr == (void *) 0x0)
1558 {
1559 the_result.error_str = dlerror();
1560 }
1561 else
1562 {
1563 the_result.error_str = (const char *) 0x0;
1564 }
1565 the_result;
1566 )",
1567 path);
1568 const char *prefix = R"(
1569 extern "C" void* dlopen (const char *path, int mode);
1570 extern "C" const char *dlerror (void);
1571 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001572 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001573 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001574 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001575 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001576 expr.GetData(),
1577 prefix,
1578 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001579 expr_error);
1580 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001581 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001582 error = result_valobj_sp->GetError();
1583 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001584 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001585 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001586 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1587 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001588 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001589 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1590 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1591 {
1592 uint32_t image_token = m_image_tokens.size();
1593 m_image_tokens.push_back (image_ptr);
1594 return image_token;
1595 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001596 else if (image_ptr == 0)
1597 {
Jim Ingham6971b862014-07-19 00:37:06 +00001598 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1599 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001600 {
Jim Ingham6971b862014-07-19 00:37:06 +00001601 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001602 {
Jim Inghamcf973792014-07-17 21:53:48 +00001603 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001604 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001605 if (error.Success() && num_chars > 0)
1606 {
1607 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001608 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001609 }
1610 }
1611 }
1612 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001613 }
1614 }
1615 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001616 else
1617 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001618 }
1619 }
1620 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001621 if (!error.AsCString())
1622 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001623 return LLDB_INVALID_IMAGE_TOKEN;
1624}
1625
1626//----------------------------------------------------------------------
1627// UnloadImage
1628//
1629// This function provides a default implementation that works for most
1630// unix variants. Any Process subclasses that need to do shared library
1631// loading differently should override LoadImage and UnloadImage and
1632// do what is needed.
1633//----------------------------------------------------------------------
1634Error
1635Process::UnloadImage (uint32_t image_token)
1636{
1637 Error error;
1638 if (image_token < m_image_tokens.size())
1639 {
1640 const addr_t image_addr = m_image_tokens[image_token];
1641 if (image_addr == LLDB_INVALID_ADDRESS)
1642 {
1643 error.SetErrorString("image already unloaded");
1644 }
1645 else
1646 {
1647 DynamicLoader *loader = GetDynamicLoader();
1648 if (loader)
1649 error = loader->CanLoadImage();
1650
1651 if (error.Success())
1652 {
1653 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001654
1655 if (thread_sp)
1656 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001657 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001658
1659 if (frame_sp)
1660 {
1661 ExecutionContext exe_ctx;
1662 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001663 EvaluateExpressionOptions expr_options;
1664 expr_options.SetUnwindOnError(true);
1665 expr_options.SetIgnoreBreakpoints(true);
1666 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001667 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001668 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001669 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001670 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001671 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001672 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001673 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001674 expr.GetData(),
1675 prefix,
1676 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001677 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001678 if (result_valobj_sp->GetError().Success())
1679 {
1680 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001681 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001682 {
1683 if (scalar.UInt(1))
1684 {
1685 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1686 }
1687 else
1688 {
1689 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1690 }
1691 }
1692 }
1693 else
1694 {
1695 error = result_valobj_sp->GetError();
1696 }
1697 }
1698 }
1699 }
1700 }
1701 }
1702 else
1703 {
1704 error.SetErrorString("invalid image token");
1705 }
1706 return error;
1707}
1708
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001709const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710Process::GetABI()
1711{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001712 if (!m_abi_sp)
1713 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1714 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715}
1716
Jim Ingham22777012010-09-23 02:01:19 +00001717LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001718Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001719{
1720 LanguageRuntimeCollection::iterator pos;
1721 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001722 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001723 {
Jim Inghamab175242012-03-10 00:22:19 +00001724 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001725
Jim Inghamab175242012-03-10 00:22:19 +00001726 m_language_runtimes[language] = runtime_sp;
1727 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001728 }
1729 else
1730 return (*pos).second.get();
1731}
1732
1733CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001734Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001735{
Jim Inghamab175242012-03-10 00:22:19 +00001736 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001737 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1738 return static_cast<CPPLanguageRuntime *> (runtime);
1739 return NULL;
1740}
1741
1742ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001743Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001744{
Jim Inghamab175242012-03-10 00:22:19 +00001745 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001746 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1747 return static_cast<ObjCLanguageRuntime *> (runtime);
1748 return NULL;
1749}
1750
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001751bool
1752Process::IsPossibleDynamicValue (ValueObject& in_value)
1753{
1754 if (in_value.IsDynamic())
1755 return false;
1756 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1757
1758 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1759 {
1760 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1761 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1762 }
1763
1764 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1765 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1766 return true;
1767
1768 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1769 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1770}
1771
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001772BreakpointSiteList &
1773Process::GetBreakpointSiteList()
1774{
1775 return m_breakpoint_site_list;
1776}
1777
1778const BreakpointSiteList &
1779Process::GetBreakpointSiteList() const
1780{
1781 return m_breakpoint_site_list;
1782}
1783
1784
1785void
1786Process::DisableAllBreakpointSites ()
1787{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001788 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1789// bp_site->SetEnabled(true);
1790 DisableBreakpointSite(bp_site);
1791 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001792}
1793
1794Error
1795Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1796{
1797 Error error (DisableBreakpointSiteByID (break_id));
1798
1799 if (error.Success())
1800 m_breakpoint_site_list.Remove(break_id);
1801
1802 return error;
1803}
1804
1805Error
1806Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1807{
1808 Error error;
1809 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1810 if (bp_site_sp)
1811 {
1812 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001813 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001814 }
1815 else
1816 {
Daniel Malead01b2952012-11-29 21:49:15 +00001817 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818 }
1819
1820 return error;
1821}
1822
1823Error
1824Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1825{
1826 Error error;
1827 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1828 if (bp_site_sp)
1829 {
1830 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001831 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832 }
1833 else
1834 {
Daniel Malead01b2952012-11-29 21:49:15 +00001835 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001836 }
1837 return error;
1838}
1839
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001840lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001841Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001843 addr_t load_addr = LLDB_INVALID_ADDRESS;
1844
1845 bool show_error = true;
1846 switch (GetState())
1847 {
1848 case eStateInvalid:
1849 case eStateUnloaded:
1850 case eStateConnected:
1851 case eStateAttaching:
1852 case eStateLaunching:
1853 case eStateDetached:
1854 case eStateExited:
1855 show_error = false;
1856 break;
1857
1858 case eStateStopped:
1859 case eStateRunning:
1860 case eStateStepping:
1861 case eStateCrashed:
1862 case eStateSuspended:
1863 show_error = IsAlive();
1864 break;
1865 }
1866
1867 // Reset the IsIndirect flag here, in case the location changes from
1868 // pointing to a indirect symbol to a regular symbol.
1869 owner->SetIsIndirect (false);
1870
1871 if (owner->ShouldResolveIndirectFunctions())
1872 {
1873 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1874 if (symbol && symbol->IsIndirect())
1875 {
1876 Error error;
1877 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1878 if (!error.Success() && show_error)
1879 {
Greg Clayton44d93782014-01-27 23:43:24 +00001880 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1881 symbol->GetAddress().GetLoadAddress(&m_target),
1882 owner->GetBreakpoint().GetID(),
1883 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001884 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001885 return LLDB_INVALID_BREAK_ID;
1886 }
1887 Address resolved_address(load_addr);
1888 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1889 owner->SetIsIndirect(true);
1890 }
1891 else
1892 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1893 }
1894 else
1895 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1896
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001897 if (load_addr != LLDB_INVALID_ADDRESS)
1898 {
1899 BreakpointSiteSP bp_site_sp;
1900
1901 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1902 // create a new breakpoint site and add it.
1903
1904 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1905
1906 if (bp_site_sp)
1907 {
1908 bp_site_sp->AddOwner (owner);
1909 owner->SetBreakpointSite (bp_site_sp);
1910 return bp_site_sp->GetID();
1911 }
1912 else
1913 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001914 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915 if (bp_site_sp)
1916 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001917 Error error = EnableBreakpointSite (bp_site_sp.get());
1918 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919 {
1920 owner->SetBreakpointSite (bp_site_sp);
1921 return m_breakpoint_site_list.Add (bp_site_sp);
1922 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001923 else
1924 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001925 if (show_error)
1926 {
1927 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001928 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1929 load_addr,
1930 owner->GetBreakpoint().GetID(),
1931 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001932 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001933 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001934 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001935 }
1936 }
1937 }
1938 // We failed to enable the breakpoint
1939 return LLDB_INVALID_BREAK_ID;
1940
1941}
1942
1943void
1944Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1945{
1946 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1947 if (num_owners == 0)
1948 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001949 // Don't try to disable the site if we don't have a live process anymore.
1950 if (IsAlive())
1951 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1953 }
1954}
1955
1956
1957size_t
1958Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1959{
1960 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001961 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001962
Jim Ingham20c77192011-06-29 19:42:28 +00001963 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001965 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1966 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001967 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001968 addr_t intersect_addr;
1969 size_t intersect_size;
1970 size_t opcode_offset;
1971 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001972 {
1973 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1974 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00001975 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001976 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00001977 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001978 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00001980 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001981 }
1982 return bytes_removed;
1983}
1984
1985
Greg Claytonded470d2011-03-19 01:12:21 +00001986
1987size_t
1988Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1989{
1990 PlatformSP platform_sp (m_target.GetPlatform());
1991 if (platform_sp)
1992 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1993 return 0;
1994}
1995
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001996Error
1997Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1998{
1999 Error error;
2000 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002001 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002 const addr_t bp_addr = bp_site->GetLoadAddress();
2003 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002004 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005 if (bp_site->IsEnabled())
2006 {
2007 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002008 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 +00002009 return error;
2010 }
2011
2012 if (bp_addr == LLDB_INVALID_ADDRESS)
2013 {
2014 error.SetErrorString("BreakpointSite contains an invalid load address.");
2015 return error;
2016 }
2017 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2018 // trap for the breakpoint site
2019 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2020
2021 if (bp_opcode_size == 0)
2022 {
Daniel Malead01b2952012-11-29 21:49:15 +00002023 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 }
2025 else
2026 {
2027 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2028
2029 if (bp_opcode_bytes == NULL)
2030 {
2031 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2032 return error;
2033 }
2034
2035 // Save the original opcode by reading it
2036 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2037 {
2038 // Write a software breakpoint in place of the original opcode
2039 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2040 {
2041 uint8_t verify_bp_opcode_bytes[64];
2042 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2043 {
2044 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2045 {
2046 bp_site->SetEnabled(true);
2047 bp_site->SetType (BreakpointSite::eSoftware);
2048 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002049 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002050 bp_site->GetID(),
2051 (uint64_t)bp_addr);
2052 }
2053 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002054 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055 }
2056 else
2057 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2058 }
2059 else
2060 error.SetErrorString("Unable to write breakpoint trap to memory.");
2061 }
2062 else
2063 error.SetErrorString("Unable to read memory at breakpoint address.");
2064 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002065 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002066 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002067 bp_site->GetID(),
2068 (uint64_t)bp_addr,
2069 error.AsCString());
2070 return error;
2071}
2072
2073Error
2074Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2075{
2076 Error error;
2077 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002078 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079 addr_t bp_addr = bp_site->GetLoadAddress();
2080 lldb::user_id_t breakID = bp_site->GetID();
2081 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002082 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002083
2084 if (bp_site->IsHardware())
2085 {
2086 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2087 }
2088 else if (bp_site->IsEnabled())
2089 {
2090 const size_t break_op_size = bp_site->GetByteSize();
2091 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2092 if (break_op_size > 0)
2093 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002094 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002095 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002096 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097 bool break_op_found = false;
2098
2099 // Read the breakpoint opcode
2100 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2101 {
2102 bool verify = false;
2103 // Make sure we have the a breakpoint opcode exists at this address
2104 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2105 {
2106 break_op_found = true;
2107 // We found a valid breakpoint opcode at this address, now restore
2108 // the saved opcode.
2109 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2110 {
2111 verify = true;
2112 }
2113 else
2114 error.SetErrorString("Memory write failed when restoring original opcode.");
2115 }
2116 else
2117 {
2118 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2119 // Set verify to true and so we can check if the original opcode has already been restored
2120 verify = true;
2121 }
2122
2123 if (verify)
2124 {
Greg Claytonc982c762010-07-09 20:39:50 +00002125 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002126 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002127 // Verify that our original opcode made it back to the inferior
2128 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2129 {
2130 // compare the memory we just read with the original opcode
2131 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2132 {
2133 // SUCCESS
2134 bp_site->SetEnabled(false);
2135 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002136 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 +00002137 return error;
2138 }
2139 else
2140 {
2141 if (break_op_found)
2142 error.SetErrorString("Failed to restore original opcode.");
2143 }
2144 }
2145 else
2146 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2147 }
2148 }
2149 else
2150 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2151 }
2152 }
2153 else
2154 {
2155 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002156 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 +00002157 return error;
2158 }
2159
2160 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002161 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002162 bp_site->GetID(),
2163 (uint64_t)bp_addr,
2164 error.AsCString());
2165 return error;
2166
2167}
2168
Greg Clayton58be07b2011-01-07 06:08:19 +00002169// Uncomment to verify memory caching works after making changes to caching code
2170//#define VERIFY_MEMORY_READS
2171
Sean Callanan64c0cf22012-06-07 22:26:42 +00002172size_t
2173Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2174{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002175 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002176 if (!GetDisableMemoryCache())
2177 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002178#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002179 // Memory caching is enabled, with debug verification
2180
2181 if (buf && size)
2182 {
2183 // Uncomment the line below to make sure memory caching is working.
2184 // I ran this through the test suite and got no assertions, so I am
2185 // pretty confident this is working well. If any changes are made to
2186 // memory caching, uncomment the line below and test your changes!
2187
2188 // Verify all memory reads by using the cache first, then redundantly
2189 // reading the same memory from the inferior and comparing to make sure
2190 // everything is exactly the same.
2191 std::string verify_buf (size, '\0');
2192 assert (verify_buf.size() == size);
2193 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2194 Error verify_error;
2195 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2196 assert (cache_bytes_read == verify_bytes_read);
2197 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2198 assert (verify_error.Success() == error.Success());
2199 return cache_bytes_read;
2200 }
2201 return 0;
2202#else // !defined(VERIFY_MEMORY_READS)
2203 // Memory caching is enabled, without debug verification
2204
2205 return m_memory_cache.Read (addr, buf, size, error);
2206#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002207 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002208 else
2209 {
2210 // Memory caching is disabled
2211
2212 return ReadMemoryFromInferior (addr, buf, size, error);
2213 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002214}
Greg Clayton58be07b2011-01-07 06:08:19 +00002215
Greg Clayton4c82d422012-05-18 23:20:01 +00002216size_t
2217Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2218{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002219 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002220 out_str.clear();
2221 addr_t curr_addr = addr;
2222 while (1)
2223 {
2224 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2225 if (length == 0)
2226 break;
2227 out_str.append(buf, length);
2228 // If we got "length - 1" bytes, we didn't get the whole C string, we
2229 // need to read some more characters
2230 if (length == sizeof(buf) - 1)
2231 curr_addr += length;
2232 else
2233 break;
2234 }
2235 return out_str.size();
2236}
2237
Greg Clayton58be07b2011-01-07 06:08:19 +00002238
2239size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002240Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2241 size_t type_width)
2242{
2243 size_t total_bytes_read = 0;
2244 if (dst && max_bytes && type_width && max_bytes >= type_width)
2245 {
2246 // Ensure a null terminator independent of the number of bytes that is read.
2247 memset (dst, 0, max_bytes);
2248 size_t bytes_left = max_bytes - type_width;
2249
2250 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2251 assert(sizeof(terminator) >= type_width &&
2252 "Attempting to validate a string with more than 4 bytes per character!");
2253
2254 addr_t curr_addr = addr;
2255 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2256 char *curr_dst = dst;
2257
2258 error.Clear();
2259 while (bytes_left > 0 && error.Success())
2260 {
2261 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2262 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2263 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2264
2265 if (bytes_read == 0)
2266 break;
2267
2268 // Search for a null terminator of correct size and alignment in bytes_read
2269 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2270 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2271 if (::strncmp(&dst[i], terminator, type_width) == 0)
2272 {
2273 error.Clear();
2274 return i;
2275 }
2276
2277 total_bytes_read += bytes_read;
2278 curr_dst += bytes_read;
2279 curr_addr += bytes_read;
2280 bytes_left -= bytes_read;
2281 }
2282 }
2283 else
2284 {
2285 if (max_bytes)
2286 error.SetErrorString("invalid arguments");
2287 }
2288 return total_bytes_read;
2289}
2290
2291// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2292// null terminators.
2293size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002294Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002295{
2296 size_t total_cstr_len = 0;
2297 if (dst && dst_max_len)
2298 {
Greg Claytone91b7952011-12-15 03:14:23 +00002299 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002300 // NULL out everything just to be safe
2301 memset (dst, 0, dst_max_len);
2302 Error error;
2303 addr_t curr_addr = addr;
2304 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2305 size_t bytes_left = dst_max_len - 1;
2306 char *curr_dst = dst;
2307
2308 while (bytes_left > 0)
2309 {
2310 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2311 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2312 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2313
2314 if (bytes_read == 0)
2315 {
Greg Claytone91b7952011-12-15 03:14:23 +00002316 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002317 dst[total_cstr_len] = '\0';
2318 break;
2319 }
2320 const size_t len = strlen(curr_dst);
2321
2322 total_cstr_len += len;
2323
2324 if (len < bytes_to_read)
2325 break;
2326
2327 curr_dst += bytes_read;
2328 curr_addr += bytes_read;
2329 bytes_left -= bytes_read;
2330 }
2331 }
Greg Claytone91b7952011-12-15 03:14:23 +00002332 else
2333 {
2334 if (dst == NULL)
2335 result_error.SetErrorString("invalid arguments");
2336 else
2337 result_error.Clear();
2338 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002339 return total_cstr_len;
2340}
2341
2342size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002343Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2344{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 if (buf == NULL || size == 0)
2346 return 0;
2347
2348 size_t bytes_read = 0;
2349 uint8_t *bytes = (uint8_t *)buf;
2350
2351 while (bytes_read < size)
2352 {
2353 const size_t curr_size = size - bytes_read;
2354 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2355 bytes + bytes_read,
2356 curr_size,
2357 error);
2358 bytes_read += curr_bytes_read;
2359 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2360 break;
2361 }
2362
2363 // Replace any software breakpoint opcodes that fall into this range back
2364 // into "buf" before we return
2365 if (bytes_read > 0)
2366 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2367 return bytes_read;
2368}
2369
Greg Clayton58a4c462010-12-16 20:01:20 +00002370uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002371Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002372{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002373 Scalar scalar;
2374 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2375 return scalar.ULongLong(fail_value);
2376 return fail_value;
2377}
2378
2379addr_t
2380Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2381{
2382 Scalar scalar;
2383 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2384 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2385 return LLDB_INVALID_ADDRESS;
2386}
2387
2388
2389bool
2390Process::WritePointerToMemory (lldb::addr_t vm_addr,
2391 lldb::addr_t ptr_value,
2392 Error &error)
2393{
2394 Scalar scalar;
2395 const uint32_t addr_byte_size = GetAddressByteSize();
2396 if (addr_byte_size <= 4)
2397 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002398 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002399 scalar = ptr_value;
2400 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002401}
2402
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002403size_t
2404Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2405{
2406 size_t bytes_written = 0;
2407 const uint8_t *bytes = (const uint8_t *)buf;
2408
2409 while (bytes_written < size)
2410 {
2411 const size_t curr_size = size - bytes_written;
2412 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2413 bytes + bytes_written,
2414 curr_size,
2415 error);
2416 bytes_written += curr_bytes_written;
2417 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2418 break;
2419 }
2420 return bytes_written;
2421}
2422
2423size_t
2424Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2425{
Greg Clayton58be07b2011-01-07 06:08:19 +00002426#if defined (ENABLE_MEMORY_CACHING)
2427 m_memory_cache.Flush (addr, size);
2428#endif
2429
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430 if (buf == NULL || size == 0)
2431 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002432
Jim Ingham4b536182011-08-09 02:12:22 +00002433 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002434
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002435 // We need to write any data that would go where any current software traps
2436 // (enabled software breakpoints) any software traps (breakpoints) that we
2437 // may have placed in our tasks memory.
2438
Greg Claytond8cf1a12013-06-12 00:46:38 +00002439 BreakpointSiteList bp_sites_in_range;
2440
2441 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002442 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002443 // No breakpoint sites overlap
2444 if (bp_sites_in_range.IsEmpty())
2445 return WriteMemoryPrivate (addr, buf, size, error);
2446 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002447 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002448 const uint8_t *ubuf = (const uint8_t *)buf;
2449 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002450
Greg Claytond8cf1a12013-06-12 00:46:38 +00002451 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2452
2453 if (error.Success())
2454 {
2455 addr_t intersect_addr;
2456 size_t intersect_size;
2457 size_t opcode_offset;
2458 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2459 assert(intersects);
2460 assert(addr <= intersect_addr && intersect_addr < addr + size);
2461 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2462 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2463
2464 // Check for bytes before this breakpoint
2465 const addr_t curr_addr = addr + bytes_written;
2466 if (intersect_addr > curr_addr)
2467 {
2468 // There are some bytes before this breakpoint that we need to
2469 // just write to memory
2470 size_t curr_size = intersect_addr - curr_addr;
2471 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2472 ubuf + bytes_written,
2473 curr_size,
2474 error);
2475 bytes_written += curr_bytes_written;
2476 if (curr_bytes_written != curr_size)
2477 {
2478 // We weren't able to write all of the requested bytes, we
2479 // are done looping and will return the number of bytes that
2480 // we have written so far.
2481 if (error.Success())
2482 error.SetErrorToGenericError();
2483 }
2484 }
2485 // Now write any bytes that would cover up any software breakpoints
2486 // directly into the breakpoint opcode buffer
2487 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2488 bytes_written += intersect_size;
2489 }
2490 });
2491
2492 if (bytes_written < size)
2493 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2494 ubuf + bytes_written,
2495 size - bytes_written,
2496 error);
2497 }
2498 }
2499 else
2500 {
2501 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502 }
2503
2504 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002505 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002506}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002507
2508size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002509Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002510{
2511 if (byte_size == UINT32_MAX)
2512 byte_size = scalar.GetByteSize();
2513 if (byte_size > 0)
2514 {
2515 uint8_t buf[32];
2516 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2517 if (mem_size > 0)
2518 return WriteMemory(addr, buf, mem_size, error);
2519 else
2520 error.SetErrorString ("failed to get scalar as memory data");
2521 }
2522 else
2523 {
2524 error.SetErrorString ("invalid scalar value");
2525 }
2526 return 0;
2527}
2528
2529size_t
2530Process::ReadScalarIntegerFromMemory (addr_t addr,
2531 uint32_t byte_size,
2532 bool is_signed,
2533 Scalar &scalar,
2534 Error &error)
2535{
Greg Clayton7060f892013-05-01 23:41:30 +00002536 uint64_t uval = 0;
2537 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002538 {
Greg Clayton7060f892013-05-01 23:41:30 +00002539 error.SetErrorString ("byte size is zero");
2540 }
2541 else if (byte_size & (byte_size - 1))
2542 {
2543 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2544 }
2545 else if (byte_size <= sizeof(uval))
2546 {
2547 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002548 if (bytes_read == byte_size)
2549 {
2550 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002551 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002552 if (byte_size <= 4)
2553 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002554 else
Greg Clayton7060f892013-05-01 23:41:30 +00002555 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002556 if (is_signed)
2557 scalar.SignExtend(byte_size * 8);
2558 return bytes_read;
2559 }
2560 }
2561 else
2562 {
2563 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2564 }
2565 return 0;
2566}
2567
Greg Claytond495c532011-05-17 03:37:42 +00002568#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002569addr_t
2570Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2571{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002572 if (GetPrivateState() != eStateStopped)
2573 return LLDB_INVALID_ADDRESS;
2574
Greg Claytond495c532011-05-17 03:37:42 +00002575#if defined (USE_ALLOCATE_MEMORY_CACHE)
2576 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2577#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002578 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002579 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002580 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002581 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 +00002582 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002583 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002584 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002585 m_mod_id.GetStopID(),
2586 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002587 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002588#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589}
2590
Sean Callanan90539452011-09-20 23:01:51 +00002591bool
2592Process::CanJIT ()
2593{
Sean Callanana7b443a2012-02-14 22:50:38 +00002594 if (m_can_jit == eCanJITDontKnow)
2595 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002596 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002597 Error err;
2598
2599 uint64_t allocated_memory = AllocateMemory(8,
2600 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2601 err);
2602
2603 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002604 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002605 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002606 if (log)
2607 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2608 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002609 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002610 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002611 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002612 if (log)
2613 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2614 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002615
2616 DeallocateMemory (allocated_memory);
2617 }
2618
Sean Callanan90539452011-09-20 23:01:51 +00002619 return m_can_jit == eCanJITYes;
2620}
2621
2622void
2623Process::SetCanJIT (bool can_jit)
2624{
2625 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2626}
2627
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002628Error
2629Process::DeallocateMemory (addr_t ptr)
2630{
Greg Claytond495c532011-05-17 03:37:42 +00002631 Error error;
2632#if defined (USE_ALLOCATE_MEMORY_CACHE)
2633 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2634 {
Daniel Malead01b2952012-11-29 21:49:15 +00002635 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002636 }
2637#else
2638 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002639
Greg Clayton5160ce52013-03-27 23:08:40 +00002640 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002641 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002642 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 +00002643 ptr,
2644 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002645 m_mod_id.GetStopID(),
2646 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002647#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002648 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649}
2650
Han Ming Ongc811d382012-11-17 00:33:14 +00002651
Greg Claytonc9660542012-02-05 02:38:54 +00002652ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002653Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002654 lldb::addr_t header_addr,
2655 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002656{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002657 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002658 if (module_sp)
2659 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002660 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002661 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002662 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002663 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002664 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002665 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002666}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002667
2668Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002669Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002670{
2671 Error error;
2672 error.SetErrorString("watchpoints are not supported");
2673 return error;
2674}
2675
2676Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002677Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678{
2679 Error error;
2680 error.SetErrorString("watchpoints are not supported");
2681 return error;
2682}
2683
2684StateType
2685Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2686{
2687 StateType state;
2688 // Now wait for the process to launch and return control to us, and then
2689 // call DidLaunch:
2690 while (1)
2691 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002692 event_sp.reset();
2693 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2694
Greg Clayton2637f822011-11-17 01:23:07 +00002695 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002697
2698 // If state is invalid, then we timed out
2699 if (state == eStateInvalid)
2700 break;
2701
2702 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002703 HandlePrivateEvent (event_sp);
2704 }
2705 return state;
2706}
2707
2708Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002709Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710{
2711 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002713 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002714 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002715 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002716 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002717 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718
Greg Claytonaa149cb2011-08-11 02:48:45 +00002719 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002720 if (exe_module)
2721 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002722 char local_exec_file_path[PATH_MAX];
2723 char platform_exec_file_path[PATH_MAX];
2724 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2725 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726 if (exe_module->GetFileSpec().Exists())
2727 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002728 // Install anything that might need to be installed prior to launching.
2729 // For host systems, this will do nothing, but if we are connected to a
2730 // remote platform it will install any needed binaries
2731 error = GetTarget().Install(&launch_info);
2732 if (error.Fail())
2733 return error;
2734
Greg Clayton71337622011-02-24 22:24:29 +00002735 if (PrivateStateThreadIsValid ())
2736 PausePrivateStateThread ();
2737
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738 error = WillLaunch (exe_module);
2739 if (error.Success())
2740 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002741 const bool restarted = false;
2742 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002743 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744
Ed Maste64fad602013-07-29 20:58:06 +00002745 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002746 {
2747 // Now launch using these arguments.
2748 error = DoLaunch (exe_module, launch_info);
2749 }
2750 else
2751 {
2752 // This shouldn't happen
2753 error.SetErrorString("failed to acquire process run lock");
2754 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002755
2756 if (error.Fail())
2757 {
2758 if (GetID() != LLDB_INVALID_PROCESS_ID)
2759 {
2760 SetID (LLDB_INVALID_PROCESS_ID);
2761 const char *error_string = error.AsCString();
2762 if (error_string == NULL)
2763 error_string = "launch failed";
2764 SetExitStatus (-1, error_string);
2765 }
2766 }
2767 else
2768 {
2769 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002770 TimeValue timeout_time;
2771 timeout_time = TimeValue::Now();
2772 timeout_time.OffsetWithSeconds(10);
2773 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774
Greg Clayton1a38ea72011-06-22 01:42:17 +00002775 if (state == eStateInvalid || event_sp.get() == NULL)
2776 {
2777 // We were able to launch the process, but we failed to
2778 // catch the initial stop.
2779 SetExitStatus (0, "failed to catch stop after launch");
2780 Destroy();
2781 }
2782 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002783 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002784
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785 DidLaunch ();
2786
Greg Claytonc859e2d2012-02-13 23:10:39 +00002787 DynamicLoader *dyld = GetDynamicLoader ();
2788 if (dyld)
2789 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002790
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002791 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002792
Jason Molendaeef51062013-11-05 03:57:19 +00002793 SystemRuntime *system_runtime = GetSystemRuntime ();
2794 if (system_runtime)
2795 system_runtime->DidLaunch();
2796
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002797 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798 // This delays passing the stopped event to listeners till DidLaunch gets
2799 // a chance to complete...
2800 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002801
2802 if (PrivateStateThreadIsValid ())
2803 ResumePrivateStateThread ();
2804 else
2805 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806 }
2807 else if (state == eStateExited)
2808 {
2809 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2810 // not likely to work, and return an invalid pid.
2811 HandlePrivateEvent (event_sp);
2812 }
2813 }
2814 }
2815 }
2816 else
2817 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002818 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 }
2820 }
2821 return error;
2822}
2823
Greg Claytonc3776bf2012-02-09 06:16:32 +00002824
2825Error
2826Process::LoadCore ()
2827{
2828 Error error = DoLoadCore();
2829 if (error.Success())
2830 {
2831 if (PrivateStateThreadIsValid ())
2832 ResumePrivateStateThread ();
2833 else
2834 StartPrivateStateThread ();
2835
Greg Claytonc859e2d2012-02-13 23:10:39 +00002836 DynamicLoader *dyld = GetDynamicLoader ();
2837 if (dyld)
2838 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002839
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002840 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002841
Jason Molendaeef51062013-11-05 03:57:19 +00002842 SystemRuntime *system_runtime = GetSystemRuntime ();
2843 if (system_runtime)
2844 system_runtime->DidAttach();
2845
Greg Claytonc859e2d2012-02-13 23:10:39 +00002846 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002847 // We successfully loaded a core file, now pretend we stopped so we can
2848 // show all of the threads in the core file and explore the crashed
2849 // state.
2850 SetPrivateState (eStateStopped);
2851
2852 }
2853 return error;
2854}
2855
Greg Claytonc859e2d2012-02-13 23:10:39 +00002856DynamicLoader *
2857Process::GetDynamicLoader ()
2858{
2859 if (m_dyld_ap.get() == NULL)
2860 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2861 return m_dyld_ap.get();
2862}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002863
Todd Fialaaf245d12014-06-30 21:05:18 +00002864const lldb::DataBufferSP
2865Process::GetAuxvData()
2866{
2867 return DataBufferSP ();
2868}
2869
Andrew MacPherson17220c12014-03-05 10:12:43 +00002870JITLoaderList &
2871Process::GetJITLoaders ()
2872{
2873 if (!m_jit_loaders_ap)
2874 {
2875 m_jit_loaders_ap.reset(new JITLoaderList());
2876 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2877 }
2878 return *m_jit_loaders_ap;
2879}
2880
Jason Molendaeef51062013-11-05 03:57:19 +00002881SystemRuntime *
2882Process::GetSystemRuntime ()
2883{
2884 if (m_system_runtime_ap.get() == NULL)
2885 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2886 return m_system_runtime_ap.get();
2887}
2888
Greg Claytonc3776bf2012-02-09 06:16:32 +00002889
Jim Inghambb3a2832011-01-29 01:49:25 +00002890Process::NextEventAction::EventActionResult
2891Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892{
Jim Inghambb3a2832011-01-29 01:49:25 +00002893 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2894 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002895 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002896 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002897 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002898 return eEventActionRetry;
2899
2900 case eStateStopped:
2901 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002902 {
2903 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002904 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002905 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002906 // We don't want these events to be reported, so go set the ShouldReportStop here:
2907 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2908
Greg Claytonc9ed4782011-11-12 02:10:56 +00002909 if (m_exec_count > 0)
2910 {
2911 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00002912 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002913 return eEventActionRetry;
2914 }
2915 else
2916 {
2917 m_process->CompleteAttach ();
2918 return eEventActionSuccess;
2919 }
2920 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002921 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002922
Greg Clayton513c26c2011-01-29 07:10:55 +00002923 default:
2924 case eStateExited:
2925 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002926 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002927 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002928
2929 m_exit_string.assign ("No valid Process");
2930 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002931}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932
Jim Inghambb3a2832011-01-29 01:49:25 +00002933Process::NextEventAction::EventActionResult
2934Process::AttachCompletionHandler::HandleBeingInterrupted()
2935{
2936 return eEventActionSuccess;
2937}
2938
2939const char *
2940Process::AttachCompletionHandler::GetExitString ()
2941{
2942 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943}
2944
2945Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002946Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002947{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002949 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002950 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002951 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002952 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002953 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002954
Greg Clayton144f3a92011-11-15 03:53:30 +00002955 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002956 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002957 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002958 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002959 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002960
Greg Clayton144f3a92011-11-15 03:53:30 +00002961 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002962 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002963 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2964
2965 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002967 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2968 if (error.Success())
2969 {
Ed Maste64fad602013-07-29 20:58:06 +00002970 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002971 {
2972 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002973 const bool restarted = false;
2974 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002975 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00002976 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00002977 }
2978 else
2979 {
2980 // This shouldn't happen
2981 error.SetErrorString("failed to acquire process run lock");
2982 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002983
Greg Clayton144f3a92011-11-15 03:53:30 +00002984 if (error.Fail())
2985 {
2986 if (GetID() != LLDB_INVALID_PROCESS_ID)
2987 {
2988 SetID (LLDB_INVALID_PROCESS_ID);
2989 if (error.AsCString() == NULL)
2990 error.SetErrorString("attach failed");
2991
2992 SetExitStatus(-1, error.AsCString());
2993 }
2994 }
2995 else
2996 {
2997 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2998 StartPrivateStateThread();
2999 }
3000 return error;
3001 }
Greg Claytone996fd32011-03-08 22:40:15 +00003002 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003003 else
Greg Claytone996fd32011-03-08 22:40:15 +00003004 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003005 ProcessInstanceInfoList process_infos;
3006 PlatformSP platform_sp (m_target.GetPlatform ());
3007
3008 if (platform_sp)
3009 {
3010 ProcessInstanceInfoMatch match_info;
3011 match_info.GetProcessInfo() = attach_info;
3012 match_info.SetNameMatchType (eNameMatchEquals);
3013 platform_sp->FindProcesses (match_info, process_infos);
3014 const uint32_t num_matches = process_infos.GetSize();
3015 if (num_matches == 1)
3016 {
3017 attach_pid = process_infos.GetProcessIDAtIndex(0);
3018 // Fall through and attach using the above process ID
3019 }
3020 else
3021 {
3022 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3023 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003024 {
3025 StreamString s;
3026 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3027 for (size_t i = 0; i < num_matches; i++)
3028 {
3029 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3030 }
3031 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3032 process_name,
3033 s.GetData());
3034 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003035 else
3036 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3037 }
3038 }
3039 else
3040 {
3041 error.SetErrorString ("invalid platform, can't find processes by name");
3042 return error;
3043 }
Greg Claytone996fd32011-03-08 22:40:15 +00003044 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045 }
3046 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003047 {
3048 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003049 }
3050 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003051
3052 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003053 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003054 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003055 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003057
Ed Maste64fad602013-07-29 20:58:06 +00003058 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003059 {
3060 // Now attach using these arguments.
3061 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003062 const bool restarted = false;
3063 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003064 error = DoAttachToProcessWithID (attach_pid, attach_info);
3065 }
3066 else
3067 {
3068 // This shouldn't happen
3069 error.SetErrorString("failed to acquire process run lock");
3070 }
3071
Greg Clayton144f3a92011-11-15 03:53:30 +00003072 if (error.Success())
3073 {
3074
3075 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3076 StartPrivateStateThread();
3077 }
3078 else
Greg Claytone996fd32011-03-08 22:40:15 +00003079 {
3080 if (GetID() != LLDB_INVALID_PROCESS_ID)
3081 {
3082 SetID (LLDB_INVALID_PROCESS_ID);
3083 const char *error_string = error.AsCString();
3084 if (error_string == NULL)
3085 error_string = "attach failed";
3086
3087 SetExitStatus(-1, error_string);
3088 }
3089 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003090 }
3091 }
3092 return error;
3093}
3094
Greg Clayton93d3c8332011-02-16 04:46:07 +00003095void
3096Process::CompleteAttach ()
3097{
3098 // Let the process subclass figure out at much as it can about the process
3099 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003100 ArchSpec process_arch;
3101 DidAttach(process_arch);
3102
3103 if (process_arch.IsValid())
3104 m_target.SetArchitecture(process_arch);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003105
Jim Ingham4299fdb2011-09-15 01:10:17 +00003106 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3107 // the same as the one we've already set, switch architectures.
3108 PlatformSP platform_sp (m_target.GetPlatform ());
3109 assert (platform_sp.get());
3110 if (platform_sp)
3111 {
Greg Clayton70512312012-05-08 01:45:38 +00003112 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003113 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003114 {
3115 ArchSpec platform_arch;
3116 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3117 if (platform_sp)
3118 {
3119 m_target.SetPlatform (platform_sp);
3120 m_target.SetArchitecture(platform_arch);
3121 }
3122 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003123 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003124 {
3125 ProcessInstanceInfo process_info;
3126 platform_sp->GetProcessInfo (GetID(), process_info);
3127 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003128 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003129 m_target.SetArchitecture (process_arch);
3130 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003131 }
3132
3133 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003134 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003135 DynamicLoader *dyld = GetDynamicLoader ();
3136 if (dyld)
3137 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003138
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003139 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003140
Jason Molendaeef51062013-11-05 03:57:19 +00003141 SystemRuntime *system_runtime = GetSystemRuntime ();
3142 if (system_runtime)
3143 system_runtime->DidAttach();
3144
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003145 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003146 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003147 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003148 Mutex::Locker modules_locker(target_modules.GetMutex());
3149 size_t num_modules = target_modules.GetSize();
3150 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003151
Andy Gibbsa297a972013-06-19 19:04:53 +00003152 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003153 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003154 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003155 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003156 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003157 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003158 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003159 break;
3160 }
3161 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003162 if (new_executable_module_sp)
3163 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003164}
3165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003167Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003168{
Greg Claytonb766a732011-02-04 01:58:07 +00003169 m_abi_sp.reset();
3170 m_process_input_reader.reset();
3171
3172 // Find the process and its architecture. Make sure it matches the architecture
3173 // of the current Target, and if not adjust it.
3174
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003175 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003176 if (error.Success())
3177 {
Greg Clayton71337622011-02-24 22:24:29 +00003178 if (GetID() != LLDB_INVALID_PROCESS_ID)
3179 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003180 EventSP event_sp;
3181 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3182
3183 if (state == eStateStopped || state == eStateCrashed)
3184 {
3185 // If we attached and actually have a process on the other end, then
3186 // this ended up being the equivalent of an attach.
3187 CompleteAttach ();
3188
3189 // This delays passing the stopped event to listeners till
3190 // CompleteAttach gets a chance to complete...
3191 HandlePrivateEvent (event_sp);
3192
3193 }
Greg Clayton71337622011-02-24 22:24:29 +00003194 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003195
3196 if (PrivateStateThreadIsValid ())
3197 ResumePrivateStateThread ();
3198 else
3199 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003200 }
3201 return error;
3202}
3203
3204
3205Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003206Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207{
Greg Clayton5160ce52013-03-27 23:08:40 +00003208 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003209 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003210 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003211 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003212 StateAsCString(m_public_state.GetValue()),
3213 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003214
3215 Error error (WillResume());
3216 // Tell the process it is about to resume before the thread list
3217 if (error.Success())
3218 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003219 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003220 // can let all of our threads know that they are about to be
3221 // resumed. Threads will each be called with
3222 // Thread::WillResume(StateType) where StateType contains the state
3223 // that they are supposed to have when the process is resumed
3224 // (suspended/running/stepping). Threads should also check
3225 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003226 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003227 if (m_thread_list.WillResume())
3228 {
Jim Ingham372787f2012-04-07 00:00:41 +00003229 // Last thing, do the PreResumeActions.
3230 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231 {
Jim Ingham0161b492013-02-09 01:29:05 +00003232 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003233 }
3234 else
3235 {
3236 m_mod_id.BumpResumeID();
3237 error = DoResume();
3238 if (error.Success())
3239 {
3240 DidResume();
3241 m_thread_list.DidResume();
3242 if (log)
3243 log->Printf ("Process thinks the process has resumed.");
3244 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003245 }
3246 }
3247 else
3248 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003249 // Somebody wanted to run without running. So generate a continue & a stopped event,
3250 // and let the world handle them.
3251 if (log)
3252 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3253
3254 SetPrivateState(eStateRunning);
3255 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 }
3257 }
Jim Ingham444586b2011-01-24 06:34:17 +00003258 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003259 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260 return error;
3261}
3262
3263Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003264Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003266 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3267 // in case it was already set and some thread plan logic calls halt on its
3268 // own.
3269 m_clear_thread_plans_on_stop |= clear_thread_plans;
3270
Jim Inghamaacc3182012-06-06 00:29:30 +00003271 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3272 // we could just straightaway get another event. It just narrows the window...
3273 m_currently_handling_event.WaitForValueEqualTo(false);
3274
3275
Jim Inghambb3a2832011-01-29 01:49:25 +00003276 // Pause our private state thread so we can ensure no one else eats
3277 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003278 Listener halt_listener ("lldb.process.halt_listener");
3279 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003280
Jim Inghambb3a2832011-01-29 01:49:25 +00003281 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003282 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003283
Greg Clayton06357c92014-07-30 17:38:47 +00003284 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003285 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003286 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003287
Greg Clayton513c26c2011-01-29 07:10:55 +00003288 bool caused_stop = false;
3289
3290 // Ask the process subclass to actually halt our process
3291 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003293 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003294 if (m_public_state.GetValue() == eStateAttaching)
3295 {
Greg Clayton06357c92014-07-30 17:38:47 +00003296 // Don't hijack and eat the eStateExited as the code that was doing
3297 // the attach will be waiting for this event...
3298 RestorePrivateProcessEvents();
3299 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003300 SetExitStatus(SIGKILL, "Cancelled async attach.");
3301 Destroy ();
3302 }
3303 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003304 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003305 // If "caused_stop" is true, then DoHalt stopped the process. If
3306 // "caused_stop" is false, the process was already stopped.
3307 // If the DoHalt caused the process to stop, then we want to catch
3308 // this event and set the interrupted bool to true before we pass
3309 // this along so clients know that the process was interrupted by
3310 // a halt command.
3311 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003312 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003313 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003314 TimeValue timeout_time;
3315 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003316 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003317 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3318 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003319
Jim Ingham0f16e732011-02-08 05:20:59 +00003320 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003321 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003322 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003323 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003324 }
3325 else
3326 {
Greg Clayton2637f822011-11-17 01:23:07 +00003327 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003328 {
3329 // We caused the process to interrupt itself, so mark this
3330 // as such in the stop event so clients can tell an interrupted
3331 // process from a natural stop
3332 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3333 }
3334 else
3335 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003336 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003337 if (log)
3338 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3339 error.SetErrorString ("Did not get stopped event after halt.");
3340 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003341 }
3342 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003343 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003344 }
3345 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003346 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003347 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003348 if (!restored_process_events)
3349 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003350
3351 // Post any event we might have consumed. If all goes well, we will have
3352 // stopped the process, intercepted the event and set the interrupted
3353 // bool in the event. Post it to the private event queue and that will end up
3354 // correctly setting the state.
3355 if (event_sp)
3356 m_private_state_broadcaster.BroadcastEvent(event_sp);
3357
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003358 return error;
3359}
3360
3361Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003362Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3363{
3364 Error error;
3365 if (m_public_state.GetValue() == eStateRunning)
3366 {
3367 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3368 if (log)
3369 log->Printf("Process::Destroy() About to halt.");
3370 error = Halt();
3371 if (error.Success())
3372 {
3373 // Consume the halt event.
3374 TimeValue timeout (TimeValue::Now());
3375 timeout.OffsetWithSeconds(1);
3376 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3377
3378 // If the process exited while we were waiting for it to stop, put the exited event into
3379 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3380 // they don't have a process anymore...
3381
3382 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3383 {
3384 if (log)
3385 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3386 return error;
3387 }
3388 else
3389 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3390
3391 if (state != eStateStopped)
3392 {
3393 if (log)
3394 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3395 // If we really couldn't stop the process then we should just error out here, but if the
3396 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3397 StateType private_state = m_private_state.GetValue();
3398 if (private_state != eStateStopped)
3399 {
3400 return error;
3401 }
3402 }
3403 }
3404 else
3405 {
3406 if (log)
3407 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3408 }
3409 }
3410 return error;
3411}
3412
3413Error
Jim Inghamacff8952013-05-02 00:27:30 +00003414Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003416 EventSP exit_event_sp;
3417 Error error;
3418 m_destroy_in_process = true;
3419
3420 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003421
3422 if (error.Success())
3423 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003424 if (DetachRequiresHalt())
3425 {
3426 error = HaltForDestroyOrDetach (exit_event_sp);
3427 if (!error.Success())
3428 {
3429 m_destroy_in_process = false;
3430 return error;
3431 }
3432 else if (exit_event_sp)
3433 {
3434 // We shouldn't need to do anything else here. There's no process left to detach from...
3435 StopPrivateStateThread();
3436 m_destroy_in_process = false;
3437 return error;
3438 }
3439 }
3440
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003441 m_thread_list.DiscardThreadPlans();
3442 DisableAllBreakpointSites();
3443
Jim Inghamacff8952013-05-02 00:27:30 +00003444 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003445 if (error.Success())
3446 {
3447 DidDetach();
3448 StopPrivateStateThread();
3449 }
Jim Inghamacff8952013-05-02 00:27:30 +00003450 else
3451 {
3452 return error;
3453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003455 m_destroy_in_process = false;
3456
3457 // If we exited when we were waiting for a process to stop, then
3458 // forward the event here so we don't lose the event
3459 if (exit_event_sp)
3460 {
3461 // Directly broadcast our exited event because we shut down our
3462 // private state thread above
3463 BroadcastEvent(exit_event_sp);
3464 }
3465
3466 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3467 // the last events through the event system, in which case we might strand the write lock. Unlock
3468 // it here so when we do to tear down the process we don't get an error destroying the lock.
3469
Ed Maste64fad602013-07-29 20:58:06 +00003470 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003471 return error;
3472}
3473
3474Error
3475Process::Destroy ()
3476{
Jim Ingham09437922013-03-01 20:04:25 +00003477
3478 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3479 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3480 // failed and the process stays around for some reason it won't be in a confused state.
3481
3482 m_destroy_in_process = true;
3483
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484 Error error (WillDestroy());
3485 if (error.Success())
3486 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003487 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003488 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003489 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003490 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003491 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003492
Jim Inghamaacc3182012-06-06 00:29:30 +00003493 if (m_public_state.GetValue() != eStateRunning)
3494 {
3495 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3496 // kill it, we don't want it hitting a breakpoint...
3497 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3498 // we're not going to have much luck doing this now.
3499 m_thread_list.DiscardThreadPlans();
3500 DisableAllBreakpointSites();
3501 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003502
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003503 error = DoDestroy();
3504 if (error.Success())
3505 {
3506 DidDestroy();
3507 StopPrivateStateThread();
3508 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003509 m_stdio_communication.StopReadThread();
3510 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003511
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003512 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003513 {
3514 m_process_input_reader->SetIsDone(true);
3515 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003516 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003517 }
3518
Greg Clayton85fb1b92012-09-11 02:33:37 +00003519 // If we exited when we were waiting for a process to stop, then
3520 // forward the event here so we don't lose the event
3521 if (exit_event_sp)
3522 {
3523 // Directly broadcast our exited event because we shut down our
3524 // private state thread above
3525 BroadcastEvent(exit_event_sp);
3526 }
3527
Jim Inghamb1e2e842012-04-12 18:49:31 +00003528 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3529 // the last events through the event system, in which case we might strand the write lock. Unlock
3530 // 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 +00003531 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532 }
Jim Ingham09437922013-03-01 20:04:25 +00003533
3534 m_destroy_in_process = false;
3535
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003536 return error;
3537}
3538
3539Error
3540Process::Signal (int signal)
3541{
3542 Error error (WillSignal());
3543 if (error.Success())
3544 {
3545 error = DoSignal(signal);
3546 if (error.Success())
3547 DidSignal();
3548 }
3549 return error;
3550}
3551
Greg Clayton514487e2011-02-15 21:59:32 +00003552lldb::ByteOrder
3553Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003554{
Greg Clayton514487e2011-02-15 21:59:32 +00003555 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003556}
3557
3558uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003559Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560{
Greg Clayton514487e2011-02-15 21:59:32 +00003561 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003562}
3563
Greg Clayton514487e2011-02-15 21:59:32 +00003564
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565bool
3566Process::ShouldBroadcastEvent (Event *event_ptr)
3567{
3568 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3569 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003570 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003571
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572 switch (state)
3573 {
Greg Claytonb766a732011-02-04 01:58:07 +00003574 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003575 case eStateAttaching:
3576 case eStateLaunching:
3577 case eStateDetached:
3578 case eStateExited:
3579 case eStateUnloaded:
3580 // These events indicate changes in the state of the debugging session, always report them.
3581 return_value = true;
3582 break;
3583 case eStateInvalid:
3584 // We stopped for no apparent reason, don't report it.
3585 return_value = false;
3586 break;
3587 case eStateRunning:
3588 case eStateStepping:
3589 // If we've started the target running, we handle the cases where we
3590 // are already running and where there is a transition from stopped to
3591 // running differently.
3592 // running -> running: Automatically suppress extra running events
3593 // stopped -> running: Report except when there is one or more no votes
3594 // and no yes votes.
3595 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003596 if (m_force_next_event_delivery)
3597 return_value = true;
3598 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003599 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003600 switch (m_last_broadcast_state)
3601 {
3602 case eStateRunning:
3603 case eStateStepping:
3604 // We always suppress multiple runnings with no PUBLIC stop in between.
3605 return_value = false;
3606 break;
3607 default:
3608 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003609 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003610 // events. If I run the lldb/test/thread/a.out file and
3611 // break at main.cpp:58, run and hit the breakpoints on
3612 // multiple threads, then somehow during the stepping over
3613 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614
Jim Ingham1460e4b2014-01-10 23:46:59 +00003615 // This is a transition from stop to run.
3616 switch (m_thread_list.ShouldReportRun (event_ptr))
3617 {
3618 case eVoteYes:
3619 case eVoteNoOpinion:
3620 return_value = true;
3621 break;
3622 case eVoteNo:
3623 return_value = false;
3624 break;
3625 }
3626 break;
3627 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003628 }
3629 break;
3630 case eStateStopped:
3631 case eStateCrashed:
3632 case eStateSuspended:
3633 {
3634 // We've stopped. First see if we're going to restart the target.
3635 // If we are going to stop, then we always broadcast the event.
3636 // 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 +00003637 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003638
Jim Inghamcb4ca112012-05-16 01:32:14 +00003639 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003640 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003641 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003642 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003643 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003644 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003645 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003646 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3647 // so they can properly set their state.
3648 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003649 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003650 }
3651 else
3652 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003653 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3654 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003655
Jim Ingham0161b492013-02-09 01:29:05 +00003656 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3657 // Asking the thread list is also not likely to go well, since we are running again.
3658 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003659
Jim Ingham0161b492013-02-09 01:29:05 +00003660 if (!was_restarted)
3661 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003662
Jim Ingham221d51c2013-05-08 00:35:16 +00003663 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003664 {
Jim Ingham0161b492013-02-09 01:29:05 +00003665 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3666 if (log)
3667 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003668 should_resume, StateAsCString(state),
3669 was_restarted, stop_vote);
3670
Jim Ingham0161b492013-02-09 01:29:05 +00003671 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672 {
3673 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003674 return_value = true;
3675 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 case eVoteNo:
3678 return_value = false;
3679 break;
3680 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003681
Jim Inghamcb95f342012-09-05 21:13:56 +00003682 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003683 {
3684 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003685 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3686 static_cast<void*>(event_ptr),
3687 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003688 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003689 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003690 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003691
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003692 }
3693 else
3694 {
3695 return_value = true;
3696 SynchronouslyNotifyStateChanged (state);
3697 }
3698 }
3699 }
Jim Ingham0161b492013-02-09 01:29:05 +00003700 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003701 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003702
Jim Ingham1460e4b2014-01-10 23:46:59 +00003703 // Forcing the next event delivery is a one shot deal. So reset it here.
3704 m_force_next_event_delivery = false;
3705
Jim Ingham0161b492013-02-09 01:29:05 +00003706 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3707 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3708 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3709 // because the PublicState reflects the last event pulled off the queue, and there may be several
3710 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3711 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003712
Jim Ingham0161b492013-02-09 01:29:05 +00003713 if (return_value)
3714 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003715
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003716 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003717 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003718 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003719 StateAsCString(m_last_broadcast_state),
3720 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721 return return_value;
3722}
3723
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003724
3725bool
Jim Ingham372787f2012-04-07 00:00:41 +00003726Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003727{
Greg Clayton5160ce52013-03-27 23:08:40 +00003728 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729
Greg Clayton8b82f082011-04-12 05:54:46 +00003730 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003731 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003732 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3733
Jim Ingham372787f2012-04-07 00:00:41 +00003734 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003735 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736
3737 // Create a thread that watches our internal state and controls which
3738 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003739 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003740
3741 if (Host::MAX_THREAD_NAME_LENGTH <= 16)
3742 {
3743 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3744 if (already_running)
3745 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3746 else
3747 snprintf(thread_name, sizeof(thread_name), "intern-state");
3748 }
Jim Ingham372787f2012-04-07 00:00:41 +00003749 else
Todd Fiala17096d72014-07-16 19:03:16 +00003750 {
3751 if (already_running)
3752 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3753 else
3754 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3755 }
3756
Jim Ingham076b3042012-04-10 01:21:57 +00003757 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003758 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003759 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3760 if (success)
3761 {
3762 ResumePrivateStateThread();
3763 return true;
3764 }
3765 else
3766 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767}
3768
3769void
3770Process::PausePrivateStateThread ()
3771{
3772 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3773}
3774
3775void
3776Process::ResumePrivateStateThread ()
3777{
3778 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3779}
3780
3781void
3782Process::StopPrivateStateThread ()
3783{
Greg Clayton8b82f082011-04-12 05:54:46 +00003784 if (PrivateStateThreadIsValid ())
3785 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003786 else
3787 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003788 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003789 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003790 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003791 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003792}
3793
3794void
3795Process::ControlPrivateStateThread (uint32_t signal)
3796{
Greg Clayton5160ce52013-03-27 23:08:40 +00003797 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003798
3799 assert (signal == eBroadcastInternalStateControlStop ||
3800 signal == eBroadcastInternalStateControlPause ||
3801 signal == eBroadcastInternalStateControlResume);
3802
3803 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003804 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003805
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003806 // Signal the private state thread. First we should copy this is case the
3807 // thread starts exiting since the private state thread will NULL this out
3808 // when it exits
3809 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003810 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003811 {
3812 TimeValue timeout_time;
3813 bool timed_out;
3814
3815 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3816
3817 timeout_time = TimeValue::Now();
3818 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003819 if (log)
3820 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003821 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3822 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3823
3824 if (signal == eBroadcastInternalStateControlStop)
3825 {
3826 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003827 {
3828 Error error;
3829 Host::ThreadCancel (private_state_thread, &error);
3830 if (log)
3831 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3832 }
3833 else
3834 {
3835 if (log)
3836 log->Printf ("The control event killed the private state thread without having to cancel.");
3837 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003838
3839 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003840 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003841 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003842 }
3843 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003844 else
3845 {
3846 if (log)
3847 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3848 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003849}
3850
3851void
Jim Inghamcfc09352012-07-27 23:57:19 +00003852Process::SendAsyncInterrupt ()
3853{
3854 if (PrivateStateThreadIsValid())
3855 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3856 else
3857 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3858}
3859
3860void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003861Process::HandlePrivateEvent (EventSP &event_sp)
3862{
Greg Clayton5160ce52013-03-27 23:08:40 +00003863 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003864 m_resume_requested = false;
3865
Jim Inghamaacc3182012-06-06 00:29:30 +00003866 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003867
Greg Clayton414f5d32011-01-25 02:58:48 +00003868 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003869
3870 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003871 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003872 {
Jim Ingham754ab982011-01-29 04:05:41 +00003873 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003874 if (log)
3875 log->Printf ("Ran next event action, result was %d.", action_result);
3876
Jim Inghambb3a2832011-01-29 01:49:25 +00003877 switch (action_result)
3878 {
3879 case NextEventAction::eEventActionSuccess:
3880 SetNextEventAction(NULL);
3881 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003882
Jim Inghambb3a2832011-01-29 01:49:25 +00003883 case NextEventAction::eEventActionRetry:
3884 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003885
Jim Inghambb3a2832011-01-29 01:49:25 +00003886 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003887 // Handle Exiting Here. If we already got an exited event,
3888 // we should just propagate it. Otherwise, swallow this event,
3889 // and set our state to exit so the next event will kill us.
3890 if (new_state != eStateExited)
3891 {
3892 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003893 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003894 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003895 SetNextEventAction(NULL);
3896 return;
3897 }
3898 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003899 break;
3900 }
3901 }
3902
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003903 // See if we should broadcast this state to external clients?
3904 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003905
3906 if (should_broadcast)
3907 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003908 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003909 if (log)
3910 {
Daniel Malead01b2952012-11-29 21:49:15 +00003911 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003912 __FUNCTION__,
3913 GetID(),
3914 StateAsCString(new_state),
3915 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003916 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003917 }
Jim Ingham9575d842011-03-11 03:53:59 +00003918 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003919 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003920 {
3921 // Only push the input handler if we aren't fowarding events,
3922 // as this means the curses GUI is in use...
3923 if (!GetTarget().GetDebugger().IsForwardingEvents())
3924 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00003925 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00003926 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003927 else if (StateIsStoppedState(new_state, false))
3928 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00003929 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00003930 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3931 {
3932 // If the lldb_private::Debugger is handling the events, we don't
3933 // want to pop the process IOHandler here, we want to do it when
3934 // we receive the stopped event so we can carefully control when
3935 // the process IOHandler is popped because when we stop we want to
3936 // display some text stating how and why we stopped, then maybe some
3937 // process/thread/frame info, and then we want the "(lldb) " prompt
3938 // to show up. If we pop the process IOHandler here, then we will
3939 // cause the command interpreter to become the top IOHandler after
3940 // the process pops off and it will update its prompt right away...
3941 // See the Debugger.cpp file where it calls the function as
3942 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3943 // Otherwise we end up getting overlapping "(lldb) " prompts and
3944 // garbled output.
3945 //
3946 // If we aren't handling the events in the debugger (which is indicated
3947 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3948 // are hijacked, then we always pop the process IO handler manually.
3949 // Hijacking happens when the internal process state thread is running
3950 // thread plans, or when commands want to run in synchronous mode
3951 // and they call "process->WaitForProcessToStop()". An example of something
3952 // that will hijack the events is a simple expression:
3953 //
3954 // (lldb) expr (int)puts("hello")
3955 //
3956 // This will cause the internal process state thread to resume and halt
3957 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3958 // events) and we do need the IO handler to be pushed and popped
3959 // correctly.
3960
3961 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
3962 PopProcessIOHandler ();
3963 }
3964 }
Jim Ingham9575d842011-03-11 03:53:59 +00003965
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003966 BroadcastEvent (event_sp);
3967 }
3968 else
3969 {
3970 if (log)
3971 {
Daniel Malead01b2952012-11-29 21:49:15 +00003972 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003973 __FUNCTION__,
3974 GetID(),
3975 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003976 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003977 }
3978 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003979 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003980}
3981
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003982thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003983Process::PrivateStateThread (void *arg)
3984{
3985 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003986 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003987 return result;
3988}
3989
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003990thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991Process::RunPrivateStateThread ()
3992{
Jim Ingham076b3042012-04-10 01:21:57 +00003993 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003994 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003995
Greg Clayton5160ce52013-03-27 23:08:40 +00003996 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003997 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003998 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3999 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004000
4001 bool exit_now = false;
4002 while (!exit_now)
4003 {
4004 EventSP event_sp;
4005 WaitForEventsPrivate (NULL, event_sp, control_only);
4006 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4007 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004008 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004009 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4010 __FUNCTION__, static_cast<void*>(this), GetID(),
4011 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004012
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004013 switch (event_sp->GetType())
4014 {
4015 case eBroadcastInternalStateControlStop:
4016 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004017 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004018
4019 case eBroadcastInternalStateControlPause:
4020 control_only = true;
4021 break;
4022
4023 case eBroadcastInternalStateControlResume:
4024 control_only = false;
4025 break;
4026 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004027
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004028 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004029 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004030 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004031 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4032 {
4033 if (m_public_state.GetValue() == eStateAttaching)
4034 {
4035 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004036 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4037 __FUNCTION__, static_cast<void*>(this),
4038 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004039 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4040 }
4041 else
4042 {
4043 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004044 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4045 __FUNCTION__, static_cast<void*>(this),
4046 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004047 Halt();
4048 }
4049 continue;
4050 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051
4052 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4053
4054 if (internal_state != eStateInvalid)
4055 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004056 if (m_clear_thread_plans_on_stop &&
4057 StateIsStoppedState(internal_state, true))
4058 {
4059 m_clear_thread_plans_on_stop = false;
4060 m_thread_list.DiscardThreadPlans();
4061 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004062 HandlePrivateEvent (event_sp);
4063 }
4064
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004065 if (internal_state == eStateInvalid ||
4066 internal_state == eStateExited ||
4067 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004068 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004069 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004070 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4071 __FUNCTION__, static_cast<void*>(this), GetID(),
4072 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004075 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004076 }
4077
Caroline Tice20ad3c42010-10-29 21:48:37 +00004078 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004079 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004080 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4081 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004082
Ed Maste64fad602013-07-29 20:58:06 +00004083 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004084 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4085 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086 return NULL;
4087}
4088
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004089//------------------------------------------------------------------
4090// Process Event Data
4091//------------------------------------------------------------------
4092
4093Process::ProcessEventData::ProcessEventData () :
4094 EventData (),
4095 m_process_sp (),
4096 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004097 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004098 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004099 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100{
4101}
4102
4103Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4104 EventData (),
4105 m_process_sp (process_sp),
4106 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004107 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004108 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004109 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110{
4111}
4112
4113Process::ProcessEventData::~ProcessEventData()
4114{
4115}
4116
4117const ConstString &
4118Process::ProcessEventData::GetFlavorString ()
4119{
4120 static ConstString g_flavor ("Process::ProcessEventData");
4121 return g_flavor;
4122}
4123
4124const ConstString &
4125Process::ProcessEventData::GetFlavor () const
4126{
4127 return ProcessEventData::GetFlavorString ();
4128}
4129
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004130void
4131Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4132{
4133 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004134 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4135 // the public event queue, then other times when we're pretending that this is where we stopped at the
4136 // end of expression evaluation. m_update_state is used to distinguish these
4137 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004138 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004139 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004140 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004141
Jim Ingham221d51c2013-05-08 00:35:16 +00004142 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004143
4144 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4145 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4146 // end up restarting the process.
4147 if (m_interrupted)
4148 return;
4149
4150 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004151 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004152 {
4153 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004154 uint32_t num_threads = curr_thread_list.GetSize();
4155 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004156
Jim Ingham4b536182011-08-09 02:12:22 +00004157 // The actions might change one of the thread's stop_info's opinions about whether we should
4158 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004159
4160 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4161 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4162 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4163 // 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
4164 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004165 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004166 for (idx = 0; idx < num_threads; ++idx)
4167 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4168
Jim Inghamc7078c22012-12-13 22:24:15 +00004169 // Use this to track whether we should continue from here. We will only continue the target running if
4170 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4171 // then it doesn't matter what the other threads say...
4172
4173 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004174
Jim Ingham0ad7e052013-04-25 02:04:59 +00004175 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4176 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4177 // thing to do is, and it's better to let the user decide than continue behind their backs.
4178
4179 bool does_anybody_have_an_opinion = false;
4180
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004181 for (idx = 0; idx < num_threads; ++idx)
4182 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004183 curr_thread_list = m_process_sp->GetThreadList();
4184 if (curr_thread_list.GetSize() != num_threads)
4185 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004186 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004187 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004188 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 +00004189 break;
4190 }
4191
4192 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4193
4194 if (thread_sp->GetIndexID() != thread_index_array[idx])
4195 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004196 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004197 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004198 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004199 idx,
4200 thread_index_array[idx],
4201 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004202 break;
4203 }
4204
Jim Inghamb15bfc72010-10-20 00:39:53 +00004205 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004206 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004207 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004208 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004209 bool this_thread_wants_to_stop;
4210 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004211 {
Jim Ingham0161b492013-02-09 01:29:05 +00004212 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4213 }
4214 else
4215 {
4216 stop_info_sp->PerformAction(event_ptr);
4217 // The stop action might restart the target. If it does, then we want to mark that in the
4218 // event so that whoever is receiving it will know to wait for the running event and reflect
4219 // that state appropriately.
4220 // We also need to stop processing actions, since they aren't expecting the target to be running.
4221
4222 // FIXME: we might have run.
4223 if (stop_info_sp->HasTargetRunSinceMe())
4224 {
4225 SetRestarted (true);
4226 break;
4227 }
4228
4229 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004230 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004231
Jim Inghamc7078c22012-12-13 22:24:15 +00004232 if (still_should_stop == false)
4233 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004234 }
4235 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004236
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004237
Jim Inghama8ca6e22013-05-03 23:04:37 +00004238 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004239 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004240 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004241 {
4242 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004243 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004244 // Use the public resume method here, since this is just
4245 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004246 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004247 }
4248 else
4249 {
4250 // If we didn't restart, run the Stop Hooks here:
4251 // They might also restart the target, so watch for that.
4252 m_process_sp->GetTarget().RunStopHooks();
4253 if (m_process_sp->GetPrivateState() == eStateRunning)
4254 SetRestarted(true);
4255 }
Jim Ingham9575d842011-03-11 03:53:59 +00004256 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004257 }
4258}
4259
4260void
4261Process::ProcessEventData::Dump (Stream *s) const
4262{
4263 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004264 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4265 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004266
Greg Clayton8b82f082011-04-12 05:54:46 +00004267 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004268}
4269
4270const Process::ProcessEventData *
4271Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4272{
4273 if (event_ptr)
4274 {
4275 const EventData *event_data = event_ptr->GetData();
4276 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4277 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4278 }
4279 return NULL;
4280}
4281
4282ProcessSP
4283Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4284{
4285 ProcessSP process_sp;
4286 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4287 if (data)
4288 process_sp = data->GetProcessSP();
4289 return process_sp;
4290}
4291
4292StateType
4293Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4294{
4295 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4296 if (data == NULL)
4297 return eStateInvalid;
4298 else
4299 return data->GetState();
4300}
4301
4302bool
4303Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4304{
4305 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4306 if (data == NULL)
4307 return false;
4308 else
4309 return data->GetRestarted();
4310}
4311
4312void
4313Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4314{
4315 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4316 if (data != NULL)
4317 data->SetRestarted(new_value);
4318}
4319
Jim Ingham0161b492013-02-09 01:29:05 +00004320size_t
4321Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4322{
4323 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4324 if (data != NULL)
4325 return data->GetNumRestartedReasons();
4326 else
4327 return 0;
4328}
4329
4330const char *
4331Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4332{
4333 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4334 if (data != NULL)
4335 return data->GetRestartedReasonAtIndex(idx);
4336 else
4337 return NULL;
4338}
4339
4340void
4341Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4342{
4343 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4344 if (data != NULL)
4345 data->AddRestartedReason(reason);
4346}
4347
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004349Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4350{
4351 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4352 if (data == NULL)
4353 return false;
4354 else
4355 return data->GetInterrupted ();
4356}
4357
4358void
4359Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4360{
4361 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4362 if (data != NULL)
4363 data->SetInterrupted(new_value);
4364}
4365
4366bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004367Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4368{
4369 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4370 if (data)
4371 {
4372 data->SetUpdateStateOnRemoval();
4373 return true;
4374 }
4375 return false;
4376}
4377
Greg Claytond9e416c2012-02-18 05:35:26 +00004378lldb::TargetSP
4379Process::CalculateTarget ()
4380{
4381 return m_target.shared_from_this();
4382}
4383
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004384void
Greg Clayton0603aa92010-10-04 01:05:56 +00004385Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004386{
Greg Claytonc14ee322011-09-22 04:58:26 +00004387 exe_ctx.SetTargetPtr (&m_target);
4388 exe_ctx.SetProcessPtr (this);
4389 exe_ctx.SetThreadPtr(NULL);
4390 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391}
4392
Greg Claytone996fd32011-03-08 22:40:15 +00004393//uint32_t
4394//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4395//{
4396// return 0;
4397//}
4398//
4399//ArchSpec
4400//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4401//{
4402// return Host::GetArchSpecForExistingProcess (pid);
4403//}
4404//
4405//ArchSpec
4406//Process::GetArchSpecForExistingProcess (const char *process_name)
4407//{
4408// return Host::GetArchSpecForExistingProcess (process_name);
4409//}
4410//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004411void
4412Process::AppendSTDOUT (const char * s, size_t len)
4413{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004414 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004415 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004416 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004417}
4418
4419void
Greg Clayton93e86192011-11-13 04:45:22 +00004420Process::AppendSTDERR (const char * s, size_t len)
4421{
4422 Mutex::Locker locker (m_stdio_communication_mutex);
4423 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004424 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004425}
4426
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004427void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004428Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004429{
4430 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004431 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004432 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4433}
4434
4435size_t
4436Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4437{
4438 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004439 if (m_profile_data.empty())
4440 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004441
4442 std::string &one_profile_data = m_profile_data.front();
4443 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004444 if (bytes_available > 0)
4445 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004446 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004447 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004448 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4449 static_cast<void*>(buf),
4450 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004451 if (bytes_available > buf_size)
4452 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004453 memcpy(buf, one_profile_data.c_str(), buf_size);
4454 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004455 bytes_available = buf_size;
4456 }
4457 else
4458 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004459 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004460 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004461 }
4462 }
4463 return bytes_available;
4464}
4465
4466
Greg Clayton93e86192011-11-13 04:45:22 +00004467//------------------------------------------------------------------
4468// Process STDIO
4469//------------------------------------------------------------------
4470
4471size_t
4472Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4473{
4474 Mutex::Locker locker(m_stdio_communication_mutex);
4475 size_t bytes_available = m_stdout_data.size();
4476 if (bytes_available > 0)
4477 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004478 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004479 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004480 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4481 static_cast<void*>(buf),
4482 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004483 if (bytes_available > buf_size)
4484 {
4485 memcpy(buf, m_stdout_data.c_str(), buf_size);
4486 m_stdout_data.erase(0, buf_size);
4487 bytes_available = buf_size;
4488 }
4489 else
4490 {
4491 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4492 m_stdout_data.clear();
4493 }
4494 }
4495 return bytes_available;
4496}
4497
4498
4499size_t
4500Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4501{
4502 Mutex::Locker locker(m_stdio_communication_mutex);
4503 size_t bytes_available = m_stderr_data.size();
4504 if (bytes_available > 0)
4505 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004506 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004507 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004508 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4509 static_cast<void*>(buf),
4510 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004511 if (bytes_available > buf_size)
4512 {
4513 memcpy(buf, m_stderr_data.c_str(), buf_size);
4514 m_stderr_data.erase(0, buf_size);
4515 bytes_available = buf_size;
4516 }
4517 else
4518 {
4519 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4520 m_stderr_data.clear();
4521 }
4522 }
4523 return bytes_available;
4524}
4525
4526void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004527Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4528{
4529 Process *process = (Process *) baton;
4530 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4531}
4532
Greg Clayton44d93782014-01-27 23:43:24 +00004533class IOHandlerProcessSTDIO :
4534 public IOHandler
4535{
4536public:
4537 IOHandlerProcessSTDIO (Process *process,
4538 int write_fd) :
4539 IOHandler(process->GetTarget().GetDebugger()),
4540 m_process (process),
4541 m_read_file (),
4542 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004543 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004544 {
4545 m_read_file.SetDescriptor(GetInputFD(), false);
4546 }
4547
4548 virtual
4549 ~IOHandlerProcessSTDIO ()
4550 {
4551
4552 }
4553
4554 bool
4555 OpenPipes ()
4556 {
Greg Clayton100eb932014-07-02 21:10:39 +00004557 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004558 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004559 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004560 }
4561
4562 void
4563 ClosePipes()
4564 {
Greg Clayton100eb932014-07-02 21:10:39 +00004565 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004566 }
4567
4568 // Each IOHandler gets to run until it is done. It should read data
4569 // from the "in" and place output into "out" and "err and return
4570 // when done.
4571 virtual void
4572 Run ()
4573 {
4574 if (m_read_file.IsValid() && m_write_file.IsValid())
4575 {
4576 SetIsDone(false);
4577 if (OpenPipes())
4578 {
4579 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004580 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004581 TerminalState terminal_state;
4582 terminal_state.Save (read_fd, false);
4583 Terminal terminal(read_fd);
4584 terminal.SetCanonical(false);
4585 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004586// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004587#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004588 while (!GetIsDone())
4589 {
4590 fd_set read_fdset;
4591 FD_ZERO (&read_fdset);
4592 FD_SET (read_fd, &read_fdset);
4593 FD_SET (pipe_read_fd, &read_fdset);
4594 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4595 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4596 if (num_set_fds < 0)
4597 {
4598 const int select_errno = errno;
4599
4600 if (select_errno != EINTR)
4601 SetIsDone(true);
4602 }
4603 else if (num_set_fds > 0)
4604 {
4605 char ch = 0;
4606 size_t n;
4607 if (FD_ISSET (read_fd, &read_fdset))
4608 {
4609 n = 1;
4610 if (m_read_file.Read(&ch, n).Success() && n == 1)
4611 {
4612 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4613 SetIsDone(true);
4614 }
4615 else
4616 SetIsDone(true);
4617 }
4618 if (FD_ISSET (pipe_read_fd, &read_fdset))
4619 {
4620 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004621 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004622 {
Greg Clayton100eb932014-07-02 21:10:39 +00004623 switch (ch)
4624 {
4625 case 'q':
4626 SetIsDone(true);
4627 break;
4628 case 'i':
4629 if (StateIsRunningState(m_process->GetState()))
4630 m_process->Halt();
4631 break;
4632 }
Greg Clayton19e11352014-02-26 22:47:33 +00004633 }
Greg Clayton44d93782014-01-27 23:43:24 +00004634 }
4635 }
4636 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004637#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004638 terminal_state.Restore();
4639
4640 }
4641 else
4642 SetIsDone(true);
4643 }
4644 else
4645 SetIsDone(true);
4646 }
4647
4648 // Hide any characters that have been displayed so far so async
4649 // output can be displayed. Refresh() will be called after the
4650 // output has been displayed.
4651 virtual void
4652 Hide ()
4653 {
4654
4655 }
4656 // Called when the async output has been received in order to update
4657 // the input reader (refresh the prompt and redisplay any current
4658 // line(s) that are being edited
4659 virtual void
4660 Refresh ()
4661 {
4662
4663 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004664
Greg Clayton44d93782014-01-27 23:43:24 +00004665 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004666 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004667 {
Greg Clayton19e11352014-02-26 22:47:33 +00004668 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004669 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004670 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004671
Greg Claytonf0066ad2014-05-02 00:45:31 +00004672 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004673 Interrupt ()
4674 {
Greg Clayton19e11352014-02-26 22:47:33 +00004675 // Do only things that are safe to do in an interrupt context (like in
4676 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4677 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4678 // that was written to the pipe and then call m_process->Halt() from a
4679 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004680 if (m_active)
4681 {
4682 char ch = 'i'; // Send 'i' for interrupt
4683 return m_pipe.Write (&ch, 1) == 1;
4684 }
4685 else
4686 {
4687 // This IOHandler might be pushed on the stack, but not being run currently
4688 // so do the right thing if we aren't actively watching for STDIN by sending
4689 // the interrupt to the process. Otherwise the write to the pipe above would
4690 // do nothing. This can happen when the command interpreter is running and
4691 // gets a "expression ...". It will be on the IOHandler thread and sending
4692 // the input is complete to the delegate which will cause the expression to
4693 // run, which will push the process IO handler, but not run it.
4694
4695 if (StateIsRunningState(m_process->GetState()))
4696 {
4697 m_process->SendAsyncInterrupt();
4698 return true;
4699 }
4700 }
4701 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004702 }
Greg Clayton44d93782014-01-27 23:43:24 +00004703
4704 virtual void
4705 GotEOF()
4706 {
4707
4708 }
4709
4710protected:
4711 Process *m_process;
4712 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4713 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004714 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004715};
4716
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004717void
Greg Clayton44d93782014-01-27 23:43:24 +00004718Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004719{
4720 // First set up the Read Thread for reading/handling process I/O
4721
Greg Clayton44d93782014-01-27 23:43:24 +00004722 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004723
4724 if (conn_ap.get())
4725 {
4726 m_stdio_communication.SetConnection (conn_ap.release());
4727 if (m_stdio_communication.IsConnected())
4728 {
4729 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4730 m_stdio_communication.StartReadThread();
4731
4732 // Now read thread is set up, set up input reader.
4733
4734 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004735 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004736 }
4737 }
4738}
4739
Greg Claytonb4874f12014-02-28 18:22:24 +00004740bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004741Process::ProcessIOHandlerIsActive ()
4742{
4743 IOHandlerSP io_handler_sp (m_process_input_reader);
4744 if (io_handler_sp)
4745 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4746 return false;
4747}
4748bool
Greg Clayton44d93782014-01-27 23:43:24 +00004749Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004750{
Greg Clayton44d93782014-01-27 23:43:24 +00004751 IOHandlerSP io_handler_sp (m_process_input_reader);
4752 if (io_handler_sp)
4753 {
4754 io_handler_sp->SetIsDone(false);
4755 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004756 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004757 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004758 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004759}
4760
Greg Claytonb4874f12014-02-28 18:22:24 +00004761bool
Greg Clayton44d93782014-01-27 23:43:24 +00004762Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004763{
Greg Clayton44d93782014-01-27 23:43:24 +00004764 IOHandlerSP io_handler_sp (m_process_input_reader);
4765 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004766 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4767 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004768}
4769
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004770// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004771void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004772Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004773{
Greg Clayton6920b522012-08-22 18:39:03 +00004774 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004775}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004776
Greg Clayton99d0faf2010-11-18 23:32:35 +00004777void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004778Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004779{
Greg Clayton6920b522012-08-22 18:39:03 +00004780 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004781}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004782
Jim Ingham1624a2d2014-05-05 02:26:40 +00004783ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004784Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004785 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004786 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004787 Stream &errors)
4788{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004789 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004790
Jim Ingham77787032011-01-20 02:03:18 +00004791 if (thread_plan_sp.get() == NULL)
4792 {
4793 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004794 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004795 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004796
Jim Ingham7d7931d2013-03-28 00:05:34 +00004797 if (!thread_plan_sp->ValidatePlan(NULL))
4798 {
4799 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004800 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004801 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004802
Greg Claytonc14ee322011-09-22 04:58:26 +00004803 if (exe_ctx.GetProcessPtr() != this)
4804 {
4805 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004806 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004807 }
4808
4809 Thread *thread = exe_ctx.GetThreadPtr();
4810 if (thread == NULL)
4811 {
4812 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004813 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004814 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004815
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004816 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4817 // For that to be true the plan can't be private - since private plans suppress themselves in the
4818 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004819
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004820 bool orig_plan_private = thread_plan_sp->GetPrivate();
4821 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004822
Jim Ingham444586b2011-01-24 06:34:17 +00004823 if (m_private_state.GetValue() != eStateStopped)
4824 {
4825 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004826 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004827 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004828
Jim Ingham66243842011-08-13 00:56:10 +00004829 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004830 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004831 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004832 if (!selected_frame_sp)
4833 {
4834 thread->SetSelectedFrame(0);
4835 selected_frame_sp = thread->GetSelectedFrame();
4836 if (!selected_frame_sp)
4837 {
4838 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004839 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004840 }
4841 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004842
Jim Ingham11b0e052013-02-19 23:22:45 +00004843 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004844
4845 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4846 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004847
Greg Claytonc14ee322011-09-22 04:58:26 +00004848 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004849
Jim Ingham66243842011-08-13 00:56:10 +00004850 uint32_t selected_tid;
4851 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004852 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004853 {
4854 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004855 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004856 }
4857 else
4858 {
4859 selected_tid = LLDB_INVALID_THREAD_ID;
4860 }
4861
Jim Ingham372787f2012-04-07 00:00:41 +00004862 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004863 lldb::StateType old_state;
4864 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004865
Greg Clayton5160ce52013-03-27 23:08:40 +00004866 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004867 if (Host::GetCurrentThread() == m_private_state_thread)
4868 {
Jim Ingham076b3042012-04-10 01:21:57 +00004869 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4870 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004871 // 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 +00004872 // we are fielding public events here.
4873 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004874 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 +00004875
Jim Ingham372787f2012-04-07 00:00:41 +00004876 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004877
4878 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4879 // returning control here.
4880 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4881 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4882 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4883 // do just what we want.
4884 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4885 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4886 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4887 old_state = m_public_state.GetValue();
4888 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004889
Jim Ingham076b3042012-04-10 01:21:57 +00004890 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004891 StartPrivateStateThread(true);
4892 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004893
Jim Ingham372787f2012-04-07 00:00:41 +00004894 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004895
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004896 if (options.GetDebug())
4897 {
4898 // In this case, we aren't actually going to run, we just want to stop right away.
4899 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4900 // FIXME: To make this prettier we should invent some stop reason for this, but that
4901 // is only cosmetic, and this functionality is only of use to lldb developers who can
4902 // live with not pretty...
4903 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004904 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004905 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004906
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004907 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004908
Sean Callanana46ec452012-07-11 21:31:24 +00004909 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004910
Jim Ingham77787032011-01-20 02:03:18 +00004911 {
Sean Callanana46ec452012-07-11 21:31:24 +00004912 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4913 // restored on exit to the function.
4914 //
4915 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4916 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004917
Sean Callanana46ec452012-07-11 21:31:24 +00004918 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004919
Jim Inghamf48169b2010-11-30 02:22:11 +00004920 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004921 {
4922 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004923 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004924 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004925 thread->GetIndexID(),
4926 thread->GetID(),
4927 s.GetData());
4928 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004929
Sean Callanana46ec452012-07-11 21:31:24 +00004930 bool got_event;
4931 lldb::EventSP event_sp;
4932 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004933
Sean Callanana46ec452012-07-11 21:31:24 +00004934 TimeValue* timeout_ptr = NULL;
4935 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004936
Jim Ingham0161b492013-02-09 01:29:05 +00004937 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 +00004938 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004939 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004940 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004941
Jim Ingham0161b492013-02-09 01:29:05 +00004942 // This is just for accounting:
4943 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004944
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004945 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00004946 uint32_t one_thread_timeout_usec;
4947 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00004948
4949 // If we are going to run all threads the whole time, or if we are only going to run one thread,
4950 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
4951 // first timeout already.
4952
4953 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00004954 {
4955 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00004956 one_thread_timeout_usec = 0;
4957 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00004958 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004959 else
Jim Ingham0161b492013-02-09 01:29:05 +00004960 {
Jim Inghamfd95f892014-04-22 01:41:52 +00004961 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004962
Jim Ingham914f4e72014-03-28 21:58:28 +00004963 // If the overall wait is forever, then we only need to set the one thread timeout:
4964 if (timeout_usec == 0)
4965 {
Ed Maste801335c2014-03-31 19:28:14 +00004966 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00004967 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00004968 else
Jim Inghamfd95f892014-04-22 01:41:52 +00004969 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00004970 }
Jim Ingham0161b492013-02-09 01:29:05 +00004971 else
4972 {
Jim Ingham914f4e72014-03-28 21:58:28 +00004973 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
4974 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
4975 uint64_t computed_one_thread_timeout;
4976 if (option_one_thread_timeout != 0)
4977 {
4978 if (timeout_usec < option_one_thread_timeout)
4979 {
4980 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004981 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00004982 }
4983 computed_one_thread_timeout = option_one_thread_timeout;
4984 }
4985 else
4986 {
4987 computed_one_thread_timeout = timeout_usec / 2;
4988 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
4989 computed_one_thread_timeout = default_one_thread_timeout_usec;
4990 }
Jim Inghamfd95f892014-04-22 01:41:52 +00004991 one_thread_timeout_usec = computed_one_thread_timeout;
4992 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
4993
Jim Ingham0161b492013-02-09 01:29:05 +00004994 }
Jim Ingham0161b492013-02-09 01:29:05 +00004995 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004996
4997 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00004998 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 +00004999 options.GetStopOthers(),
5000 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005001 before_first_timeout,
5002 one_thread_timeout_usec,
5003 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005004
Jim Ingham1460e4b2014-01-10 23:46:59 +00005005 // This isn't going to work if there are unfetched events on the queue.
5006 // Are there cases where we might want to run the remaining events here, and then try to
5007 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005008
Jim Ingham1460e4b2014-01-10 23:46:59 +00005009 Event *other_events = listener.PeekAtNextEvent();
5010 if (other_events != NULL)
5011 {
5012 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005013 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005014 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005015
Jim Ingham1460e4b2014-01-10 23:46:59 +00005016 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5017 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5018 // event coalescing to cause us to lose OUR running event...
5019 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005020
Jim Ingham8559a352012-11-26 23:52:18 +00005021 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5022 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005023
5024#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5025 // It's pretty much impossible to write test cases for things like:
5026 // One thread timeout expires, I go to halt, but the process already stopped
5027 // on the function call stop breakpoint. Turning on this define will make us not
5028 // fetch the first event till after the halt. So if you run a quick function, it will have
5029 // completed, and the completion event will be waiting, when you interrupt for halt.
5030 // The expression evaluation should still succeed.
5031 bool miss_first_event = true;
5032#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005033 TimeValue one_thread_timeout;
5034 TimeValue final_timeout;
5035
Jim Ingham35878c42014-04-08 21:33:21 +00005036
Sean Callanana46ec452012-07-11 21:31:24 +00005037 while (1)
5038 {
5039 // We usually want to resume the process if we get to the top of the loop.
5040 // The only exception is if we get two running events with no intervening
5041 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005042 if (log)
5043 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5044 do_resume,
5045 handle_running_event,
5046 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005047
Jim Ingham184e9812013-01-15 02:47:48 +00005048 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005049 {
5050 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005051
Jim Ingham184e9812013-01-15 02:47:48 +00005052 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005053 {
Jim Ingham0161b492013-02-09 01:29:05 +00005054 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005055 Error resume_error = PrivateResume ();
5056 if (!resume_error.Success())
5057 {
Jim Ingham0161b492013-02-09 01:29:05 +00005058 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5059 num_resumes,
5060 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005061 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005062 break;
5063 }
Sean Callanana46ec452012-07-11 21:31:24 +00005064 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005065
Jim Ingham0161b492013-02-09 01:29:05 +00005066 TimeValue resume_timeout = TimeValue::Now();
5067 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005068
Jim Ingham0161b492013-02-09 01:29:05 +00005069 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005070 if (!got_event)
5071 {
5072 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005073 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5074 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005075
Jim Ingham0161b492013-02-09 01:29:05 +00005076 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005077 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005078 break;
5079 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005080
Sean Callanana46ec452012-07-11 21:31:24 +00005081 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005082
Sean Callanana46ec452012-07-11 21:31:24 +00005083 if (stop_state != eStateRunning)
5084 {
Jim Ingham0161b492013-02-09 01:29:05 +00005085 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005086
Jim Ingham0161b492013-02-09 01:29:05 +00005087 if (stop_state == eStateStopped)
5088 {
5089 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5090 if (log)
5091 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5092 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5093 num_resumes,
5094 StateAsCString(stop_state),
5095 restarted,
5096 do_resume,
5097 handle_running_event);
5098 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005099
Jim Ingham0161b492013-02-09 01:29:05 +00005100 if (restarted)
5101 {
5102 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5103 // event here. But if I do, the best thing is to Halt and then get out of here.
5104 Halt();
5105 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005106
Jim Ingham35e1bda2012-10-16 21:41:58 +00005107 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5108 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005109 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005110 break;
5111 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005112
Sean Callanana46ec452012-07-11 21:31:24 +00005113 if (log)
5114 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5115 // We need to call the function synchronously, so spin waiting for it to return.
5116 // If we get interrupted while executing, we're going to lose our context, and
5117 // won't be able to gather the result at this point.
5118 // We set the timeout AFTER the resume, since the resume takes some time and we
5119 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005120 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005121 else
5122 {
Sean Callanana46ec452012-07-11 21:31:24 +00005123 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005124 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005125 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005126
Jim Ingham0161b492013-02-09 01:29:05 +00005127 if (before_first_timeout)
5128 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005129 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005130 {
5131 one_thread_timeout = TimeValue::Now();
5132 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005133 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005134 }
Jim Ingham0161b492013-02-09 01:29:05 +00005135 else
5136 {
5137 if (timeout_usec == 0)
5138 timeout_ptr = NULL;
5139 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005140 {
5141 final_timeout = TimeValue::Now();
5142 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005143 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005144 }
Jim Ingham0161b492013-02-09 01:29:05 +00005145 }
5146 }
5147 else
5148 {
5149 if (timeout_usec == 0)
5150 timeout_ptr = NULL;
5151 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005152 {
5153 final_timeout = TimeValue::Now();
5154 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005155 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005156 }
Jim Ingham0161b492013-02-09 01:29:05 +00005157 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005158
Jim Ingham0161b492013-02-09 01:29:05 +00005159 do_resume = true;
5160 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005161
Sean Callanana46ec452012-07-11 21:31:24 +00005162 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005163 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005164
Jim Ingham0f16e732011-02-08 05:20:59 +00005165 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005166 {
Sean Callanana46ec452012-07-11 21:31:24 +00005167 if (timeout_ptr)
5168 {
Matt Kopec676a4872013-02-21 23:55:31 +00005169 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005170 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5171 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005172 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005173 else
Sean Callanana46ec452012-07-11 21:31:24 +00005174 {
5175 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5176 }
5177 }
Jim Ingham35878c42014-04-08 21:33:21 +00005178
5179#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5180 // See comment above...
5181 if (miss_first_event)
5182 {
5183 usleep(1000);
5184 miss_first_event = false;
5185 got_event = false;
5186 }
5187 else
5188#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005189 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005190
Sean Callanana46ec452012-07-11 21:31:24 +00005191 if (got_event)
5192 {
5193 if (event_sp.get())
5194 {
5195 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005196 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005197 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005198 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005199 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005200 errors.Printf ("Execution halted by user interrupt.");
5201 if (log)
5202 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005203 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005204 }
5205 else
5206 {
5207 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5208 if (log)
5209 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005210
Jim Inghamcfc09352012-07-27 23:57:19 +00005211 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005212 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005213 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005214 {
Jim Ingham0161b492013-02-09 01:29:05 +00005215 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005216 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5217 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005218 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005219 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005220 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005221 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005222 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005223 }
5224 else
5225 {
Jim Ingham0161b492013-02-09 01:29:05 +00005226 // If we were restarted, we just need to go back up to fetch another event.
5227 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005228 {
5229 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005230 {
5231 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5232 }
5233 keep_going = true;
5234 do_resume = false;
5235 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005236
Jim Inghamcfc09352012-07-27 23:57:19 +00005237 }
5238 else
5239 {
Jim Ingham0161b492013-02-09 01:29:05 +00005240 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5241 StopReason stop_reason = eStopReasonInvalid;
5242 if (stop_info_sp)
5243 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005244
Jim Ingham0161b492013-02-09 01:29:05 +00005245 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5246 // it is OUR plan that is complete?
5247 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005248 {
5249 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005250 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5251 // Now mark this plan as private so it doesn't get reported as the stop reason
5252 // after this point.
5253 if (thread_plan_sp)
5254 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005255 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005256 }
5257 else
5258 {
Jim Ingham0161b492013-02-09 01:29:05 +00005259 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005260 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005261 {
5262 if (log)
5263 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005264 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005265 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005266 {
5267 event_to_broadcast_sp = event_sp;
5268 }
Jim Ingham0161b492013-02-09 01:29:05 +00005269 }
Jim Ingham184e9812013-01-15 02:47:48 +00005270 else
Jim Ingham0161b492013-02-09 01:29:05 +00005271 {
5272 if (log)
5273 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005274 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005275 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005276 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005277 }
Jim Ingham184e9812013-01-15 02:47:48 +00005278 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005279 }
Sean Callanana46ec452012-07-11 21:31:24 +00005280 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005281 }
5282 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005283
Jim Inghamcfc09352012-07-27 23:57:19 +00005284 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005285 // This shouldn't really happen, but sometimes we do get two running events without an
5286 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005287 do_resume = false;
5288 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005289 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005290 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005291
Jim Inghamcfc09352012-07-27 23:57:19 +00005292 default:
5293 if (log)
5294 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005295
Jim Inghamcfc09352012-07-27 23:57:19 +00005296 if (stop_state == eStateExited)
5297 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005298
Sean Callananbf154da2012-08-08 17:35:10 +00005299 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005300 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005301 break;
5302 }
Sean Callanana46ec452012-07-11 21:31:24 +00005303 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005304
Sean Callanana46ec452012-07-11 21:31:24 +00005305 if (keep_going)
5306 continue;
5307 else
5308 break;
5309 }
5310 else
5311 {
5312 if (log)
5313 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005314 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005315 break;
5316 }
5317 }
5318 else
5319 {
5320 // If we didn't get an event that means we've timed out...
5321 // We will interrupt the process here. Depending on what we were asked to do we will
5322 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005323
Sean Callanana46ec452012-07-11 21:31:24 +00005324 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005325 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005326 {
Jim Ingham0161b492013-02-09 01:29:05 +00005327 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005328 {
5329 if (timeout_usec != 0)
5330 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005331 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005332 "running for %" PRIu32 " usec with all threads enabled.",
5333 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005334 }
5335 else
5336 {
5337 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005338 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005339 }
5340 }
Sean Callanana46ec452012-07-11 21:31:24 +00005341 else
5342 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005343 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005344 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005345 }
5346 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005347 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005348 "abandoning execution.",
5349 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005350 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005351
Jim Ingham0161b492013-02-09 01:29:05 +00005352 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5353 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5354 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5355 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5356 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005357
Jim Ingham0161b492013-02-09 01:29:05 +00005358 bool back_to_top = true;
5359 uint32_t try_halt_again = 0;
5360 bool do_halt = true;
5361 const uint32_t num_retries = 5;
5362 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005363 {
Jim Ingham0161b492013-02-09 01:29:05 +00005364 Error halt_error;
5365 if (do_halt)
5366 {
5367 if (log)
5368 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5369 halt_error = Halt();
5370 }
5371 if (halt_error.Success())
5372 {
5373 if (log)
5374 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005375
Jim Ingham0161b492013-02-09 01:29:05 +00005376 real_timeout = TimeValue::Now();
5377 real_timeout.OffsetWithMicroSeconds(500000);
5378
5379 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005380
Jim Ingham0161b492013-02-09 01:29:05 +00005381 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005382 {
Jim Ingham0161b492013-02-09 01:29:05 +00005383 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5384 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005385 {
Jim Ingham0161b492013-02-09 01:29:05 +00005386 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5387 if (stop_state == lldb::eStateStopped
5388 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5389 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005390 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005391
Jim Ingham0161b492013-02-09 01:29:05 +00005392 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005393 {
Jim Ingham0161b492013-02-09 01:29:05 +00005394 // Between the time we initiated the Halt and the time we delivered it, the process could have
5395 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005396
Jim Ingham0161b492013-02-09 01:29:05 +00005397 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5398 {
5399 if (log)
5400 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5401 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005402 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005403 back_to_top = false;
5404 break;
5405 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005406
Jim Ingham0161b492013-02-09 01:29:05 +00005407 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5408 {
5409 if (log)
5410 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5411 "Exiting wait loop.");
5412 try_halt_again++;
5413 do_halt = false;
5414 continue;
5415 }
Sean Callanana46ec452012-07-11 21:31:24 +00005416
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005417 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005418 {
5419 if (log)
5420 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005421 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005422 back_to_top = false;
5423 break;
5424 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005425
Jim Ingham0161b492013-02-09 01:29:05 +00005426 if (before_first_timeout)
5427 {
5428 // Set all the other threads to run, and return to the top of the loop, which will continue;
5429 before_first_timeout = false;
5430 thread_plan_sp->SetStopOthers (false);
5431 if (log)
5432 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005433
Jim Ingham0161b492013-02-09 01:29:05 +00005434 back_to_top = true;
5435 break;
5436 }
5437 else
5438 {
5439 // Running all threads failed, so return Interrupted.
5440 if (log)
5441 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005442 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005443 back_to_top = false;
5444 break;
5445 }
Sean Callanana46ec452012-07-11 21:31:24 +00005446 }
5447 }
5448 else
Jim Ingham0161b492013-02-09 01:29:05 +00005449 { if (log)
5450 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5451 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005452 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005453 back_to_top = false;
5454 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005455 }
5456 }
Jim Ingham0161b492013-02-09 01:29:05 +00005457 else
5458 {
5459 try_halt_again++;
5460 continue;
5461 }
Sean Callanana46ec452012-07-11 21:31:24 +00005462 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005463
Jim Ingham0161b492013-02-09 01:29:05 +00005464 if (!back_to_top || try_halt_again > num_retries)
5465 break;
5466 else
5467 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005468 }
Sean Callanana46ec452012-07-11 21:31:24 +00005469 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005470
Sean Callanana46ec452012-07-11 21:31:24 +00005471 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5472 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5473 {
5474 StopPrivateStateThread();
5475 Error error;
5476 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005477 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005478 {
5479 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5480 }
5481 m_public_state.SetValueNoLock(old_state);
5482
5483 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005484
Jim Ingham184e9812013-01-15 02:47:48 +00005485 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5486 // could happen:
5487 // 1) The execution successfully completed
5488 // 2) We hit a breakpoint, and ignore_breakpoints was true
5489 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005490 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5491 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005492
Jim Ingham8646d3c2014-05-05 02:47:44 +00005493 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005494 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005495 {
5496 thread_plan_sp->RestoreThreadState();
5497 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005498
Sean Callanana46ec452012-07-11 21:31:24 +00005499 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005500 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005501 {
5502 if (log)
5503 {
5504 StreamString s;
5505 if (event_sp)
5506 event_sp->Dump (&s);
5507 else
5508 {
5509 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5510 }
5511
5512 StreamString ts;
5513
5514 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005515
Sean Callanana46ec452012-07-11 21:31:24 +00005516 do
5517 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005518 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005519 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005520 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005521 break;
5522 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005523 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005524 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005525 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005526 break;
5527 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005528 else
Sean Callanana46ec452012-07-11 21:31:24 +00005529 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005530 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5531
5532 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005533 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005534 event_explanation = "<no event data>";
5535 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005536 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005537
Jim Inghamcfc09352012-07-27 23:57:19 +00005538 Process *process = event_data->GetProcessSP().get();
5539
5540 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005541 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005542 event_explanation = "<no process>";
5543 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005544 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005545
Jim Inghamcfc09352012-07-27 23:57:19 +00005546 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005547
Jim Inghamcfc09352012-07-27 23:57:19 +00005548 uint32_t num_threads = thread_list.GetSize();
5549 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005550
Jim Inghamcfc09352012-07-27 23:57:19 +00005551 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005552
Jim Inghamcfc09352012-07-27 23:57:19 +00005553 for (thread_index = 0;
5554 thread_index < num_threads;
5555 ++thread_index)
5556 {
5557 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005558
Jim Inghamcfc09352012-07-27 23:57:19 +00005559 if (!thread)
5560 {
5561 ts.Printf("<?> ");
5562 continue;
5563 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005564
Daniel Malead01b2952012-11-29 21:49:15 +00005565 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005566 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005567
Jim Inghamcfc09352012-07-27 23:57:19 +00005568 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005569 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005570 else
5571 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005572
Jim Inghamcfc09352012-07-27 23:57:19 +00005573 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5574 if (stop_info_sp)
5575 {
5576 const char *stop_desc = stop_info_sp->GetDescription();
5577 if (stop_desc)
5578 ts.PutCString (stop_desc);
5579 }
5580 ts.Printf(">");
5581 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005582
Jim Inghamcfc09352012-07-27 23:57:19 +00005583 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005584 }
Sean Callanana46ec452012-07-11 21:31:24 +00005585 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005586
Jim Inghamcfc09352012-07-27 23:57:19 +00005587 if (event_explanation)
5588 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005589 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005590 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5591 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005592
Jim Inghame4483cf2013-09-27 01:13:01 +00005593 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005594 {
5595 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005596 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5597 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005598 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5599 thread_plan_sp->SetPrivate (orig_plan_private);
5600 }
5601 else
5602 {
5603 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005604 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5605 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005606 }
5607 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005608 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005609 {
5610 if (log)
5611 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005612
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005613 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005614 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005615 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005616 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005617 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005618 }
5619 else
5620 {
Sean Callanana46ec452012-07-11 21:31:24 +00005621 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005622 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005623 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005624 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005625 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005626 }
5627 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5628 {
5629 if (log)
5630 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005631 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005632 }
5633 else
5634 {
5635 if (log)
5636 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005637 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005638 {
5639 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005640 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005641 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5642 thread_plan_sp->SetPrivate (orig_plan_private);
5643 }
5644 }
5645 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005646
Sean Callanana46ec452012-07-11 21:31:24 +00005647 // Thread we ran the function in may have gone away because we ran the target
5648 // Check that it's still there, and if it is put it back in the context. Also restore the
5649 // frame in the context if it is still present.
5650 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5651 if (thread)
5652 {
5653 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5654 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005655
Sean Callanana46ec452012-07-11 21:31:24 +00005656 // Also restore the current process'es selected frame & thread, since this function calling may
5657 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005658
Sean Callanana46ec452012-07-11 21:31:24 +00005659 if (selected_tid != LLDB_INVALID_THREAD_ID)
5660 {
5661 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5662 {
5663 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005664 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005665 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005666 if (old_frame_sp)
5667 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005668 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005669 }
5670 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005671
Sean Callanana46ec452012-07-11 21:31:24 +00005672 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005673
Sean Callanana46ec452012-07-11 21:31:24 +00005674 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005675 {
Sean Callanana46ec452012-07-11 21:31:24 +00005676 if (log)
5677 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5678 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005679 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005680
Jim Inghamf48169b2010-11-30 02:22:11 +00005681 return return_value;
5682}
5683
5684const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005685Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005686{
5687 const char *result_name;
5688
5689 switch (result)
5690 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005691 case eExpressionCompleted:
5692 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005693 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005694 case eExpressionDiscarded:
5695 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005696 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005697 case eExpressionInterrupted:
5698 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005699 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005700 case eExpressionHitBreakpoint:
5701 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005702 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005703 case eExpressionSetupError:
5704 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005705 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005706 case eExpressionParseError:
5707 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005708 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005709 case eExpressionResultUnavailable:
5710 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005711 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005712 case eExpressionTimedOut:
5713 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005714 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005715 case eExpressionStoppedForDebug:
5716 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005717 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005718 }
5719 return result_name;
5720}
5721
Greg Clayton7260f622011-04-18 08:33:37 +00005722void
5723Process::GetStatus (Stream &strm)
5724{
5725 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005726 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005727 {
5728 if (state == eStateExited)
5729 {
5730 int exit_status = GetExitStatus();
5731 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005732 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005733 GetID(),
5734 exit_status,
5735 exit_status,
5736 exit_description ? exit_description : "");
5737 }
5738 else
5739 {
5740 if (state == eStateConnected)
5741 strm.Printf ("Connected to remote target.\n");
5742 else
Daniel Malead01b2952012-11-29 21:49:15 +00005743 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005744 }
5745 }
5746 else
5747 {
Daniel Malead01b2952012-11-29 21:49:15 +00005748 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005749 }
5750}
5751
5752size_t
5753Process::GetThreadStatus (Stream &strm,
5754 bool only_threads_with_stop_reason,
5755 uint32_t start_frame,
5756 uint32_t num_frames,
5757 uint32_t num_frames_with_source)
5758{
5759 size_t num_thread_infos_dumped = 0;
5760
Jim Ingham4a65fb12014-03-07 11:20:03 +00005761 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5762 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5763 // ID's, and look them up one by one:
5764
5765 uint32_t num_threads;
5766 std::vector<uint32_t> thread_index_array;
5767 //Scope for thread list locker;
5768 {
5769 Mutex::Locker locker (GetThreadList().GetMutex());
5770 ThreadList &curr_thread_list = GetThreadList();
5771 num_threads = curr_thread_list.GetSize();
5772 uint32_t idx;
5773 thread_index_array.resize(num_threads);
5774 for (idx = 0; idx < num_threads; ++idx)
5775 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5776 }
5777
Greg Clayton7260f622011-04-18 08:33:37 +00005778 for (uint32_t i = 0; i < num_threads; i++)
5779 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005780 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5781 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005782 {
5783 if (only_threads_with_stop_reason)
5784 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005785 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005786 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005787 continue;
5788 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005789 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005790 start_frame,
5791 num_frames,
5792 num_frames_with_source);
5793 ++num_thread_infos_dumped;
5794 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005795 else
5796 {
5797 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5798 if (log)
5799 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5800
5801 }
Greg Clayton7260f622011-04-18 08:33:37 +00005802 }
5803 return num_thread_infos_dumped;
5804}
5805
Greg Claytona9f40ad2012-02-22 04:37:26 +00005806void
5807Process::AddInvalidMemoryRegion (const LoadRange &region)
5808{
5809 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5810}
5811
5812bool
5813Process::RemoveInvalidMemoryRange (const LoadRange &region)
5814{
5815 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5816}
5817
Jim Ingham372787f2012-04-07 00:00:41 +00005818void
5819Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5820{
5821 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5822}
5823
5824bool
5825Process::RunPreResumeActions ()
5826{
5827 bool result = true;
5828 while (!m_pre_resume_actions.empty())
5829 {
5830 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5831 m_pre_resume_actions.pop_back();
5832 bool this_result = action.callback (action.baton);
5833 if (result == true) result = this_result;
5834 }
5835 return result;
5836}
5837
5838void
5839Process::ClearPreResumeActions ()
5840{
5841 m_pre_resume_actions.clear();
5842}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005843
Greg Claytonfa559e52012-05-18 02:38:05 +00005844void
5845Process::Flush ()
5846{
5847 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005848 m_extended_thread_list.Flush();
5849 m_extended_thread_stop_id = 0;
5850 m_queue_list.Clear();
5851 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005852}
Greg Clayton90ba8112012-12-05 00:16:59 +00005853
5854void
5855Process::DidExec ()
5856{
5857 Target &target = GetTarget();
5858 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005859 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005860 m_dynamic_checkers_ap.reset();
5861 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005862 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005863 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005864 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005865 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005866 m_image_tokens.clear();
5867 m_allocated_memory_cache.Clear();
5868 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005869 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005870 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005871 DoDidExec();
5872 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005873 // Flush the process (threads and all stack frames) after running CompleteAttach()
5874 // in case the dynamic loader loaded things in new locations.
5875 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005876
5877 // After we figure out what was loaded/unloaded in CompleteAttach,
5878 // we need to let the target know so it can do any cleanup it needs to.
5879 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005880}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005881
Jim Ingham1460e4b2014-01-10 23:46:59 +00005882addr_t
5883Process::ResolveIndirectFunction(const Address *address, Error &error)
5884{
5885 if (address == nullptr)
5886 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005887 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005888 return LLDB_INVALID_ADDRESS;
5889 }
5890
5891 addr_t function_addr = LLDB_INVALID_ADDRESS;
5892
5893 addr_t addr = address->GetLoadAddress(&GetTarget());
5894 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5895 if (iter != m_resolved_indirect_addresses.end())
5896 {
5897 function_addr = (*iter).second;
5898 }
5899 else
5900 {
5901 if (!InferiorCall(this, address, function_addr))
5902 {
5903 Symbol *symbol = address->CalculateSymbolContextSymbol();
5904 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5905 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5906 function_addr = LLDB_INVALID_ADDRESS;
5907 }
5908 else
5909 {
5910 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5911 }
5912 }
5913 return function_addr;
5914}
5915
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005916void
5917Process::ModulesDidLoad (ModuleList &module_list)
5918{
5919 SystemRuntime *sys_runtime = GetSystemRuntime();
5920 if (sys_runtime)
5921 {
5922 sys_runtime->ModulesDidLoad (module_list);
5923 }
5924
5925 GetJITLoaders().ModulesDidLoad (module_list);
5926}