blob: 4092aa7f80bfc6d5c822cb28e4bf27abe521c729 [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
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000405 {
406 FileAction action;
407 if (action.Open (STDIN_FILENO, option_arg, true, false))
408 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000410 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000411
412 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000413 {
414 FileAction action;
415 if (action.Open (STDOUT_FILENO, option_arg, false, true))
416 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000417 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000418 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000419
420 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000421 {
422 FileAction action;
423 if (action.Open (STDERR_FILENO, option_arg, false, true))
424 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000425 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000426 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000427
Greg Clayton8b82f082011-04-12 05:54:46 +0000428 case 'p': // Process plug-in name
429 launch_info.SetProcessPluginName (option_arg);
430 break;
431
432 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000433 {
434 FileAction action;
435 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
436 launch_info.AppendFileAction (action);
437 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
438 launch_info.AppendFileAction (action);
439 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
440 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000441 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000442 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000443
444 case 'w':
445 launch_info.SetWorkingDirectory (option_arg);
446 break;
447
448 case 't': // Open process in new terminal window
449 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
450 break;
451
452 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000453 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
454 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000455 break;
456
Todd Fiala51637922014-08-19 17:40:43 +0000457 case 'A': // Disable ASLR.
458 {
459 bool success;
460 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
461 if (success)
462 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
463 else
464 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000465 break;
Todd Fiala51637922014-08-19 17:40:43 +0000466 }
467
468 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000469 if (option_arg && option_arg[0])
470 launch_info.SetShell (option_arg);
471 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000472 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000473 break;
474
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 case 'v':
476 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
477 break;
478
479 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000480 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000481 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000482 }
483 return error;
484}
485
486OptionDefinition
487ProcessLaunchCommandOptions::g_option_table[] =
488{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000489{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
Todd Fiala51637922014-08-19 17:40:43 +0000490{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000491{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
492{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
493{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
494{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
495{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000496
Zachary Turnerd37221d2014-07-09 16:31:49 +0000497{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
498{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
499{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000500
Zachary Turnerd37221d2014-07-09 16:31:49 +0000501{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000502
Zachary Turnerd37221d2014-07-09 16:31:49 +0000503{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000504
Zachary Turnerd37221d2014-07-09 16:31:49 +0000505{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000506};
507
508
509
510bool
511ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000512{
513 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
514 return true;
515 const char *match_name = m_match_info.GetName();
516 if (!match_name)
517 return true;
518
519 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
520}
521
522bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000523ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000524{
525 if (!NameMatches (proc_info.GetName()))
526 return false;
527
528 if (m_match_info.ProcessIDIsValid() &&
529 m_match_info.GetProcessID() != proc_info.GetProcessID())
530 return false;
531
532 if (m_match_info.ParentProcessIDIsValid() &&
533 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
534 return false;
535
Greg Clayton8b82f082011-04-12 05:54:46 +0000536 if (m_match_info.UserIDIsValid () &&
537 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000538 return false;
539
Greg Clayton8b82f082011-04-12 05:54:46 +0000540 if (m_match_info.GroupIDIsValid () &&
541 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000542 return false;
543
544 if (m_match_info.EffectiveUserIDIsValid () &&
545 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
546 return false;
547
548 if (m_match_info.EffectiveGroupIDIsValid () &&
549 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
550 return false;
551
552 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000553 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000554 return false;
555 return true;
556}
557
558bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000559ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000560{
561 if (m_name_match_type != eNameMatchIgnore)
562 return false;
563
564 if (m_match_info.ProcessIDIsValid())
565 return false;
566
567 if (m_match_info.ParentProcessIDIsValid())
568 return false;
569
Greg Clayton8b82f082011-04-12 05:54:46 +0000570 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000571 return false;
572
Greg Clayton8b82f082011-04-12 05:54:46 +0000573 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000574 return false;
575
576 if (m_match_info.EffectiveUserIDIsValid ())
577 return false;
578
579 if (m_match_info.EffectiveGroupIDIsValid ())
580 return false;
581
582 if (m_match_info.GetArchitecture().IsValid())
583 return false;
584
585 if (m_match_all_users)
586 return false;
587
588 return true;
589
590}
591
592void
Greg Clayton8b82f082011-04-12 05:54:46 +0000593ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000594{
595 m_match_info.Clear();
596 m_name_match_type = eNameMatchIgnore;
597 m_match_all_users = false;
598}
Greg Clayton58be07b2011-01-07 06:08:19 +0000599
Greg Claytonc3776bf2012-02-09 06:16:32 +0000600ProcessSP
601Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000602{
Greg Clayton949e8222013-01-16 17:29:04 +0000603 static uint32_t g_process_unique_id = 0;
604
Greg Claytonc3776bf2012-02-09 06:16:32 +0000605 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606 ProcessCreateInstance create_callback = NULL;
607 if (plugin_name)
608 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000609 ConstString const_plugin_name(plugin_name);
610 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000611 if (create_callback)
612 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000613 process_sp = create_callback(target, listener, crash_file_path);
614 if (process_sp)
615 {
Greg Clayton949e8222013-01-16 17:29:04 +0000616 if (process_sp->CanDebug(target, true))
617 {
618 process_sp->m_process_unique_id = ++g_process_unique_id;
619 }
620 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000621 process_sp.reset();
622 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623 }
624 }
625 else
626 {
Greg Claytonc982c762010-07-09 20:39:50 +0000627 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000629 process_sp = create_callback(target, listener, crash_file_path);
630 if (process_sp)
631 {
Greg Clayton949e8222013-01-16 17:29:04 +0000632 if (process_sp->CanDebug(target, false))
633 {
634 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000635 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000636 }
637 else
638 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000639 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 }
641 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000642 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643}
644
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000645ConstString &
646Process::GetStaticBroadcasterClass ()
647{
648 static ConstString class_name ("lldb.process");
649 return class_name;
650}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651
652//----------------------------------------------------------------------
653// Process constructor
654//----------------------------------------------------------------------
655Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000656 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000658 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000659 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 m_public_state (eStateUnloaded),
661 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000662 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
663 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 m_private_state_listener ("lldb.process.internal_state_listener"),
665 m_private_state_control_wait(),
666 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000667 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000668 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000670 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671 m_exit_status (-1),
672 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000673 m_thread_mutex (Mutex::eMutexTypeRecursive),
674 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000676 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000677 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000678 m_queue_list (this),
679 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000681 m_image_tokens (),
682 m_listener (listener),
683 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000684 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000685 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000686 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000687 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000688 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000689 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000690 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000691 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000692 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
693 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000694 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000695 m_memory_cache (*this),
696 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000697 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000698 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000699 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000700 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000701 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000702 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000703 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000704 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000705 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000706 m_destroy_in_process (false),
707 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000709 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000710
Greg Clayton5160ce52013-03-27 23:08:40 +0000711 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000713 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000715 SetEventName (eBroadcastBitStateChanged, "state-changed");
716 SetEventName (eBroadcastBitInterrupt, "interrupt");
717 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
718 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000719 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000720
Greg Clayton35a4cc52012-10-29 20:52:08 +0000721 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
722 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
723 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
724
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 listener.StartListeningForEvents (this,
726 eBroadcastBitStateChanged |
727 eBroadcastBitInterrupt |
728 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000729 eBroadcastBitSTDERR |
730 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731
732 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000733 eBroadcastBitStateChanged |
734 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735
736 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
737 eBroadcastInternalStateControlStop |
738 eBroadcastInternalStateControlPause |
739 eBroadcastInternalStateControlResume);
740}
741
742//----------------------------------------------------------------------
743// Destructor
744//----------------------------------------------------------------------
745Process::~Process()
746{
Greg Clayton5160ce52013-03-27 23:08:40 +0000747 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000749 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750 StopPrivateStateThread();
751}
752
Greg Clayton67cc0632012-08-22 17:17:09 +0000753const ProcessPropertiesSP &
754Process::GetGlobalProperties()
755{
756 static ProcessPropertiesSP g_settings_sp;
757 if (!g_settings_sp)
758 g_settings_sp.reset (new ProcessProperties (true));
759 return g_settings_sp;
760}
761
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762void
763Process::Finalize()
764{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000765 switch (GetPrivateState())
766 {
767 case eStateConnected:
768 case eStateAttaching:
769 case eStateLaunching:
770 case eStateStopped:
771 case eStateRunning:
772 case eStateStepping:
773 case eStateCrashed:
774 case eStateSuspended:
775 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000776 {
777 // FIXME: This will have to be a process setting:
778 bool keep_stopped = false;
779 Detach(keep_stopped);
780 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000781 else
782 Destroy();
783 break;
784
785 case eStateInvalid:
786 case eStateUnloaded:
787 case eStateDetached:
788 case eStateExited:
789 break;
790 }
791
Greg Clayton1ed54f52011-10-01 00:45:15 +0000792 // Clear our broadcaster before we proceed with destroying
793 Broadcaster::Clear();
794
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 // Do any cleanup needed prior to being destructed... Subclasses
796 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000797
798 // We need to destroy the loader before the derived Process class gets destroyed
799 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000800 m_dynamic_checkers_ap.reset();
801 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000802 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000803 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000804 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000805 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000806 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000807 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000808 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000809 m_queue_list.Clear();
810 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000811 std::vector<Notifications> empty_notifications;
812 m_notifications.swap(empty_notifications);
813 m_image_tokens.clear();
814 m_memory_cache.Clear();
815 m_allocated_memory_cache.Clear();
816 m_language_runtimes.clear();
817 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000818//#ifdef LLDB_CONFIGURATION_DEBUG
819// StreamFile s(stdout, false);
820// EventSP event_sp;
821// while (m_private_state_listener.GetNextEvent(event_sp))
822// {
823// event_sp->Dump (&s);
824// s.EOL();
825// }
826//#endif
827 // We have to be very careful here as the m_private_state_listener might
828 // contain events that have ProcessSP values in them which can keep this
829 // process around forever. These events need to be cleared out.
830 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000831 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
832 m_public_run_lock.SetStopped();
833 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
834 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000835 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000836}
837
838void
839Process::RegisterNotificationCallbacks (const Notifications& callbacks)
840{
841 m_notifications.push_back(callbacks);
842 if (callbacks.initialize != NULL)
843 callbacks.initialize (callbacks.baton, this);
844}
845
846bool
847Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
848{
849 std::vector<Notifications>::iterator pos, end = m_notifications.end();
850 for (pos = m_notifications.begin(); pos != end; ++pos)
851 {
852 if (pos->baton == callbacks.baton &&
853 pos->initialize == callbacks.initialize &&
854 pos->process_state_changed == callbacks.process_state_changed)
855 {
856 m_notifications.erase(pos);
857 return true;
858 }
859 }
860 return false;
861}
862
863void
864Process::SynchronouslyNotifyStateChanged (StateType state)
865{
866 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
867 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
868 {
869 if (notification_pos->process_state_changed)
870 notification_pos->process_state_changed (notification_pos->baton, this, state);
871 }
872}
873
874// FIXME: We need to do some work on events before the general Listener sees them.
875// For instance if we are continuing from a breakpoint, we need to ensure that we do
876// the little "insert real insn, step & stop" trick. But we can't do that when the
877// event is delivered by the broadcaster - since that is done on the thread that is
878// waiting for new events, so if we needed more than one event for our handling, we would
879// stall. So instead we do it when we fetch the event off of the queue.
880//
881
882StateType
883Process::GetNextEvent (EventSP &event_sp)
884{
885 StateType state = eStateInvalid;
886
887 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
888 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
889
890 return state;
891}
892
Todd Fialaa3b89e22014-08-12 14:33:19 +0000893bool
894Process::SyncIOHandler (uint64_t timeout_msec)
895{
896 bool timed_out = false;
897
898 // don't sync (potentially context switch) in case where there is no process IO
899 if (m_process_input_reader)
900 {
901 TimeValue timeout = TimeValue::Now();
902 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
903
904 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
905
906 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
907 if(log)
908 {
909 if(timed_out)
910 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
911 else
912 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
913 }
914
915 // reset sync one-shot so it will be ready for next time
916 m_iohandler_sync.SetValue(false, eBroadcastNever);
917 }
918
919 return !timed_out;
920}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921
922StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000923Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000924{
Jim Ingham4b536182011-08-09 02:12:22 +0000925 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
926 // We have to actually check each event, and in the case of a stopped event check the restarted flag
927 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000928 if (event_sp_ptr)
929 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000930 StateType state = GetState();
931 // If we are exited or detached, we won't ever get back to any
932 // other valid state...
933 if (state == eStateDetached || state == eStateExited)
934 return state;
935
Daniel Malea9e9919f2013-10-09 16:56:28 +0000936 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
937 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000938 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
939 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000940
941 if (!wait_always &&
942 StateIsStoppedState(state, true) &&
943 StateIsStoppedState(GetPrivateState(), true)) {
944 if (log)
945 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
946 __FUNCTION__);
947 return state;
948 }
949
Jim Ingham4b536182011-08-09 02:12:22 +0000950 while (state != eStateInvalid)
951 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000952 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000953 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000954 if (event_sp_ptr && event_sp)
955 *event_sp_ptr = event_sp;
956
Jim Ingham4b536182011-08-09 02:12:22 +0000957 switch (state)
958 {
959 case eStateCrashed:
960 case eStateDetached:
961 case eStateExited:
962 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000963 // We need to toggle the run lock as this won't get done in
964 // SetPublicState() if the process is hijacked.
965 if (hijack_listener)
966 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000967 return state;
968 case eStateStopped:
969 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
970 continue;
971 else
Greg Clayton44d93782014-01-27 23:43:24 +0000972 {
973 // We need to toggle the run lock as this won't get done in
974 // SetPublicState() if the process is hijacked.
975 if (hijack_listener)
976 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000977 return state;
Greg Clayton44d93782014-01-27 23:43:24 +0000978 }
Jim Ingham4b536182011-08-09 02:12:22 +0000979 default:
980 continue;
981 }
982 }
983 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984}
985
986
987StateType
988Process::WaitForState
989(
990 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +0000991 const StateType *match_states,
992 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993)
994{
995 EventSP event_sp;
996 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000997 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998 while (state != eStateInvalid)
999 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001000 // If we are exited or detached, we won't ever get back to any
1001 // other valid state...
1002 if (state == eStateDetached || state == eStateExited)
1003 return state;
1004
Greg Clayton44d93782014-01-27 23:43:24 +00001005 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006
1007 for (i=0; i<num_match_states; ++i)
1008 {
1009 if (match_states[i] == state)
1010 return state;
1011 }
1012 }
1013 return state;
1014}
1015
Jim Ingham30f9b212010-10-11 23:53:14 +00001016bool
1017Process::HijackProcessEvents (Listener *listener)
1018{
1019 if (listener != NULL)
1020 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001021 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001022 }
1023 else
1024 return false;
1025}
1026
1027void
1028Process::RestoreProcessEvents ()
1029{
1030 RestoreBroadcaster();
1031}
1032
Jim Ingham0f16e732011-02-08 05:20:59 +00001033bool
1034Process::HijackPrivateProcessEvents (Listener *listener)
1035{
1036 if (listener != NULL)
1037 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001038 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001039 }
1040 else
1041 return false;
1042}
1043
1044void
1045Process::RestorePrivateProcessEvents ()
1046{
1047 m_private_state_broadcaster.RestoreBroadcaster();
1048}
1049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001051Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001052{
Greg Clayton5160ce52013-03-27 23:08:40 +00001053 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054
1055 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001056 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1057 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058
Greg Clayton44d93782014-01-27 23:43:24 +00001059 Listener *listener = hijack_listener;
1060 if (listener == NULL)
1061 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001062
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001064 if (listener->WaitForEventForBroadcasterWithType (timeout,
1065 this,
1066 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1067 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001068 {
1069 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1070 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1071 else if (log)
1072 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1073 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074
1075 if (log)
1076 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001077 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078 StateAsCString(state));
1079 return state;
1080}
1081
1082Event *
1083Process::PeekAtStateChangedEvents ()
1084{
Greg Clayton5160ce52013-03-27 23:08:40 +00001085 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086
1087 if (log)
1088 log->Printf ("Process::%s...", __FUNCTION__);
1089
1090 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001091 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1092 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001093 if (log)
1094 {
1095 if (event_ptr)
1096 {
1097 log->Printf ("Process::%s (event_ptr) => %s",
1098 __FUNCTION__,
1099 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1100 }
1101 else
1102 {
1103 log->Printf ("Process::%s no events found",
1104 __FUNCTION__);
1105 }
1106 }
1107 return event_ptr;
1108}
1109
1110StateType
1111Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1112{
Greg Clayton5160ce52013-03-27 23:08:40 +00001113 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114
1115 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001116 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1117 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
1119 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001120 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1121 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001122 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001123 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001124 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1125 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126
1127 // This is a bit of a hack, but when we wait here we could very well return
1128 // to the command-line, and that could disable the log, which would render the
1129 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001130 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001131 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1132 __FUNCTION__, static_cast<const void *>(timeout),
1133 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 return state;
1135}
1136
1137bool
1138Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1139{
Greg Clayton5160ce52013-03-27 23:08:40 +00001140 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141
1142 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001143 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1144 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001145
1146 if (control_only)
1147 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1148 else
1149 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1150}
1151
1152bool
1153Process::IsRunning () const
1154{
1155 return StateIsRunningState (m_public_state.GetValue());
1156}
1157
1158int
1159Process::GetExitStatus ()
1160{
1161 if (m_public_state.GetValue() == eStateExited)
1162 return m_exit_status;
1163 return -1;
1164}
1165
Greg Clayton85851dd2010-12-04 00:10:17 +00001166
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167const char *
1168Process::GetExitDescription ()
1169{
1170 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1171 return m_exit_string.c_str();
1172 return NULL;
1173}
1174
Greg Clayton6779606a2011-01-22 23:43:18 +00001175bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176Process::SetExitStatus (int status, const char *cstr)
1177{
Greg Clayton5160ce52013-03-27 23:08:40 +00001178 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001179 if (log)
1180 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1181 status, status,
1182 cstr ? "\"" : "",
1183 cstr ? cstr : "NULL",
1184 cstr ? "\"" : "");
1185
Greg Clayton6779606a2011-01-22 23:43:18 +00001186 // We were already in the exited state
1187 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001188 {
Greg Clayton385d6032011-01-26 23:47:29 +00001189 if (log)
1190 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001191 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001192 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001193
1194 m_exit_status = status;
1195 if (cstr)
1196 m_exit_string = cstr;
1197 else
1198 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199
Greg Clayton6779606a2011-01-22 23:43:18 +00001200 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001201
Greg Clayton6779606a2011-01-22 23:43:18 +00001202 SetPrivateState (eStateExited);
1203 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204}
1205
1206// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001207// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208// found in the global target list (we want to be completely sure that the
1209// lldb_private::Process doesn't go away before we can deliver the signal.
1210bool
Greg Claytone4e45922011-11-16 05:37:56 +00001211Process::SetProcessExitStatus (void *callback_baton,
1212 lldb::pid_t pid,
1213 bool exited,
1214 int signo, // Zero for no signal
1215 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001216)
1217{
Greg Clayton5160ce52013-03-27 23:08:40 +00001218 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001219 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001220 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001221 callback_baton,
1222 pid,
1223 exited,
1224 signo,
1225 exit_status);
1226
1227 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001228 {
Greg Clayton66111032010-06-23 01:19:29 +00001229 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001230 if (target_sp)
1231 {
1232 ProcessSP process_sp (target_sp->GetProcessSP());
1233 if (process_sp)
1234 {
1235 const char *signal_cstr = NULL;
1236 if (signo)
1237 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1238
1239 process_sp->SetExitStatus (exit_status, signal_cstr);
1240 }
1241 }
1242 return true;
1243 }
1244 return false;
1245}
1246
1247
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001248void
1249Process::UpdateThreadListIfNeeded ()
1250{
1251 const uint32_t stop_id = GetStopID();
1252 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1253 {
Greg Clayton2637f822011-11-17 01:23:07 +00001254 const StateType state = GetPrivateState();
1255 if (StateIsStoppedState (state, true))
1256 {
1257 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001258 // m_thread_list does have its own mutex, but we need to
1259 // hold onto the mutex between the call to UpdateThreadList(...)
1260 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001261 ThreadList &old_thread_list = m_thread_list;
1262 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001263 ThreadList new_thread_list(this);
1264 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001265 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001266 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001267 {
Jim Ingham09437922013-03-01 20:04:25 +00001268 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1269 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1270 // shutting us down, causing a deadlock.
1271 if (!m_destroy_in_process)
1272 {
1273 OperatingSystem *os = GetOperatingSystem ();
1274 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001275 {
1276 // Clear any old backing threads where memory threads might have been
1277 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001278 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001279 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001280 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001281
1282 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001283 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1284 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1285 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 +00001286 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001287 else
1288 {
1289 // No OS plug-in, the new thread list is the same as the real thread list
1290 new_thread_list = real_thread_list;
1291 }
Jim Ingham09437922013-03-01 20:04:25 +00001292 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001293
1294 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001295 m_thread_list.Update (new_thread_list);
1296 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001297
Jason Molenda4ff13262013-11-20 00:31:38 +00001298 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1299 {
1300 // Clear any extended threads that we may have accumulated previously
1301 m_extended_thread_list.Clear();
1302 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001303
1304 m_queue_list.Clear();
1305 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001306 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001307 }
Greg Clayton2637f822011-11-17 01:23:07 +00001308 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001309 }
1310}
1311
Jason Molenda5e8dce42013-12-13 00:29:16 +00001312void
1313Process::UpdateQueueListIfNeeded ()
1314{
1315 if (m_system_runtime_ap.get())
1316 {
1317 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1318 {
1319 const StateType state = GetPrivateState();
1320 if (StateIsStoppedState (state, true))
1321 {
1322 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1323 m_queue_list_stop_id = GetLastNaturalStopID();
1324 }
1325 }
1326 }
1327}
1328
Greg Claytona4d87472013-01-18 23:41:08 +00001329ThreadSP
1330Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1331{
1332 OperatingSystem *os = GetOperatingSystem ();
1333 if (os)
1334 return os->CreateThread(tid, context);
1335 return ThreadSP();
1336}
1337
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001338uint32_t
1339Process::GetNextThreadIndexID (uint64_t thread_id)
1340{
1341 return AssignIndexIDToThread(thread_id);
1342}
1343
1344bool
1345Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1346{
1347 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1348 if (iterator == m_thread_id_to_index_id_map.end())
1349 {
1350 return false;
1351 }
1352 else
1353 {
1354 return true;
1355 }
1356}
1357
1358uint32_t
1359Process::AssignIndexIDToThread(uint64_t thread_id)
1360{
1361 uint32_t result = 0;
1362 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1363 if (iterator == m_thread_id_to_index_id_map.end())
1364 {
1365 result = ++m_thread_index_id;
1366 m_thread_id_to_index_id_map[thread_id] = result;
1367 }
1368 else
1369 {
1370 result = iterator->second;
1371 }
1372
1373 return result;
1374}
1375
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376StateType
1377Process::GetState()
1378{
1379 // If any other threads access this we will need a mutex for it
1380 return m_public_state.GetValue ();
1381}
1382
1383void
Jim Ingham221d51c2013-05-08 00:35:16 +00001384Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001385{
Greg Clayton5160ce52013-03-27 23:08:40 +00001386 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001388 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001389 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001391
1392 // On the transition from Run to Stopped, we unlock the writer end of the
1393 // run lock. The lock gets locked in Resume, which is the public API
1394 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001395 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1396 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001397 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001398 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001399 if (log)
1400 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001401 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001402 }
1403 else
1404 {
1405 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1406 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001407 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001408 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001409 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001410 {
1411 if (log)
1412 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001413 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001414 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001415 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001416 }
1417 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418}
1419
Jim Ingham3b8285d2012-04-19 01:40:33 +00001420Error
1421Process::Resume ()
1422{
Greg Clayton5160ce52013-03-27 23:08:40 +00001423 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001424 if (log)
1425 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001426 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001427 {
1428 Error error("Resume request failed - process still running.");
1429 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001430 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001431 return error;
1432 }
1433 return PrivateResume();
1434}
1435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001436StateType
1437Process::GetPrivateState ()
1438{
1439 return m_private_state.GetValue();
1440}
1441
1442void
1443Process::SetPrivateState (StateType new_state)
1444{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001445 if (m_finalize_called)
1446 return;
1447
Greg Clayton5160ce52013-03-27 23:08:40 +00001448 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001449 bool state_changed = false;
1450
1451 if (log)
1452 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1453
Andrew Kaylor29d65742013-05-10 17:19:04 +00001454 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001455 Mutex::Locker locker(m_private_state.GetMutex());
1456
1457 const StateType old_state = m_private_state.GetValueNoLock ();
1458 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001459
Greg Claytonaa49c832013-05-03 22:25:56 +00001460 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1461 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1462 if (old_state_is_stopped != new_state_is_stopped)
1463 {
1464 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001465 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001466 else
Ed Maste64fad602013-07-29 20:58:06 +00001467 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001468 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001469
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470 if (state_changed)
1471 {
1472 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001473 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001475 // Note, this currently assumes that all threads in the list
1476 // stop when the process stops. In the future we will want to
1477 // support a debugging model where some threads continue to run
1478 // while others are stopped. When that happens we will either need
1479 // a way for the thread list to identify which threads are stopping
1480 // or create a special thread list containing only threads which
1481 // actually stopped.
1482 //
1483 // The process plugin is responsible for managing the actual
1484 // behavior of the threads and should have stopped any threads
1485 // that are going to stop before we get here.
1486 m_thread_list.DidStop();
1487
Jim Ingham4b536182011-08-09 02:12:22 +00001488 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001489 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001491 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492 }
1493 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001494 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1495 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1496 else
1497 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 }
1499 else
1500 {
1501 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001502 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001503 }
1504}
1505
Jim Ingham0faa43f2011-11-08 03:00:11 +00001506void
1507Process::SetRunningUserExpression (bool on)
1508{
1509 m_mod_id.SetRunningUserExpression (on);
1510}
1511
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512addr_t
1513Process::GetImageInfoAddress()
1514{
1515 return LLDB_INVALID_ADDRESS;
1516}
1517
Greg Clayton8f343b02010-11-04 01:54:29 +00001518//----------------------------------------------------------------------
1519// LoadImage
1520//
1521// This function provides a default implementation that works for most
1522// unix variants. Any Process subclasses that need to do shared library
1523// loading differently should override LoadImage and UnloadImage and
1524// do what is needed.
1525//----------------------------------------------------------------------
1526uint32_t
1527Process::LoadImage (const FileSpec &image_spec, Error &error)
1528{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001529 char path[PATH_MAX];
1530 image_spec.GetPath(path, sizeof(path));
1531
Greg Clayton8f343b02010-11-04 01:54:29 +00001532 DynamicLoader *loader = GetDynamicLoader();
1533 if (loader)
1534 {
1535 error = loader->CanLoadImage();
1536 if (error.Fail())
1537 return LLDB_INVALID_IMAGE_TOKEN;
1538 }
1539
1540 if (error.Success())
1541 {
1542 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001543
1544 if (thread_sp)
1545 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001546 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001547
1548 if (frame_sp)
1549 {
1550 ExecutionContext exe_ctx;
1551 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001552 EvaluateExpressionOptions expr_options;
1553 expr_options.SetUnwindOnError(true);
1554 expr_options.SetIgnoreBreakpoints(true);
1555 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001556 expr_options.SetResultIsInternal(true);
1557
Greg Clayton8f343b02010-11-04 01:54:29 +00001558 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001559 expr.Printf(R"(
1560 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1561 the_result.image_ptr = dlopen ("%s", 2);
1562 if (the_result.image_ptr == (void *) 0x0)
1563 {
1564 the_result.error_str = dlerror();
1565 }
1566 else
1567 {
1568 the_result.error_str = (const char *) 0x0;
1569 }
1570 the_result;
1571 )",
1572 path);
1573 const char *prefix = R"(
1574 extern "C" void* dlopen (const char *path, int mode);
1575 extern "C" const char *dlerror (void);
1576 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001577 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001578 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001579 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001580 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001581 expr.GetData(),
1582 prefix,
1583 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001584 expr_error);
1585 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001586 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001587 error = result_valobj_sp->GetError();
1588 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001589 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001590 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001591 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1592 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001593 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001594 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1595 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1596 {
1597 uint32_t image_token = m_image_tokens.size();
1598 m_image_tokens.push_back (image_ptr);
1599 return image_token;
1600 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001601 else if (image_ptr == 0)
1602 {
Jim Ingham6971b862014-07-19 00:37:06 +00001603 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1604 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001605 {
Jim Ingham6971b862014-07-19 00:37:06 +00001606 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001607 {
Jim Inghamcf973792014-07-17 21:53:48 +00001608 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001609 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001610 if (error.Success() && num_chars > 0)
1611 {
1612 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001613 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001614 }
1615 }
1616 }
1617 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001618 }
1619 }
1620 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001621 else
1622 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001623 }
1624 }
1625 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001626 if (!error.AsCString())
1627 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001628 return LLDB_INVALID_IMAGE_TOKEN;
1629}
1630
1631//----------------------------------------------------------------------
1632// UnloadImage
1633//
1634// This function provides a default implementation that works for most
1635// unix variants. Any Process subclasses that need to do shared library
1636// loading differently should override LoadImage and UnloadImage and
1637// do what is needed.
1638//----------------------------------------------------------------------
1639Error
1640Process::UnloadImage (uint32_t image_token)
1641{
1642 Error error;
1643 if (image_token < m_image_tokens.size())
1644 {
1645 const addr_t image_addr = m_image_tokens[image_token];
1646 if (image_addr == LLDB_INVALID_ADDRESS)
1647 {
1648 error.SetErrorString("image already unloaded");
1649 }
1650 else
1651 {
1652 DynamicLoader *loader = GetDynamicLoader();
1653 if (loader)
1654 error = loader->CanLoadImage();
1655
1656 if (error.Success())
1657 {
1658 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001659
1660 if (thread_sp)
1661 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001662 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001663
1664 if (frame_sp)
1665 {
1666 ExecutionContext exe_ctx;
1667 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001668 EvaluateExpressionOptions expr_options;
1669 expr_options.SetUnwindOnError(true);
1670 expr_options.SetIgnoreBreakpoints(true);
1671 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001672 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001673 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001674 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001675 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001676 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001677 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001678 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001679 expr.GetData(),
1680 prefix,
1681 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001682 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001683 if (result_valobj_sp->GetError().Success())
1684 {
1685 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001686 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001687 {
1688 if (scalar.UInt(1))
1689 {
1690 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1691 }
1692 else
1693 {
1694 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1695 }
1696 }
1697 }
1698 else
1699 {
1700 error = result_valobj_sp->GetError();
1701 }
1702 }
1703 }
1704 }
1705 }
1706 }
1707 else
1708 {
1709 error.SetErrorString("invalid image token");
1710 }
1711 return error;
1712}
1713
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001714const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715Process::GetABI()
1716{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001717 if (!m_abi_sp)
1718 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1719 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001720}
1721
Jim Ingham22777012010-09-23 02:01:19 +00001722LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001723Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001724{
1725 LanguageRuntimeCollection::iterator pos;
1726 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001727 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001728 {
Jim Inghamab175242012-03-10 00:22:19 +00001729 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001730
Jim Inghamab175242012-03-10 00:22:19 +00001731 m_language_runtimes[language] = runtime_sp;
1732 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001733 }
1734 else
1735 return (*pos).second.get();
1736}
1737
1738CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001739Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001740{
Jim Inghamab175242012-03-10 00:22:19 +00001741 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001742 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1743 return static_cast<CPPLanguageRuntime *> (runtime);
1744 return NULL;
1745}
1746
1747ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001748Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001749{
Jim Inghamab175242012-03-10 00:22:19 +00001750 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001751 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1752 return static_cast<ObjCLanguageRuntime *> (runtime);
1753 return NULL;
1754}
1755
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001756bool
1757Process::IsPossibleDynamicValue (ValueObject& in_value)
1758{
1759 if (in_value.IsDynamic())
1760 return false;
1761 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1762
1763 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1764 {
1765 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1766 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1767 }
1768
1769 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1770 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1771 return true;
1772
1773 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1774 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1775}
1776
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001777BreakpointSiteList &
1778Process::GetBreakpointSiteList()
1779{
1780 return m_breakpoint_site_list;
1781}
1782
1783const BreakpointSiteList &
1784Process::GetBreakpointSiteList() const
1785{
1786 return m_breakpoint_site_list;
1787}
1788
1789
1790void
1791Process::DisableAllBreakpointSites ()
1792{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001793 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1794// bp_site->SetEnabled(true);
1795 DisableBreakpointSite(bp_site);
1796 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001797}
1798
1799Error
1800Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1801{
1802 Error error (DisableBreakpointSiteByID (break_id));
1803
1804 if (error.Success())
1805 m_breakpoint_site_list.Remove(break_id);
1806
1807 return error;
1808}
1809
1810Error
1811Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1812{
1813 Error error;
1814 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1815 if (bp_site_sp)
1816 {
1817 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001818 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 }
1820 else
1821 {
Daniel Malead01b2952012-11-29 21:49:15 +00001822 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 }
1824
1825 return error;
1826}
1827
1828Error
1829Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1830{
1831 Error error;
1832 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1833 if (bp_site_sp)
1834 {
1835 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001836 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 }
1838 else
1839 {
Daniel Malead01b2952012-11-29 21:49:15 +00001840 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841 }
1842 return error;
1843}
1844
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001845lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001846Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001847{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001848 addr_t load_addr = LLDB_INVALID_ADDRESS;
1849
1850 bool show_error = true;
1851 switch (GetState())
1852 {
1853 case eStateInvalid:
1854 case eStateUnloaded:
1855 case eStateConnected:
1856 case eStateAttaching:
1857 case eStateLaunching:
1858 case eStateDetached:
1859 case eStateExited:
1860 show_error = false;
1861 break;
1862
1863 case eStateStopped:
1864 case eStateRunning:
1865 case eStateStepping:
1866 case eStateCrashed:
1867 case eStateSuspended:
1868 show_error = IsAlive();
1869 break;
1870 }
1871
1872 // Reset the IsIndirect flag here, in case the location changes from
1873 // pointing to a indirect symbol to a regular symbol.
1874 owner->SetIsIndirect (false);
1875
1876 if (owner->ShouldResolveIndirectFunctions())
1877 {
1878 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1879 if (symbol && symbol->IsIndirect())
1880 {
1881 Error error;
1882 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1883 if (!error.Success() && show_error)
1884 {
Greg Clayton44d93782014-01-27 23:43:24 +00001885 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1886 symbol->GetAddress().GetLoadAddress(&m_target),
1887 owner->GetBreakpoint().GetID(),
1888 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001889 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001890 return LLDB_INVALID_BREAK_ID;
1891 }
1892 Address resolved_address(load_addr);
1893 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1894 owner->SetIsIndirect(true);
1895 }
1896 else
1897 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1898 }
1899 else
1900 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1901
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902 if (load_addr != LLDB_INVALID_ADDRESS)
1903 {
1904 BreakpointSiteSP bp_site_sp;
1905
1906 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1907 // create a new breakpoint site and add it.
1908
1909 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1910
1911 if (bp_site_sp)
1912 {
1913 bp_site_sp->AddOwner (owner);
1914 owner->SetBreakpointSite (bp_site_sp);
1915 return bp_site_sp->GetID();
1916 }
1917 else
1918 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001919 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001920 if (bp_site_sp)
1921 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001922 Error error = EnableBreakpointSite (bp_site_sp.get());
1923 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001924 {
1925 owner->SetBreakpointSite (bp_site_sp);
1926 return m_breakpoint_site_list.Add (bp_site_sp);
1927 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001928 else
1929 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001930 if (show_error)
1931 {
1932 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001933 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1934 load_addr,
1935 owner->GetBreakpoint().GetID(),
1936 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001937 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001938 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001939 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940 }
1941 }
1942 }
1943 // We failed to enable the breakpoint
1944 return LLDB_INVALID_BREAK_ID;
1945
1946}
1947
1948void
1949Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1950{
1951 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1952 if (num_owners == 0)
1953 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001954 // Don't try to disable the site if we don't have a live process anymore.
1955 if (IsAlive())
1956 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1958 }
1959}
1960
1961
1962size_t
1963Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1964{
1965 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001966 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001967
Jim Ingham20c77192011-06-29 19:42:28 +00001968 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001969 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001970 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1971 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001973 addr_t intersect_addr;
1974 size_t intersect_size;
1975 size_t opcode_offset;
1976 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001977 {
1978 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1979 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00001980 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001981 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00001982 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001983 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001984 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00001985 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986 }
1987 return bytes_removed;
1988}
1989
1990
Greg Claytonded470d2011-03-19 01:12:21 +00001991
1992size_t
1993Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1994{
1995 PlatformSP platform_sp (m_target.GetPlatform());
1996 if (platform_sp)
1997 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1998 return 0;
1999}
2000
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002001Error
2002Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2003{
2004 Error error;
2005 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002006 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 const addr_t bp_addr = bp_site->GetLoadAddress();
2008 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002009 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002010 if (bp_site->IsEnabled())
2011 {
2012 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002013 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 +00002014 return error;
2015 }
2016
2017 if (bp_addr == LLDB_INVALID_ADDRESS)
2018 {
2019 error.SetErrorString("BreakpointSite contains an invalid load address.");
2020 return error;
2021 }
2022 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2023 // trap for the breakpoint site
2024 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2025
2026 if (bp_opcode_size == 0)
2027 {
Daniel Malead01b2952012-11-29 21:49:15 +00002028 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029 }
2030 else
2031 {
2032 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2033
2034 if (bp_opcode_bytes == NULL)
2035 {
2036 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2037 return error;
2038 }
2039
2040 // Save the original opcode by reading it
2041 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2042 {
2043 // Write a software breakpoint in place of the original opcode
2044 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2045 {
2046 uint8_t verify_bp_opcode_bytes[64];
2047 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2048 {
2049 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2050 {
2051 bp_site->SetEnabled(true);
2052 bp_site->SetType (BreakpointSite::eSoftware);
2053 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002054 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055 bp_site->GetID(),
2056 (uint64_t)bp_addr);
2057 }
2058 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002059 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060 }
2061 else
2062 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2063 }
2064 else
2065 error.SetErrorString("Unable to write breakpoint trap to memory.");
2066 }
2067 else
2068 error.SetErrorString("Unable to read memory at breakpoint address.");
2069 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002070 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002071 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002072 bp_site->GetID(),
2073 (uint64_t)bp_addr,
2074 error.AsCString());
2075 return error;
2076}
2077
2078Error
2079Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2080{
2081 Error error;
2082 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002083 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002084 addr_t bp_addr = bp_site->GetLoadAddress();
2085 lldb::user_id_t breakID = bp_site->GetID();
2086 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002087 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088
2089 if (bp_site->IsHardware())
2090 {
2091 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2092 }
2093 else if (bp_site->IsEnabled())
2094 {
2095 const size_t break_op_size = bp_site->GetByteSize();
2096 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2097 if (break_op_size > 0)
2098 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002099 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002100 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002101 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102 bool break_op_found = false;
2103
2104 // Read the breakpoint opcode
2105 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2106 {
2107 bool verify = false;
2108 // Make sure we have the a breakpoint opcode exists at this address
2109 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2110 {
2111 break_op_found = true;
2112 // We found a valid breakpoint opcode at this address, now restore
2113 // the saved opcode.
2114 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2115 {
2116 verify = true;
2117 }
2118 else
2119 error.SetErrorString("Memory write failed when restoring original opcode.");
2120 }
2121 else
2122 {
2123 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2124 // Set verify to true and so we can check if the original opcode has already been restored
2125 verify = true;
2126 }
2127
2128 if (verify)
2129 {
Greg Claytonc982c762010-07-09 20:39:50 +00002130 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002131 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002132 // Verify that our original opcode made it back to the inferior
2133 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2134 {
2135 // compare the memory we just read with the original opcode
2136 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2137 {
2138 // SUCCESS
2139 bp_site->SetEnabled(false);
2140 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002141 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 +00002142 return error;
2143 }
2144 else
2145 {
2146 if (break_op_found)
2147 error.SetErrorString("Failed to restore original opcode.");
2148 }
2149 }
2150 else
2151 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2152 }
2153 }
2154 else
2155 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2156 }
2157 }
2158 else
2159 {
2160 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002161 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 +00002162 return error;
2163 }
2164
2165 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002166 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167 bp_site->GetID(),
2168 (uint64_t)bp_addr,
2169 error.AsCString());
2170 return error;
2171
2172}
2173
Greg Clayton58be07b2011-01-07 06:08:19 +00002174// Uncomment to verify memory caching works after making changes to caching code
2175//#define VERIFY_MEMORY_READS
2176
Sean Callanan64c0cf22012-06-07 22:26:42 +00002177size_t
2178Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2179{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002180 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002181 if (!GetDisableMemoryCache())
2182 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002183#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002184 // Memory caching is enabled, with debug verification
2185
2186 if (buf && size)
2187 {
2188 // Uncomment the line below to make sure memory caching is working.
2189 // I ran this through the test suite and got no assertions, so I am
2190 // pretty confident this is working well. If any changes are made to
2191 // memory caching, uncomment the line below and test your changes!
2192
2193 // Verify all memory reads by using the cache first, then redundantly
2194 // reading the same memory from the inferior and comparing to make sure
2195 // everything is exactly the same.
2196 std::string verify_buf (size, '\0');
2197 assert (verify_buf.size() == size);
2198 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2199 Error verify_error;
2200 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2201 assert (cache_bytes_read == verify_bytes_read);
2202 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2203 assert (verify_error.Success() == error.Success());
2204 return cache_bytes_read;
2205 }
2206 return 0;
2207#else // !defined(VERIFY_MEMORY_READS)
2208 // Memory caching is enabled, without debug verification
2209
2210 return m_memory_cache.Read (addr, buf, size, error);
2211#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002212 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002213 else
2214 {
2215 // Memory caching is disabled
2216
2217 return ReadMemoryFromInferior (addr, buf, size, error);
2218 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002219}
Greg Clayton58be07b2011-01-07 06:08:19 +00002220
Greg Clayton4c82d422012-05-18 23:20:01 +00002221size_t
2222Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2223{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002224 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002225 out_str.clear();
2226 addr_t curr_addr = addr;
2227 while (1)
2228 {
2229 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2230 if (length == 0)
2231 break;
2232 out_str.append(buf, length);
2233 // If we got "length - 1" bytes, we didn't get the whole C string, we
2234 // need to read some more characters
2235 if (length == sizeof(buf) - 1)
2236 curr_addr += length;
2237 else
2238 break;
2239 }
2240 return out_str.size();
2241}
2242
Greg Clayton58be07b2011-01-07 06:08:19 +00002243
2244size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002245Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2246 size_t type_width)
2247{
2248 size_t total_bytes_read = 0;
2249 if (dst && max_bytes && type_width && max_bytes >= type_width)
2250 {
2251 // Ensure a null terminator independent of the number of bytes that is read.
2252 memset (dst, 0, max_bytes);
2253 size_t bytes_left = max_bytes - type_width;
2254
2255 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2256 assert(sizeof(terminator) >= type_width &&
2257 "Attempting to validate a string with more than 4 bytes per character!");
2258
2259 addr_t curr_addr = addr;
2260 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2261 char *curr_dst = dst;
2262
2263 error.Clear();
2264 while (bytes_left > 0 && error.Success())
2265 {
2266 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2267 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2268 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2269
2270 if (bytes_read == 0)
2271 break;
2272
2273 // Search for a null terminator of correct size and alignment in bytes_read
2274 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2275 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2276 if (::strncmp(&dst[i], terminator, type_width) == 0)
2277 {
2278 error.Clear();
2279 return i;
2280 }
2281
2282 total_bytes_read += bytes_read;
2283 curr_dst += bytes_read;
2284 curr_addr += bytes_read;
2285 bytes_left -= bytes_read;
2286 }
2287 }
2288 else
2289 {
2290 if (max_bytes)
2291 error.SetErrorString("invalid arguments");
2292 }
2293 return total_bytes_read;
2294}
2295
2296// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2297// null terminators.
2298size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002299Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002300{
2301 size_t total_cstr_len = 0;
2302 if (dst && dst_max_len)
2303 {
Greg Claytone91b7952011-12-15 03:14:23 +00002304 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002305 // NULL out everything just to be safe
2306 memset (dst, 0, dst_max_len);
2307 Error error;
2308 addr_t curr_addr = addr;
2309 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2310 size_t bytes_left = dst_max_len - 1;
2311 char *curr_dst = dst;
2312
2313 while (bytes_left > 0)
2314 {
2315 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2316 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2317 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2318
2319 if (bytes_read == 0)
2320 {
Greg Claytone91b7952011-12-15 03:14:23 +00002321 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002322 dst[total_cstr_len] = '\0';
2323 break;
2324 }
2325 const size_t len = strlen(curr_dst);
2326
2327 total_cstr_len += len;
2328
2329 if (len < bytes_to_read)
2330 break;
2331
2332 curr_dst += bytes_read;
2333 curr_addr += bytes_read;
2334 bytes_left -= bytes_read;
2335 }
2336 }
Greg Claytone91b7952011-12-15 03:14:23 +00002337 else
2338 {
2339 if (dst == NULL)
2340 result_error.SetErrorString("invalid arguments");
2341 else
2342 result_error.Clear();
2343 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002344 return total_cstr_len;
2345}
2346
2347size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002348Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2349{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002350 if (buf == NULL || size == 0)
2351 return 0;
2352
2353 size_t bytes_read = 0;
2354 uint8_t *bytes = (uint8_t *)buf;
2355
2356 while (bytes_read < size)
2357 {
2358 const size_t curr_size = size - bytes_read;
2359 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2360 bytes + bytes_read,
2361 curr_size,
2362 error);
2363 bytes_read += curr_bytes_read;
2364 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2365 break;
2366 }
2367
2368 // Replace any software breakpoint opcodes that fall into this range back
2369 // into "buf" before we return
2370 if (bytes_read > 0)
2371 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2372 return bytes_read;
2373}
2374
Greg Clayton58a4c462010-12-16 20:01:20 +00002375uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002376Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002377{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002378 Scalar scalar;
2379 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2380 return scalar.ULongLong(fail_value);
2381 return fail_value;
2382}
2383
2384addr_t
2385Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2386{
2387 Scalar scalar;
2388 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2389 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2390 return LLDB_INVALID_ADDRESS;
2391}
2392
2393
2394bool
2395Process::WritePointerToMemory (lldb::addr_t vm_addr,
2396 lldb::addr_t ptr_value,
2397 Error &error)
2398{
2399 Scalar scalar;
2400 const uint32_t addr_byte_size = GetAddressByteSize();
2401 if (addr_byte_size <= 4)
2402 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002403 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002404 scalar = ptr_value;
2405 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002406}
2407
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002408size_t
2409Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2410{
2411 size_t bytes_written = 0;
2412 const uint8_t *bytes = (const uint8_t *)buf;
2413
2414 while (bytes_written < size)
2415 {
2416 const size_t curr_size = size - bytes_written;
2417 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2418 bytes + bytes_written,
2419 curr_size,
2420 error);
2421 bytes_written += curr_bytes_written;
2422 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2423 break;
2424 }
2425 return bytes_written;
2426}
2427
2428size_t
2429Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2430{
Greg Clayton58be07b2011-01-07 06:08:19 +00002431#if defined (ENABLE_MEMORY_CACHING)
2432 m_memory_cache.Flush (addr, size);
2433#endif
2434
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002435 if (buf == NULL || size == 0)
2436 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002437
Jim Ingham4b536182011-08-09 02:12:22 +00002438 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002439
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 // We need to write any data that would go where any current software traps
2441 // (enabled software breakpoints) any software traps (breakpoints) that we
2442 // may have placed in our tasks memory.
2443
Greg Claytond8cf1a12013-06-12 00:46:38 +00002444 BreakpointSiteList bp_sites_in_range;
2445
2446 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002447 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002448 // No breakpoint sites overlap
2449 if (bp_sites_in_range.IsEmpty())
2450 return WriteMemoryPrivate (addr, buf, size, error);
2451 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002453 const uint8_t *ubuf = (const uint8_t *)buf;
2454 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455
Greg Claytond8cf1a12013-06-12 00:46:38 +00002456 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2457
2458 if (error.Success())
2459 {
2460 addr_t intersect_addr;
2461 size_t intersect_size;
2462 size_t opcode_offset;
2463 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2464 assert(intersects);
2465 assert(addr <= intersect_addr && intersect_addr < addr + size);
2466 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2467 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2468
2469 // Check for bytes before this breakpoint
2470 const addr_t curr_addr = addr + bytes_written;
2471 if (intersect_addr > curr_addr)
2472 {
2473 // There are some bytes before this breakpoint that we need to
2474 // just write to memory
2475 size_t curr_size = intersect_addr - curr_addr;
2476 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2477 ubuf + bytes_written,
2478 curr_size,
2479 error);
2480 bytes_written += curr_bytes_written;
2481 if (curr_bytes_written != curr_size)
2482 {
2483 // We weren't able to write all of the requested bytes, we
2484 // are done looping and will return the number of bytes that
2485 // we have written so far.
2486 if (error.Success())
2487 error.SetErrorToGenericError();
2488 }
2489 }
2490 // Now write any bytes that would cover up any software breakpoints
2491 // directly into the breakpoint opcode buffer
2492 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2493 bytes_written += intersect_size;
2494 }
2495 });
2496
2497 if (bytes_written < size)
2498 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2499 ubuf + bytes_written,
2500 size - bytes_written,
2501 error);
2502 }
2503 }
2504 else
2505 {
2506 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507 }
2508
2509 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002510 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002511}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002512
2513size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002514Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002515{
2516 if (byte_size == UINT32_MAX)
2517 byte_size = scalar.GetByteSize();
2518 if (byte_size > 0)
2519 {
2520 uint8_t buf[32];
2521 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2522 if (mem_size > 0)
2523 return WriteMemory(addr, buf, mem_size, error);
2524 else
2525 error.SetErrorString ("failed to get scalar as memory data");
2526 }
2527 else
2528 {
2529 error.SetErrorString ("invalid scalar value");
2530 }
2531 return 0;
2532}
2533
2534size_t
2535Process::ReadScalarIntegerFromMemory (addr_t addr,
2536 uint32_t byte_size,
2537 bool is_signed,
2538 Scalar &scalar,
2539 Error &error)
2540{
Greg Clayton7060f892013-05-01 23:41:30 +00002541 uint64_t uval = 0;
2542 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002543 {
Greg Clayton7060f892013-05-01 23:41:30 +00002544 error.SetErrorString ("byte size is zero");
2545 }
2546 else if (byte_size & (byte_size - 1))
2547 {
2548 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2549 }
2550 else if (byte_size <= sizeof(uval))
2551 {
2552 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002553 if (bytes_read == byte_size)
2554 {
2555 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002556 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002557 if (byte_size <= 4)
2558 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002559 else
Greg Clayton7060f892013-05-01 23:41:30 +00002560 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002561 if (is_signed)
2562 scalar.SignExtend(byte_size * 8);
2563 return bytes_read;
2564 }
2565 }
2566 else
2567 {
2568 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2569 }
2570 return 0;
2571}
2572
Greg Claytond495c532011-05-17 03:37:42 +00002573#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002574addr_t
2575Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2576{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002577 if (GetPrivateState() != eStateStopped)
2578 return LLDB_INVALID_ADDRESS;
2579
Greg Claytond495c532011-05-17 03:37:42 +00002580#if defined (USE_ALLOCATE_MEMORY_CACHE)
2581 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2582#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002583 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002584 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002585 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002586 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 +00002587 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002588 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002589 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002590 m_mod_id.GetStopID(),
2591 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002592 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002593#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594}
2595
Sean Callanan90539452011-09-20 23:01:51 +00002596bool
2597Process::CanJIT ()
2598{
Sean Callanana7b443a2012-02-14 22:50:38 +00002599 if (m_can_jit == eCanJITDontKnow)
2600 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002601 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002602 Error err;
2603
2604 uint64_t allocated_memory = AllocateMemory(8,
2605 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2606 err);
2607
2608 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002609 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002610 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002611 if (log)
2612 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2613 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002614 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002615 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002616 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002617 if (log)
2618 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2619 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002620
2621 DeallocateMemory (allocated_memory);
2622 }
2623
Sean Callanan90539452011-09-20 23:01:51 +00002624 return m_can_jit == eCanJITYes;
2625}
2626
2627void
2628Process::SetCanJIT (bool can_jit)
2629{
2630 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2631}
2632
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633Error
2634Process::DeallocateMemory (addr_t ptr)
2635{
Greg Claytond495c532011-05-17 03:37:42 +00002636 Error error;
2637#if defined (USE_ALLOCATE_MEMORY_CACHE)
2638 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2639 {
Daniel Malead01b2952012-11-29 21:49:15 +00002640 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002641 }
2642#else
2643 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002644
Greg Clayton5160ce52013-03-27 23:08:40 +00002645 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002646 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002647 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 +00002648 ptr,
2649 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002650 m_mod_id.GetStopID(),
2651 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002652#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002653 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654}
2655
Han Ming Ongc811d382012-11-17 00:33:14 +00002656
Greg Claytonc9660542012-02-05 02:38:54 +00002657ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002658Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002659 lldb::addr_t header_addr,
2660 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002661{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002662 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002663 if (module_sp)
2664 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002665 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002666 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002667 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002668 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002669 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002670 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002671}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672
2673Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002674Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002675{
2676 Error error;
2677 error.SetErrorString("watchpoints are not supported");
2678 return error;
2679}
2680
2681Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002682Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002683{
2684 Error error;
2685 error.SetErrorString("watchpoints are not supported");
2686 return error;
2687}
2688
2689StateType
2690Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2691{
2692 StateType state;
2693 // Now wait for the process to launch and return control to us, and then
2694 // call DidLaunch:
2695 while (1)
2696 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002697 event_sp.reset();
2698 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2699
Greg Clayton2637f822011-11-17 01:23:07 +00002700 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002702
2703 // If state is invalid, then we timed out
2704 if (state == eStateInvalid)
2705 break;
2706
2707 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708 HandlePrivateEvent (event_sp);
2709 }
2710 return state;
2711}
2712
2713Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002714Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002715{
2716 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002718 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002719 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002720 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002721 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002722 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002723
Greg Claytonaa149cb2011-08-11 02:48:45 +00002724 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002725 if (exe_module)
2726 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002727 char local_exec_file_path[PATH_MAX];
2728 char platform_exec_file_path[PATH_MAX];
2729 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2730 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 if (exe_module->GetFileSpec().Exists())
2732 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002733 // Install anything that might need to be installed prior to launching.
2734 // For host systems, this will do nothing, but if we are connected to a
2735 // remote platform it will install any needed binaries
2736 error = GetTarget().Install(&launch_info);
2737 if (error.Fail())
2738 return error;
2739
Greg Clayton71337622011-02-24 22:24:29 +00002740 if (PrivateStateThreadIsValid ())
2741 PausePrivateStateThread ();
2742
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743 error = WillLaunch (exe_module);
2744 if (error.Success())
2745 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002746 const bool restarted = false;
2747 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002748 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749
Ed Maste64fad602013-07-29 20:58:06 +00002750 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002751 {
2752 // Now launch using these arguments.
2753 error = DoLaunch (exe_module, launch_info);
2754 }
2755 else
2756 {
2757 // This shouldn't happen
2758 error.SetErrorString("failed to acquire process run lock");
2759 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760
2761 if (error.Fail())
2762 {
2763 if (GetID() != LLDB_INVALID_PROCESS_ID)
2764 {
2765 SetID (LLDB_INVALID_PROCESS_ID);
2766 const char *error_string = error.AsCString();
2767 if (error_string == NULL)
2768 error_string = "launch failed";
2769 SetExitStatus (-1, error_string);
2770 }
2771 }
2772 else
2773 {
2774 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002775 TimeValue timeout_time;
2776 timeout_time = TimeValue::Now();
2777 timeout_time.OffsetWithSeconds(10);
2778 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002779
Greg Clayton1a38ea72011-06-22 01:42:17 +00002780 if (state == eStateInvalid || event_sp.get() == NULL)
2781 {
2782 // We were able to launch the process, but we failed to
2783 // catch the initial stop.
2784 SetExitStatus (0, "failed to catch stop after launch");
2785 Destroy();
2786 }
2787 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002790 DidLaunch ();
2791
Greg Claytonc859e2d2012-02-13 23:10:39 +00002792 DynamicLoader *dyld = GetDynamicLoader ();
2793 if (dyld)
2794 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002795
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002796 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002797
Jason Molendaeef51062013-11-05 03:57:19 +00002798 SystemRuntime *system_runtime = GetSystemRuntime ();
2799 if (system_runtime)
2800 system_runtime->DidLaunch();
2801
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002802 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803 // This delays passing the stopped event to listeners till DidLaunch gets
2804 // a chance to complete...
2805 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002806
2807 if (PrivateStateThreadIsValid ())
2808 ResumePrivateStateThread ();
2809 else
2810 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002811 }
2812 else if (state == eStateExited)
2813 {
2814 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2815 // not likely to work, and return an invalid pid.
2816 HandlePrivateEvent (event_sp);
2817 }
2818 }
2819 }
2820 }
2821 else
2822 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002823 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824 }
2825 }
2826 return error;
2827}
2828
Greg Claytonc3776bf2012-02-09 06:16:32 +00002829
2830Error
2831Process::LoadCore ()
2832{
2833 Error error = DoLoadCore();
2834 if (error.Success())
2835 {
2836 if (PrivateStateThreadIsValid ())
2837 ResumePrivateStateThread ();
2838 else
2839 StartPrivateStateThread ();
2840
Greg Claytonc859e2d2012-02-13 23:10:39 +00002841 DynamicLoader *dyld = GetDynamicLoader ();
2842 if (dyld)
2843 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002844
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002845 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002846
Jason Molendaeef51062013-11-05 03:57:19 +00002847 SystemRuntime *system_runtime = GetSystemRuntime ();
2848 if (system_runtime)
2849 system_runtime->DidAttach();
2850
Greg Claytonc859e2d2012-02-13 23:10:39 +00002851 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002852 // We successfully loaded a core file, now pretend we stopped so we can
2853 // show all of the threads in the core file and explore the crashed
2854 // state.
2855 SetPrivateState (eStateStopped);
2856
2857 }
2858 return error;
2859}
2860
Greg Claytonc859e2d2012-02-13 23:10:39 +00002861DynamicLoader *
2862Process::GetDynamicLoader ()
2863{
2864 if (m_dyld_ap.get() == NULL)
2865 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2866 return m_dyld_ap.get();
2867}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002868
Todd Fialaaf245d12014-06-30 21:05:18 +00002869const lldb::DataBufferSP
2870Process::GetAuxvData()
2871{
2872 return DataBufferSP ();
2873}
2874
Andrew MacPherson17220c12014-03-05 10:12:43 +00002875JITLoaderList &
2876Process::GetJITLoaders ()
2877{
2878 if (!m_jit_loaders_ap)
2879 {
2880 m_jit_loaders_ap.reset(new JITLoaderList());
2881 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2882 }
2883 return *m_jit_loaders_ap;
2884}
2885
Jason Molendaeef51062013-11-05 03:57:19 +00002886SystemRuntime *
2887Process::GetSystemRuntime ()
2888{
2889 if (m_system_runtime_ap.get() == NULL)
2890 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2891 return m_system_runtime_ap.get();
2892}
2893
Greg Claytonc3776bf2012-02-09 06:16:32 +00002894
Jim Inghambb3a2832011-01-29 01:49:25 +00002895Process::NextEventAction::EventActionResult
2896Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897{
Jim Inghambb3a2832011-01-29 01:49:25 +00002898 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2899 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002900 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002901 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002902 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002903 return eEventActionRetry;
2904
2905 case eStateStopped:
2906 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002907 {
2908 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002909 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002910 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002911 // We don't want these events to be reported, so go set the ShouldReportStop here:
2912 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2913
Greg Claytonc9ed4782011-11-12 02:10:56 +00002914 if (m_exec_count > 0)
2915 {
2916 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00002917 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002918 return eEventActionRetry;
2919 }
2920 else
2921 {
2922 m_process->CompleteAttach ();
2923 return eEventActionSuccess;
2924 }
2925 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002926 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002927
Greg Clayton513c26c2011-01-29 07:10:55 +00002928 default:
2929 case eStateExited:
2930 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002931 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002932 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002933
2934 m_exit_string.assign ("No valid Process");
2935 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002936}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002937
Jim Inghambb3a2832011-01-29 01:49:25 +00002938Process::NextEventAction::EventActionResult
2939Process::AttachCompletionHandler::HandleBeingInterrupted()
2940{
2941 return eEventActionSuccess;
2942}
2943
2944const char *
2945Process::AttachCompletionHandler::GetExitString ()
2946{
2947 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948}
2949
2950Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002951Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002952{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002953 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002954 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002955 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002956 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002957 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002958 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002959
Greg Clayton144f3a92011-11-15 03:53:30 +00002960 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002961 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002962 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002963 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002964 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002965
Greg Clayton144f3a92011-11-15 03:53:30 +00002966 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002967 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002968 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2969
2970 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002972 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2973 if (error.Success())
2974 {
Ed Maste64fad602013-07-29 20:58:06 +00002975 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002976 {
2977 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002978 const bool restarted = false;
2979 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002980 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00002981 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00002982 }
2983 else
2984 {
2985 // This shouldn't happen
2986 error.SetErrorString("failed to acquire process run lock");
2987 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002988
Greg Clayton144f3a92011-11-15 03:53:30 +00002989 if (error.Fail())
2990 {
2991 if (GetID() != LLDB_INVALID_PROCESS_ID)
2992 {
2993 SetID (LLDB_INVALID_PROCESS_ID);
2994 if (error.AsCString() == NULL)
2995 error.SetErrorString("attach failed");
2996
2997 SetExitStatus(-1, error.AsCString());
2998 }
2999 }
3000 else
3001 {
3002 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3003 StartPrivateStateThread();
3004 }
3005 return error;
3006 }
Greg Claytone996fd32011-03-08 22:40:15 +00003007 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003008 else
Greg Claytone996fd32011-03-08 22:40:15 +00003009 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003010 ProcessInstanceInfoList process_infos;
3011 PlatformSP platform_sp (m_target.GetPlatform ());
3012
3013 if (platform_sp)
3014 {
3015 ProcessInstanceInfoMatch match_info;
3016 match_info.GetProcessInfo() = attach_info;
3017 match_info.SetNameMatchType (eNameMatchEquals);
3018 platform_sp->FindProcesses (match_info, process_infos);
3019 const uint32_t num_matches = process_infos.GetSize();
3020 if (num_matches == 1)
3021 {
3022 attach_pid = process_infos.GetProcessIDAtIndex(0);
3023 // Fall through and attach using the above process ID
3024 }
3025 else
3026 {
3027 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3028 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003029 {
3030 StreamString s;
3031 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3032 for (size_t i = 0; i < num_matches; i++)
3033 {
3034 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3035 }
3036 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3037 process_name,
3038 s.GetData());
3039 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003040 else
3041 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3042 }
3043 }
3044 else
3045 {
3046 error.SetErrorString ("invalid platform, can't find processes by name");
3047 return error;
3048 }
Greg Claytone996fd32011-03-08 22:40:15 +00003049 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 }
3051 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003052 {
3053 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003054 }
3055 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003056
3057 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003058 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003059 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003060 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003062
Ed Maste64fad602013-07-29 20:58:06 +00003063 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003064 {
3065 // Now attach using these arguments.
3066 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003067 const bool restarted = false;
3068 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003069 error = DoAttachToProcessWithID (attach_pid, attach_info);
3070 }
3071 else
3072 {
3073 // This shouldn't happen
3074 error.SetErrorString("failed to acquire process run lock");
3075 }
3076
Greg Clayton144f3a92011-11-15 03:53:30 +00003077 if (error.Success())
3078 {
3079
3080 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3081 StartPrivateStateThread();
3082 }
3083 else
Greg Claytone996fd32011-03-08 22:40:15 +00003084 {
3085 if (GetID() != LLDB_INVALID_PROCESS_ID)
3086 {
3087 SetID (LLDB_INVALID_PROCESS_ID);
3088 const char *error_string = error.AsCString();
3089 if (error_string == NULL)
3090 error_string = "attach failed";
3091
3092 SetExitStatus(-1, error_string);
3093 }
3094 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003095 }
3096 }
3097 return error;
3098}
3099
Greg Clayton93d3c8332011-02-16 04:46:07 +00003100void
3101Process::CompleteAttach ()
3102{
3103 // Let the process subclass figure out at much as it can about the process
3104 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003105 ArchSpec process_arch;
3106 DidAttach(process_arch);
3107
3108 if (process_arch.IsValid())
3109 m_target.SetArchitecture(process_arch);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003110
Jim Ingham4299fdb2011-09-15 01:10:17 +00003111 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3112 // the same as the one we've already set, switch architectures.
3113 PlatformSP platform_sp (m_target.GetPlatform ());
3114 assert (platform_sp.get());
3115 if (platform_sp)
3116 {
Greg Clayton70512312012-05-08 01:45:38 +00003117 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003118 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003119 {
3120 ArchSpec platform_arch;
3121 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3122 if (platform_sp)
3123 {
3124 m_target.SetPlatform (platform_sp);
3125 m_target.SetArchitecture(platform_arch);
3126 }
3127 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003128 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003129 {
3130 ProcessInstanceInfo process_info;
3131 platform_sp->GetProcessInfo (GetID(), process_info);
3132 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003133 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003134 m_target.SetArchitecture (process_arch);
3135 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003136 }
3137
3138 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003139 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003140 DynamicLoader *dyld = GetDynamicLoader ();
3141 if (dyld)
3142 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003143
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003144 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003145
Jason Molendaeef51062013-11-05 03:57:19 +00003146 SystemRuntime *system_runtime = GetSystemRuntime ();
3147 if (system_runtime)
3148 system_runtime->DidAttach();
3149
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003150 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003151 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003152 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003153 Mutex::Locker modules_locker(target_modules.GetMutex());
3154 size_t num_modules = target_modules.GetSize();
3155 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003156
Andy Gibbsa297a972013-06-19 19:04:53 +00003157 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003158 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003159 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003160 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003161 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003162 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003163 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003164 break;
3165 }
3166 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003167 if (new_executable_module_sp)
3168 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003169}
3170
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003171Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003172Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003173{
Greg Claytonb766a732011-02-04 01:58:07 +00003174 m_abi_sp.reset();
3175 m_process_input_reader.reset();
3176
3177 // Find the process and its architecture. Make sure it matches the architecture
3178 // of the current Target, and if not adjust it.
3179
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003180 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003181 if (error.Success())
3182 {
Greg Clayton71337622011-02-24 22:24:29 +00003183 if (GetID() != LLDB_INVALID_PROCESS_ID)
3184 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003185 EventSP event_sp;
3186 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3187
3188 if (state == eStateStopped || state == eStateCrashed)
3189 {
3190 // If we attached and actually have a process on the other end, then
3191 // this ended up being the equivalent of an attach.
3192 CompleteAttach ();
3193
3194 // This delays passing the stopped event to listeners till
3195 // CompleteAttach gets a chance to complete...
3196 HandlePrivateEvent (event_sp);
3197
3198 }
Greg Clayton71337622011-02-24 22:24:29 +00003199 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003200
3201 if (PrivateStateThreadIsValid ())
3202 ResumePrivateStateThread ();
3203 else
3204 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003205 }
3206 return error;
3207}
3208
3209
3210Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003211Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003212{
Greg Clayton5160ce52013-03-27 23:08:40 +00003213 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003214 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003215 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003216 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003217 StateAsCString(m_public_state.GetValue()),
3218 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003219
3220 Error error (WillResume());
3221 // Tell the process it is about to resume before the thread list
3222 if (error.Success())
3223 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003224 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003225 // can let all of our threads know that they are about to be
3226 // resumed. Threads will each be called with
3227 // Thread::WillResume(StateType) where StateType contains the state
3228 // that they are supposed to have when the process is resumed
3229 // (suspended/running/stepping). Threads should also check
3230 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003231 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003232 if (m_thread_list.WillResume())
3233 {
Jim Ingham372787f2012-04-07 00:00:41 +00003234 // Last thing, do the PreResumeActions.
3235 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003236 {
Jim Ingham0161b492013-02-09 01:29:05 +00003237 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003238 }
3239 else
3240 {
3241 m_mod_id.BumpResumeID();
3242 error = DoResume();
3243 if (error.Success())
3244 {
3245 DidResume();
3246 m_thread_list.DidResume();
3247 if (log)
3248 log->Printf ("Process thinks the process has resumed.");
3249 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003250 }
3251 }
3252 else
3253 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003254 // Somebody wanted to run without running. So generate a continue & a stopped event,
3255 // and let the world handle them.
3256 if (log)
3257 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3258
3259 SetPrivateState(eStateRunning);
3260 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003261 }
3262 }
Jim Ingham444586b2011-01-24 06:34:17 +00003263 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003264 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265 return error;
3266}
3267
3268Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003269Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003271 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3272 // in case it was already set and some thread plan logic calls halt on its
3273 // own.
3274 m_clear_thread_plans_on_stop |= clear_thread_plans;
3275
Jim Inghamaacc3182012-06-06 00:29:30 +00003276 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3277 // we could just straightaway get another event. It just narrows the window...
3278 m_currently_handling_event.WaitForValueEqualTo(false);
3279
3280
Jim Inghambb3a2832011-01-29 01:49:25 +00003281 // Pause our private state thread so we can ensure no one else eats
3282 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003283 Listener halt_listener ("lldb.process.halt_listener");
3284 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003285
Jim Inghambb3a2832011-01-29 01:49:25 +00003286 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003287 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003288
Greg Clayton06357c92014-07-30 17:38:47 +00003289 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003290 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003291 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003292
Greg Clayton513c26c2011-01-29 07:10:55 +00003293 bool caused_stop = false;
3294
3295 // Ask the process subclass to actually halt our process
3296 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003297 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003298 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003299 if (m_public_state.GetValue() == eStateAttaching)
3300 {
Greg Clayton06357c92014-07-30 17:38:47 +00003301 // Don't hijack and eat the eStateExited as the code that was doing
3302 // the attach will be waiting for this event...
3303 RestorePrivateProcessEvents();
3304 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003305 SetExitStatus(SIGKILL, "Cancelled async attach.");
3306 Destroy ();
3307 }
3308 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003309 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003310 // If "caused_stop" is true, then DoHalt stopped the process. If
3311 // "caused_stop" is false, the process was already stopped.
3312 // If the DoHalt caused the process to stop, then we want to catch
3313 // this event and set the interrupted bool to true before we pass
3314 // this along so clients know that the process was interrupted by
3315 // a halt command.
3316 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003317 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003318 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003319 TimeValue timeout_time;
3320 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003321 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003322 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3323 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003324
Jim Ingham0f16e732011-02-08 05:20:59 +00003325 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003326 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003327 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003328 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003329 }
3330 else
3331 {
Greg Clayton2637f822011-11-17 01:23:07 +00003332 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003333 {
3334 // We caused the process to interrupt itself, so mark this
3335 // as such in the stop event so clients can tell an interrupted
3336 // process from a natural stop
3337 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3338 }
3339 else
3340 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003341 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003342 if (log)
3343 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3344 error.SetErrorString ("Did not get stopped event after halt.");
3345 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003346 }
3347 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003348 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003349 }
3350 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003351 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003352 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003353 if (!restored_process_events)
3354 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003355
3356 // Post any event we might have consumed. If all goes well, we will have
3357 // stopped the process, intercepted the event and set the interrupted
3358 // bool in the event. Post it to the private event queue and that will end up
3359 // correctly setting the state.
3360 if (event_sp)
3361 m_private_state_broadcaster.BroadcastEvent(event_sp);
3362
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363 return error;
3364}
3365
3366Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003367Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3368{
3369 Error error;
3370 if (m_public_state.GetValue() == eStateRunning)
3371 {
3372 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3373 if (log)
3374 log->Printf("Process::Destroy() About to halt.");
3375 error = Halt();
3376 if (error.Success())
3377 {
3378 // Consume the halt event.
3379 TimeValue timeout (TimeValue::Now());
3380 timeout.OffsetWithSeconds(1);
3381 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3382
3383 // If the process exited while we were waiting for it to stop, put the exited event into
3384 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3385 // they don't have a process anymore...
3386
3387 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3388 {
3389 if (log)
3390 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3391 return error;
3392 }
3393 else
3394 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3395
3396 if (state != eStateStopped)
3397 {
3398 if (log)
3399 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3400 // If we really couldn't stop the process then we should just error out here, but if the
3401 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3402 StateType private_state = m_private_state.GetValue();
3403 if (private_state != eStateStopped)
3404 {
3405 return error;
3406 }
3407 }
3408 }
3409 else
3410 {
3411 if (log)
3412 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3413 }
3414 }
3415 return error;
3416}
3417
3418Error
Jim Inghamacff8952013-05-02 00:27:30 +00003419Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003420{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003421 EventSP exit_event_sp;
3422 Error error;
3423 m_destroy_in_process = true;
3424
3425 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003426
3427 if (error.Success())
3428 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003429 if (DetachRequiresHalt())
3430 {
3431 error = HaltForDestroyOrDetach (exit_event_sp);
3432 if (!error.Success())
3433 {
3434 m_destroy_in_process = false;
3435 return error;
3436 }
3437 else if (exit_event_sp)
3438 {
3439 // We shouldn't need to do anything else here. There's no process left to detach from...
3440 StopPrivateStateThread();
3441 m_destroy_in_process = false;
3442 return error;
3443 }
3444 }
3445
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003446 m_thread_list.DiscardThreadPlans();
3447 DisableAllBreakpointSites();
3448
Jim Inghamacff8952013-05-02 00:27:30 +00003449 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003450 if (error.Success())
3451 {
3452 DidDetach();
3453 StopPrivateStateThread();
3454 }
Jim Inghamacff8952013-05-02 00:27:30 +00003455 else
3456 {
3457 return error;
3458 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003460 m_destroy_in_process = false;
3461
3462 // If we exited when we were waiting for a process to stop, then
3463 // forward the event here so we don't lose the event
3464 if (exit_event_sp)
3465 {
3466 // Directly broadcast our exited event because we shut down our
3467 // private state thread above
3468 BroadcastEvent(exit_event_sp);
3469 }
3470
3471 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3472 // the last events through the event system, in which case we might strand the write lock. Unlock
3473 // it here so when we do to tear down the process we don't get an error destroying the lock.
3474
Ed Maste64fad602013-07-29 20:58:06 +00003475 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003476 return error;
3477}
3478
3479Error
3480Process::Destroy ()
3481{
Jim Ingham09437922013-03-01 20:04:25 +00003482
3483 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3484 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3485 // failed and the process stays around for some reason it won't be in a confused state.
3486
3487 m_destroy_in_process = true;
3488
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003489 Error error (WillDestroy());
3490 if (error.Success())
3491 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003492 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003493 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003494 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003495 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003496 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003497
Jim Inghamaacc3182012-06-06 00:29:30 +00003498 if (m_public_state.GetValue() != eStateRunning)
3499 {
3500 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3501 // kill it, we don't want it hitting a breakpoint...
3502 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3503 // we're not going to have much luck doing this now.
3504 m_thread_list.DiscardThreadPlans();
3505 DisableAllBreakpointSites();
3506 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003507
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003508 error = DoDestroy();
3509 if (error.Success())
3510 {
3511 DidDestroy();
3512 StopPrivateStateThread();
3513 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003514 m_stdio_communication.StopReadThread();
3515 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003516
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003517 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003518 {
3519 m_process_input_reader->SetIsDone(true);
3520 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003521 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003522 }
3523
Greg Clayton85fb1b92012-09-11 02:33:37 +00003524 // If we exited when we were waiting for a process to stop, then
3525 // forward the event here so we don't lose the event
3526 if (exit_event_sp)
3527 {
3528 // Directly broadcast our exited event because we shut down our
3529 // private state thread above
3530 BroadcastEvent(exit_event_sp);
3531 }
3532
Jim Inghamb1e2e842012-04-12 18:49:31 +00003533 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3534 // the last events through the event system, in which case we might strand the write lock. Unlock
3535 // 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 +00003536 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003537 }
Jim Ingham09437922013-03-01 20:04:25 +00003538
3539 m_destroy_in_process = false;
3540
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541 return error;
3542}
3543
3544Error
3545Process::Signal (int signal)
3546{
3547 Error error (WillSignal());
3548 if (error.Success())
3549 {
3550 error = DoSignal(signal);
3551 if (error.Success())
3552 DidSignal();
3553 }
3554 return error;
3555}
3556
Greg Clayton514487e2011-02-15 21:59:32 +00003557lldb::ByteOrder
3558Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559{
Greg Clayton514487e2011-02-15 21:59:32 +00003560 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561}
3562
3563uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003564Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565{
Greg Clayton514487e2011-02-15 21:59:32 +00003566 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003567}
3568
Greg Clayton514487e2011-02-15 21:59:32 +00003569
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003570bool
3571Process::ShouldBroadcastEvent (Event *event_ptr)
3572{
3573 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3574 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003575 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003576
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577 switch (state)
3578 {
Greg Claytonb766a732011-02-04 01:58:07 +00003579 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580 case eStateAttaching:
3581 case eStateLaunching:
3582 case eStateDetached:
3583 case eStateExited:
3584 case eStateUnloaded:
3585 // These events indicate changes in the state of the debugging session, always report them.
3586 return_value = true;
3587 break;
3588 case eStateInvalid:
3589 // We stopped for no apparent reason, don't report it.
3590 return_value = false;
3591 break;
3592 case eStateRunning:
3593 case eStateStepping:
3594 // If we've started the target running, we handle the cases where we
3595 // are already running and where there is a transition from stopped to
3596 // running differently.
3597 // running -> running: Automatically suppress extra running events
3598 // stopped -> running: Report except when there is one or more no votes
3599 // and no yes votes.
3600 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003601 if (m_force_next_event_delivery)
3602 return_value = true;
3603 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003604 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003605 switch (m_last_broadcast_state)
3606 {
3607 case eStateRunning:
3608 case eStateStepping:
3609 // We always suppress multiple runnings with no PUBLIC stop in between.
3610 return_value = false;
3611 break;
3612 default:
3613 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003614 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003615 // events. If I run the lldb/test/thread/a.out file and
3616 // break at main.cpp:58, run and hit the breakpoints on
3617 // multiple threads, then somehow during the stepping over
3618 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003619
Jim Ingham1460e4b2014-01-10 23:46:59 +00003620 // This is a transition from stop to run.
3621 switch (m_thread_list.ShouldReportRun (event_ptr))
3622 {
3623 case eVoteYes:
3624 case eVoteNoOpinion:
3625 return_value = true;
3626 break;
3627 case eVoteNo:
3628 return_value = false;
3629 break;
3630 }
3631 break;
3632 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003633 }
3634 break;
3635 case eStateStopped:
3636 case eStateCrashed:
3637 case eStateSuspended:
3638 {
3639 // We've stopped. First see if we're going to restart the target.
3640 // If we are going to stop, then we always broadcast the event.
3641 // 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 +00003642 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003643
Jim Inghamcb4ca112012-05-16 01:32:14 +00003644 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003645 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003647 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003648 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003649 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003650 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003651 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3652 // so they can properly set their state.
3653 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003654 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003655 }
3656 else
3657 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003658 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3659 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003660
Jim Ingham0161b492013-02-09 01:29:05 +00003661 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3662 // Asking the thread list is also not likely to go well, since we are running again.
3663 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003664
Jim Ingham0161b492013-02-09 01:29:05 +00003665 if (!was_restarted)
3666 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003667
Jim Ingham221d51c2013-05-08 00:35:16 +00003668 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003669 {
Jim Ingham0161b492013-02-09 01:29:05 +00003670 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3671 if (log)
3672 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003673 should_resume, StateAsCString(state),
3674 was_restarted, stop_vote);
3675
Jim Ingham0161b492013-02-09 01:29:05 +00003676 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 {
3678 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003679 return_value = true;
3680 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003681 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003682 case eVoteNo:
3683 return_value = false;
3684 break;
3685 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003686
Jim Inghamcb95f342012-09-05 21:13:56 +00003687 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003688 {
3689 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003690 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3691 static_cast<void*>(event_ptr),
3692 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003693 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003694 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003695 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003696
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003697 }
3698 else
3699 {
3700 return_value = true;
3701 SynchronouslyNotifyStateChanged (state);
3702 }
3703 }
3704 }
Jim Ingham0161b492013-02-09 01:29:05 +00003705 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003706 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003707
Jim Ingham1460e4b2014-01-10 23:46:59 +00003708 // Forcing the next event delivery is a one shot deal. So reset it here.
3709 m_force_next_event_delivery = false;
3710
Jim Ingham0161b492013-02-09 01:29:05 +00003711 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3712 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3713 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3714 // because the PublicState reflects the last event pulled off the queue, and there may be several
3715 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3716 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003717
Jim Ingham0161b492013-02-09 01:29:05 +00003718 if (return_value)
3719 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003720
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003722 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003723 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003724 StateAsCString(m_last_broadcast_state),
3725 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 return return_value;
3727}
3728
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729
3730bool
Jim Ingham372787f2012-04-07 00:00:41 +00003731Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732{
Greg Clayton5160ce52013-03-27 23:08:40 +00003733 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003734
Greg Clayton8b82f082011-04-12 05:54:46 +00003735 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003737 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3738
Jim Ingham372787f2012-04-07 00:00:41 +00003739 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003740 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003741
3742 // Create a thread that watches our internal state and controls which
3743 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003744 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003745
3746 if (Host::MAX_THREAD_NAME_LENGTH <= 16)
3747 {
3748 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3749 if (already_running)
3750 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3751 else
3752 snprintf(thread_name, sizeof(thread_name), "intern-state");
3753 }
Jim Ingham372787f2012-04-07 00:00:41 +00003754 else
Todd Fiala17096d72014-07-16 19:03:16 +00003755 {
3756 if (already_running)
3757 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3758 else
3759 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3760 }
3761
Jim Ingham076b3042012-04-10 01:21:57 +00003762 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003763 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003764 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3765 if (success)
3766 {
3767 ResumePrivateStateThread();
3768 return true;
3769 }
3770 else
3771 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772}
3773
3774void
3775Process::PausePrivateStateThread ()
3776{
3777 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3778}
3779
3780void
3781Process::ResumePrivateStateThread ()
3782{
3783 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3784}
3785
3786void
3787Process::StopPrivateStateThread ()
3788{
Greg Clayton8b82f082011-04-12 05:54:46 +00003789 if (PrivateStateThreadIsValid ())
3790 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003791 else
3792 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003793 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003794 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003795 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003796 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003797}
3798
3799void
3800Process::ControlPrivateStateThread (uint32_t signal)
3801{
Greg Clayton5160ce52013-03-27 23:08:40 +00003802 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003803
3804 assert (signal == eBroadcastInternalStateControlStop ||
3805 signal == eBroadcastInternalStateControlPause ||
3806 signal == eBroadcastInternalStateControlResume);
3807
3808 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003809 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003811 // Signal the private state thread. First we should copy this is case the
3812 // thread starts exiting since the private state thread will NULL this out
3813 // when it exits
3814 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003815 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003816 {
3817 TimeValue timeout_time;
3818 bool timed_out;
3819
3820 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3821
3822 timeout_time = TimeValue::Now();
3823 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003824 if (log)
3825 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3827 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3828
3829 if (signal == eBroadcastInternalStateControlStop)
3830 {
3831 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003832 {
3833 Error error;
3834 Host::ThreadCancel (private_state_thread, &error);
3835 if (log)
3836 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3837 }
3838 else
3839 {
3840 if (log)
3841 log->Printf ("The control event killed the private state thread without having to cancel.");
3842 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843
3844 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003845 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003846 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847 }
3848 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003849 else
3850 {
3851 if (log)
3852 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3853 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003854}
3855
3856void
Jim Inghamcfc09352012-07-27 23:57:19 +00003857Process::SendAsyncInterrupt ()
3858{
3859 if (PrivateStateThreadIsValid())
3860 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3861 else
3862 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3863}
3864
3865void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866Process::HandlePrivateEvent (EventSP &event_sp)
3867{
Greg Clayton5160ce52013-03-27 23:08:40 +00003868 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003869 m_resume_requested = false;
3870
Jim Inghamaacc3182012-06-06 00:29:30 +00003871 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003872
Greg Clayton414f5d32011-01-25 02:58:48 +00003873 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003874
3875 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003876 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003877 {
Jim Ingham754ab982011-01-29 04:05:41 +00003878 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003879 if (log)
3880 log->Printf ("Ran next event action, result was %d.", action_result);
3881
Jim Inghambb3a2832011-01-29 01:49:25 +00003882 switch (action_result)
3883 {
3884 case NextEventAction::eEventActionSuccess:
3885 SetNextEventAction(NULL);
3886 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003887
Jim Inghambb3a2832011-01-29 01:49:25 +00003888 case NextEventAction::eEventActionRetry:
3889 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003890
Jim Inghambb3a2832011-01-29 01:49:25 +00003891 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003892 // Handle Exiting Here. If we already got an exited event,
3893 // we should just propagate it. Otherwise, swallow this event,
3894 // and set our state to exit so the next event will kill us.
3895 if (new_state != eStateExited)
3896 {
3897 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003898 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003899 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003900 SetNextEventAction(NULL);
3901 return;
3902 }
3903 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003904 break;
3905 }
3906 }
3907
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003908 // See if we should broadcast this state to external clients?
3909 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003910
3911 if (should_broadcast)
3912 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003913 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003914 if (log)
3915 {
Daniel Malead01b2952012-11-29 21:49:15 +00003916 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003917 __FUNCTION__,
3918 GetID(),
3919 StateAsCString(new_state),
3920 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003921 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003922 }
Jim Ingham9575d842011-03-11 03:53:59 +00003923 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003924 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003925 {
3926 // Only push the input handler if we aren't fowarding events,
3927 // as this means the curses GUI is in use...
3928 if (!GetTarget().GetDebugger().IsForwardingEvents())
3929 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00003930 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00003931 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003932 else if (StateIsStoppedState(new_state, false))
3933 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00003934 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00003935 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3936 {
3937 // If the lldb_private::Debugger is handling the events, we don't
3938 // want to pop the process IOHandler here, we want to do it when
3939 // we receive the stopped event so we can carefully control when
3940 // the process IOHandler is popped because when we stop we want to
3941 // display some text stating how and why we stopped, then maybe some
3942 // process/thread/frame info, and then we want the "(lldb) " prompt
3943 // to show up. If we pop the process IOHandler here, then we will
3944 // cause the command interpreter to become the top IOHandler after
3945 // the process pops off and it will update its prompt right away...
3946 // See the Debugger.cpp file where it calls the function as
3947 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3948 // Otherwise we end up getting overlapping "(lldb) " prompts and
3949 // garbled output.
3950 //
3951 // If we aren't handling the events in the debugger (which is indicated
3952 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3953 // are hijacked, then we always pop the process IO handler manually.
3954 // Hijacking happens when the internal process state thread is running
3955 // thread plans, or when commands want to run in synchronous mode
3956 // and they call "process->WaitForProcessToStop()". An example of something
3957 // that will hijack the events is a simple expression:
3958 //
3959 // (lldb) expr (int)puts("hello")
3960 //
3961 // This will cause the internal process state thread to resume and halt
3962 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3963 // events) and we do need the IO handler to be pushed and popped
3964 // correctly.
3965
3966 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
3967 PopProcessIOHandler ();
3968 }
3969 }
Jim Ingham9575d842011-03-11 03:53:59 +00003970
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971 BroadcastEvent (event_sp);
3972 }
3973 else
3974 {
3975 if (log)
3976 {
Daniel Malead01b2952012-11-29 21:49:15 +00003977 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003978 __FUNCTION__,
3979 GetID(),
3980 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003981 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982 }
3983 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003984 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003985}
3986
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003987thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988Process::PrivateStateThread (void *arg)
3989{
3990 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003991 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003992 return result;
3993}
3994
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003995thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003996Process::RunPrivateStateThread ()
3997{
Jim Ingham076b3042012-04-10 01:21:57 +00003998 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003999 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004000
Greg Clayton5160ce52013-03-27 23:08:40 +00004001 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004002 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004003 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4004 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004005
4006 bool exit_now = false;
4007 while (!exit_now)
4008 {
4009 EventSP event_sp;
4010 WaitForEventsPrivate (NULL, event_sp, control_only);
4011 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4012 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004013 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004014 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4015 __FUNCTION__, static_cast<void*>(this), GetID(),
4016 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004017
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004018 switch (event_sp->GetType())
4019 {
4020 case eBroadcastInternalStateControlStop:
4021 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004022 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004023
4024 case eBroadcastInternalStateControlPause:
4025 control_only = true;
4026 break;
4027
4028 case eBroadcastInternalStateControlResume:
4029 control_only = false;
4030 break;
4031 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004032
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004033 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004034 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004035 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004036 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4037 {
4038 if (m_public_state.GetValue() == eStateAttaching)
4039 {
4040 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004041 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4042 __FUNCTION__, static_cast<void*>(this),
4043 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004044 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4045 }
4046 else
4047 {
4048 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004049 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4050 __FUNCTION__, static_cast<void*>(this),
4051 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004052 Halt();
4053 }
4054 continue;
4055 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004056
4057 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4058
4059 if (internal_state != eStateInvalid)
4060 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004061 if (m_clear_thread_plans_on_stop &&
4062 StateIsStoppedState(internal_state, true))
4063 {
4064 m_clear_thread_plans_on_stop = false;
4065 m_thread_list.DiscardThreadPlans();
4066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004067 HandlePrivateEvent (event_sp);
4068 }
4069
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004070 if (internal_state == eStateInvalid ||
4071 internal_state == eStateExited ||
4072 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004073 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004074 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004075 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4076 __FUNCTION__, static_cast<void*>(this), GetID(),
4077 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004078
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004079 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004080 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004081 }
4082
Caroline Tice20ad3c42010-10-29 21:48:37 +00004083 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004084 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004085 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4086 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004087
Ed Maste64fad602013-07-29 20:58:06 +00004088 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004089 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4090 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091 return NULL;
4092}
4093
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094//------------------------------------------------------------------
4095// Process Event Data
4096//------------------------------------------------------------------
4097
4098Process::ProcessEventData::ProcessEventData () :
4099 EventData (),
4100 m_process_sp (),
4101 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004102 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004103 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004104 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004105{
4106}
4107
4108Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4109 EventData (),
4110 m_process_sp (process_sp),
4111 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004112 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004113 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004114 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115{
4116}
4117
4118Process::ProcessEventData::~ProcessEventData()
4119{
4120}
4121
4122const ConstString &
4123Process::ProcessEventData::GetFlavorString ()
4124{
4125 static ConstString g_flavor ("Process::ProcessEventData");
4126 return g_flavor;
4127}
4128
4129const ConstString &
4130Process::ProcessEventData::GetFlavor () const
4131{
4132 return ProcessEventData::GetFlavorString ();
4133}
4134
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004135void
4136Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4137{
4138 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004139 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4140 // the public event queue, then other times when we're pretending that this is where we stopped at the
4141 // end of expression evaluation. m_update_state is used to distinguish these
4142 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004143 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004144 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004146
Jim Ingham221d51c2013-05-08 00:35:16 +00004147 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004148
4149 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4150 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4151 // end up restarting the process.
4152 if (m_interrupted)
4153 return;
4154
4155 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004157 {
4158 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004159 uint32_t num_threads = curr_thread_list.GetSize();
4160 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004161
Jim Ingham4b536182011-08-09 02:12:22 +00004162 // The actions might change one of the thread's stop_info's opinions about whether we should
4163 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004164
4165 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4166 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4167 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4168 // 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
4169 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004170 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004171 for (idx = 0; idx < num_threads; ++idx)
4172 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4173
Jim Inghamc7078c22012-12-13 22:24:15 +00004174 // Use this to track whether we should continue from here. We will only continue the target running if
4175 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4176 // then it doesn't matter what the other threads say...
4177
4178 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004179
Jim Ingham0ad7e052013-04-25 02:04:59 +00004180 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4181 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4182 // thing to do is, and it's better to let the user decide than continue behind their backs.
4183
4184 bool does_anybody_have_an_opinion = false;
4185
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004186 for (idx = 0; idx < num_threads; ++idx)
4187 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004188 curr_thread_list = m_process_sp->GetThreadList();
4189 if (curr_thread_list.GetSize() != num_threads)
4190 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004191 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004192 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004193 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 +00004194 break;
4195 }
4196
4197 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4198
4199 if (thread_sp->GetIndexID() != thread_index_array[idx])
4200 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004201 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004202 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004203 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004204 idx,
4205 thread_index_array[idx],
4206 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004207 break;
4208 }
4209
Jim Inghamb15bfc72010-10-20 00:39:53 +00004210 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004211 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004212 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004213 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004214 bool this_thread_wants_to_stop;
4215 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004216 {
Jim Ingham0161b492013-02-09 01:29:05 +00004217 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4218 }
4219 else
4220 {
4221 stop_info_sp->PerformAction(event_ptr);
4222 // The stop action might restart the target. If it does, then we want to mark that in the
4223 // event so that whoever is receiving it will know to wait for the running event and reflect
4224 // that state appropriately.
4225 // We also need to stop processing actions, since they aren't expecting the target to be running.
4226
4227 // FIXME: we might have run.
4228 if (stop_info_sp->HasTargetRunSinceMe())
4229 {
4230 SetRestarted (true);
4231 break;
4232 }
4233
4234 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004235 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004236
Jim Inghamc7078c22012-12-13 22:24:15 +00004237 if (still_should_stop == false)
4238 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239 }
4240 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004241
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004242
Jim Inghama8ca6e22013-05-03 23:04:37 +00004243 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004244 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004245 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004246 {
4247 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004248 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004249 // Use the public resume method here, since this is just
4250 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004251 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004252 }
4253 else
4254 {
4255 // If we didn't restart, run the Stop Hooks here:
4256 // They might also restart the target, so watch for that.
4257 m_process_sp->GetTarget().RunStopHooks();
4258 if (m_process_sp->GetPrivateState() == eStateRunning)
4259 SetRestarted(true);
4260 }
Jim Ingham9575d842011-03-11 03:53:59 +00004261 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004262 }
4263}
4264
4265void
4266Process::ProcessEventData::Dump (Stream *s) const
4267{
4268 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004269 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4270 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004271
Greg Clayton8b82f082011-04-12 05:54:46 +00004272 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004273}
4274
4275const Process::ProcessEventData *
4276Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4277{
4278 if (event_ptr)
4279 {
4280 const EventData *event_data = event_ptr->GetData();
4281 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4282 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4283 }
4284 return NULL;
4285}
4286
4287ProcessSP
4288Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4289{
4290 ProcessSP process_sp;
4291 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4292 if (data)
4293 process_sp = data->GetProcessSP();
4294 return process_sp;
4295}
4296
4297StateType
4298Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4299{
4300 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4301 if (data == NULL)
4302 return eStateInvalid;
4303 else
4304 return data->GetState();
4305}
4306
4307bool
4308Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4309{
4310 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4311 if (data == NULL)
4312 return false;
4313 else
4314 return data->GetRestarted();
4315}
4316
4317void
4318Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4319{
4320 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4321 if (data != NULL)
4322 data->SetRestarted(new_value);
4323}
4324
Jim Ingham0161b492013-02-09 01:29:05 +00004325size_t
4326Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4327{
4328 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4329 if (data != NULL)
4330 return data->GetNumRestartedReasons();
4331 else
4332 return 0;
4333}
4334
4335const char *
4336Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4337{
4338 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4339 if (data != NULL)
4340 return data->GetRestartedReasonAtIndex(idx);
4341 else
4342 return NULL;
4343}
4344
4345void
4346Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4347{
4348 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4349 if (data != NULL)
4350 data->AddRestartedReason(reason);
4351}
4352
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004354Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4355{
4356 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4357 if (data == NULL)
4358 return false;
4359 else
4360 return data->GetInterrupted ();
4361}
4362
4363void
4364Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4365{
4366 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4367 if (data != NULL)
4368 data->SetInterrupted(new_value);
4369}
4370
4371bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004372Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4373{
4374 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4375 if (data)
4376 {
4377 data->SetUpdateStateOnRemoval();
4378 return true;
4379 }
4380 return false;
4381}
4382
Greg Claytond9e416c2012-02-18 05:35:26 +00004383lldb::TargetSP
4384Process::CalculateTarget ()
4385{
4386 return m_target.shared_from_this();
4387}
4388
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004389void
Greg Clayton0603aa92010-10-04 01:05:56 +00004390Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391{
Greg Claytonc14ee322011-09-22 04:58:26 +00004392 exe_ctx.SetTargetPtr (&m_target);
4393 exe_ctx.SetProcessPtr (this);
4394 exe_ctx.SetThreadPtr(NULL);
4395 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004396}
4397
Greg Claytone996fd32011-03-08 22:40:15 +00004398//uint32_t
4399//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4400//{
4401// return 0;
4402//}
4403//
4404//ArchSpec
4405//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4406//{
4407// return Host::GetArchSpecForExistingProcess (pid);
4408//}
4409//
4410//ArchSpec
4411//Process::GetArchSpecForExistingProcess (const char *process_name)
4412//{
4413// return Host::GetArchSpecForExistingProcess (process_name);
4414//}
4415//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004416void
4417Process::AppendSTDOUT (const char * s, size_t len)
4418{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004419 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004420 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004421 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004422}
4423
4424void
Greg Clayton93e86192011-11-13 04:45:22 +00004425Process::AppendSTDERR (const char * s, size_t len)
4426{
4427 Mutex::Locker locker (m_stdio_communication_mutex);
4428 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004429 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004430}
4431
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004432void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004433Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004434{
4435 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004436 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004437 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4438}
4439
4440size_t
4441Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4442{
4443 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004444 if (m_profile_data.empty())
4445 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004446
4447 std::string &one_profile_data = m_profile_data.front();
4448 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004449 if (bytes_available > 0)
4450 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004451 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004452 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004453 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4454 static_cast<void*>(buf),
4455 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004456 if (bytes_available > buf_size)
4457 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004458 memcpy(buf, one_profile_data.c_str(), buf_size);
4459 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004460 bytes_available = buf_size;
4461 }
4462 else
4463 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004464 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004465 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004466 }
4467 }
4468 return bytes_available;
4469}
4470
4471
Greg Clayton93e86192011-11-13 04:45:22 +00004472//------------------------------------------------------------------
4473// Process STDIO
4474//------------------------------------------------------------------
4475
4476size_t
4477Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4478{
4479 Mutex::Locker locker(m_stdio_communication_mutex);
4480 size_t bytes_available = m_stdout_data.size();
4481 if (bytes_available > 0)
4482 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004483 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004484 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004485 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4486 static_cast<void*>(buf),
4487 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004488 if (bytes_available > buf_size)
4489 {
4490 memcpy(buf, m_stdout_data.c_str(), buf_size);
4491 m_stdout_data.erase(0, buf_size);
4492 bytes_available = buf_size;
4493 }
4494 else
4495 {
4496 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4497 m_stdout_data.clear();
4498 }
4499 }
4500 return bytes_available;
4501}
4502
4503
4504size_t
4505Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4506{
4507 Mutex::Locker locker(m_stdio_communication_mutex);
4508 size_t bytes_available = m_stderr_data.size();
4509 if (bytes_available > 0)
4510 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004511 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004512 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004513 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4514 static_cast<void*>(buf),
4515 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004516 if (bytes_available > buf_size)
4517 {
4518 memcpy(buf, m_stderr_data.c_str(), buf_size);
4519 m_stderr_data.erase(0, buf_size);
4520 bytes_available = buf_size;
4521 }
4522 else
4523 {
4524 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4525 m_stderr_data.clear();
4526 }
4527 }
4528 return bytes_available;
4529}
4530
4531void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004532Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4533{
4534 Process *process = (Process *) baton;
4535 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4536}
4537
Greg Clayton44d93782014-01-27 23:43:24 +00004538class IOHandlerProcessSTDIO :
4539 public IOHandler
4540{
4541public:
4542 IOHandlerProcessSTDIO (Process *process,
4543 int write_fd) :
4544 IOHandler(process->GetTarget().GetDebugger()),
4545 m_process (process),
4546 m_read_file (),
4547 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004548 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004549 {
4550 m_read_file.SetDescriptor(GetInputFD(), false);
4551 }
4552
4553 virtual
4554 ~IOHandlerProcessSTDIO ()
4555 {
4556
4557 }
4558
4559 bool
4560 OpenPipes ()
4561 {
Greg Clayton100eb932014-07-02 21:10:39 +00004562 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004563 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004564 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004565 }
4566
4567 void
4568 ClosePipes()
4569 {
Greg Clayton100eb932014-07-02 21:10:39 +00004570 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004571 }
4572
4573 // Each IOHandler gets to run until it is done. It should read data
4574 // from the "in" and place output into "out" and "err and return
4575 // when done.
4576 virtual void
4577 Run ()
4578 {
4579 if (m_read_file.IsValid() && m_write_file.IsValid())
4580 {
4581 SetIsDone(false);
4582 if (OpenPipes())
4583 {
4584 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004585 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004586 TerminalState terminal_state;
4587 terminal_state.Save (read_fd, false);
4588 Terminal terminal(read_fd);
4589 terminal.SetCanonical(false);
4590 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004591// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004592#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004593 while (!GetIsDone())
4594 {
4595 fd_set read_fdset;
4596 FD_ZERO (&read_fdset);
4597 FD_SET (read_fd, &read_fdset);
4598 FD_SET (pipe_read_fd, &read_fdset);
4599 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4600 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4601 if (num_set_fds < 0)
4602 {
4603 const int select_errno = errno;
4604
4605 if (select_errno != EINTR)
4606 SetIsDone(true);
4607 }
4608 else if (num_set_fds > 0)
4609 {
4610 char ch = 0;
4611 size_t n;
4612 if (FD_ISSET (read_fd, &read_fdset))
4613 {
4614 n = 1;
4615 if (m_read_file.Read(&ch, n).Success() && n == 1)
4616 {
4617 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4618 SetIsDone(true);
4619 }
4620 else
4621 SetIsDone(true);
4622 }
4623 if (FD_ISSET (pipe_read_fd, &read_fdset))
4624 {
4625 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004626 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004627 {
Greg Clayton100eb932014-07-02 21:10:39 +00004628 switch (ch)
4629 {
4630 case 'q':
4631 SetIsDone(true);
4632 break;
4633 case 'i':
4634 if (StateIsRunningState(m_process->GetState()))
4635 m_process->Halt();
4636 break;
4637 }
Greg Clayton19e11352014-02-26 22:47:33 +00004638 }
Greg Clayton44d93782014-01-27 23:43:24 +00004639 }
4640 }
4641 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004642#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004643 terminal_state.Restore();
4644
4645 }
4646 else
4647 SetIsDone(true);
4648 }
4649 else
4650 SetIsDone(true);
4651 }
4652
4653 // Hide any characters that have been displayed so far so async
4654 // output can be displayed. Refresh() will be called after the
4655 // output has been displayed.
4656 virtual void
4657 Hide ()
4658 {
4659
4660 }
4661 // Called when the async output has been received in order to update
4662 // the input reader (refresh the prompt and redisplay any current
4663 // line(s) that are being edited
4664 virtual void
4665 Refresh ()
4666 {
4667
4668 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004669
Greg Clayton44d93782014-01-27 23:43:24 +00004670 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004671 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004672 {
Greg Clayton19e11352014-02-26 22:47:33 +00004673 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004674 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004675 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004676
Greg Claytonf0066ad2014-05-02 00:45:31 +00004677 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004678 Interrupt ()
4679 {
Greg Clayton19e11352014-02-26 22:47:33 +00004680 // Do only things that are safe to do in an interrupt context (like in
4681 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4682 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4683 // that was written to the pipe and then call m_process->Halt() from a
4684 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004685 if (m_active)
4686 {
4687 char ch = 'i'; // Send 'i' for interrupt
4688 return m_pipe.Write (&ch, 1) == 1;
4689 }
4690 else
4691 {
4692 // This IOHandler might be pushed on the stack, but not being run currently
4693 // so do the right thing if we aren't actively watching for STDIN by sending
4694 // the interrupt to the process. Otherwise the write to the pipe above would
4695 // do nothing. This can happen when the command interpreter is running and
4696 // gets a "expression ...". It will be on the IOHandler thread and sending
4697 // the input is complete to the delegate which will cause the expression to
4698 // run, which will push the process IO handler, but not run it.
4699
4700 if (StateIsRunningState(m_process->GetState()))
4701 {
4702 m_process->SendAsyncInterrupt();
4703 return true;
4704 }
4705 }
4706 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004707 }
Greg Clayton44d93782014-01-27 23:43:24 +00004708
4709 virtual void
4710 GotEOF()
4711 {
4712
4713 }
4714
4715protected:
4716 Process *m_process;
4717 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4718 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004719 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004720};
4721
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004722void
Greg Clayton44d93782014-01-27 23:43:24 +00004723Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004724{
4725 // First set up the Read Thread for reading/handling process I/O
4726
Greg Clayton44d93782014-01-27 23:43:24 +00004727 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004728
4729 if (conn_ap.get())
4730 {
4731 m_stdio_communication.SetConnection (conn_ap.release());
4732 if (m_stdio_communication.IsConnected())
4733 {
4734 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4735 m_stdio_communication.StartReadThread();
4736
4737 // Now read thread is set up, set up input reader.
4738
4739 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004740 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004741 }
4742 }
4743}
4744
Greg Claytonb4874f12014-02-28 18:22:24 +00004745bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004746Process::ProcessIOHandlerIsActive ()
4747{
4748 IOHandlerSP io_handler_sp (m_process_input_reader);
4749 if (io_handler_sp)
4750 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4751 return false;
4752}
4753bool
Greg Clayton44d93782014-01-27 23:43:24 +00004754Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004755{
Greg Clayton44d93782014-01-27 23:43:24 +00004756 IOHandlerSP io_handler_sp (m_process_input_reader);
4757 if (io_handler_sp)
4758 {
4759 io_handler_sp->SetIsDone(false);
4760 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004761 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004762 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004763 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004764}
4765
Greg Claytonb4874f12014-02-28 18:22:24 +00004766bool
Greg Clayton44d93782014-01-27 23:43:24 +00004767Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004768{
Greg Clayton44d93782014-01-27 23:43:24 +00004769 IOHandlerSP io_handler_sp (m_process_input_reader);
4770 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004771 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4772 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004773}
4774
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004775// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004776void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004777Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004778{
Greg Clayton6920b522012-08-22 18:39:03 +00004779 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004780}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004781
Greg Clayton99d0faf2010-11-18 23:32:35 +00004782void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004783Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004784{
Greg Clayton6920b522012-08-22 18:39:03 +00004785 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004786}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004787
Jim Ingham1624a2d2014-05-05 02:26:40 +00004788ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004789Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004790 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004791 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004792 Stream &errors)
4793{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004794 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004795
Jim Ingham77787032011-01-20 02:03:18 +00004796 if (thread_plan_sp.get() == NULL)
4797 {
4798 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004799 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004800 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004801
Jim Ingham7d7931d2013-03-28 00:05:34 +00004802 if (!thread_plan_sp->ValidatePlan(NULL))
4803 {
4804 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004805 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004806 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004807
Greg Claytonc14ee322011-09-22 04:58:26 +00004808 if (exe_ctx.GetProcessPtr() != this)
4809 {
4810 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004811 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004812 }
4813
4814 Thread *thread = exe_ctx.GetThreadPtr();
4815 if (thread == NULL)
4816 {
4817 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004818 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004819 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004820
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004821 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4822 // For that to be true the plan can't be private - since private plans suppress themselves in the
4823 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004824
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004825 bool orig_plan_private = thread_plan_sp->GetPrivate();
4826 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004827
Jim Ingham444586b2011-01-24 06:34:17 +00004828 if (m_private_state.GetValue() != eStateStopped)
4829 {
4830 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004831 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004832 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004833
Jim Ingham66243842011-08-13 00:56:10 +00004834 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004835 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004836 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004837 if (!selected_frame_sp)
4838 {
4839 thread->SetSelectedFrame(0);
4840 selected_frame_sp = thread->GetSelectedFrame();
4841 if (!selected_frame_sp)
4842 {
4843 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004844 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004845 }
4846 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004847
Jim Ingham11b0e052013-02-19 23:22:45 +00004848 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004849
4850 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4851 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004852
Greg Claytonc14ee322011-09-22 04:58:26 +00004853 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004854
Jim Ingham66243842011-08-13 00:56:10 +00004855 uint32_t selected_tid;
4856 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004857 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004858 {
4859 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004860 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004861 }
4862 else
4863 {
4864 selected_tid = LLDB_INVALID_THREAD_ID;
4865 }
4866
Jim Ingham372787f2012-04-07 00:00:41 +00004867 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004868 lldb::StateType old_state;
4869 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004870
Greg Clayton5160ce52013-03-27 23:08:40 +00004871 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004872 if (Host::GetCurrentThread() == m_private_state_thread)
4873 {
Jim Ingham076b3042012-04-10 01:21:57 +00004874 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4875 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004876 // 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 +00004877 // we are fielding public events here.
4878 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004879 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 +00004880
Jim Ingham372787f2012-04-07 00:00:41 +00004881 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004882
4883 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4884 // returning control here.
4885 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4886 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4887 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4888 // do just what we want.
4889 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4890 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4891 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4892 old_state = m_public_state.GetValue();
4893 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004894
Jim Ingham076b3042012-04-10 01:21:57 +00004895 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004896 StartPrivateStateThread(true);
4897 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004898
Jim Ingham372787f2012-04-07 00:00:41 +00004899 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004900
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004901 if (options.GetDebug())
4902 {
4903 // In this case, we aren't actually going to run, we just want to stop right away.
4904 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4905 // FIXME: To make this prettier we should invent some stop reason for this, but that
4906 // is only cosmetic, and this functionality is only of use to lldb developers who can
4907 // live with not pretty...
4908 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004909 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004910 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004911
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004912 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004913
Sean Callanana46ec452012-07-11 21:31:24 +00004914 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004915
Jim Ingham77787032011-01-20 02:03:18 +00004916 {
Sean Callanana46ec452012-07-11 21:31:24 +00004917 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4918 // restored on exit to the function.
4919 //
4920 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4921 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004922
Sean Callanana46ec452012-07-11 21:31:24 +00004923 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004924
Jim Inghamf48169b2010-11-30 02:22:11 +00004925 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004926 {
4927 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004928 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004929 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004930 thread->GetIndexID(),
4931 thread->GetID(),
4932 s.GetData());
4933 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004934
Sean Callanana46ec452012-07-11 21:31:24 +00004935 bool got_event;
4936 lldb::EventSP event_sp;
4937 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004938
Sean Callanana46ec452012-07-11 21:31:24 +00004939 TimeValue* timeout_ptr = NULL;
4940 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004941
Jim Ingham0161b492013-02-09 01:29:05 +00004942 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 +00004943 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004944 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004945 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004946
Jim Ingham0161b492013-02-09 01:29:05 +00004947 // This is just for accounting:
4948 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004949
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004950 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00004951 uint32_t one_thread_timeout_usec;
4952 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00004953
4954 // If we are going to run all threads the whole time, or if we are only going to run one thread,
4955 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
4956 // first timeout already.
4957
4958 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00004959 {
4960 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00004961 one_thread_timeout_usec = 0;
4962 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00004963 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004964 else
Jim Ingham0161b492013-02-09 01:29:05 +00004965 {
Jim Inghamfd95f892014-04-22 01:41:52 +00004966 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004967
Jim Ingham914f4e72014-03-28 21:58:28 +00004968 // If the overall wait is forever, then we only need to set the one thread timeout:
4969 if (timeout_usec == 0)
4970 {
Ed Maste801335c2014-03-31 19:28:14 +00004971 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00004972 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00004973 else
Jim Inghamfd95f892014-04-22 01:41:52 +00004974 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00004975 }
Jim Ingham0161b492013-02-09 01:29:05 +00004976 else
4977 {
Jim Ingham914f4e72014-03-28 21:58:28 +00004978 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
4979 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
4980 uint64_t computed_one_thread_timeout;
4981 if (option_one_thread_timeout != 0)
4982 {
4983 if (timeout_usec < option_one_thread_timeout)
4984 {
4985 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004986 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00004987 }
4988 computed_one_thread_timeout = option_one_thread_timeout;
4989 }
4990 else
4991 {
4992 computed_one_thread_timeout = timeout_usec / 2;
4993 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
4994 computed_one_thread_timeout = default_one_thread_timeout_usec;
4995 }
Jim Inghamfd95f892014-04-22 01:41:52 +00004996 one_thread_timeout_usec = computed_one_thread_timeout;
4997 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
4998
Jim Ingham0161b492013-02-09 01:29:05 +00004999 }
Jim Ingham0161b492013-02-09 01:29:05 +00005000 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005001
5002 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005003 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 +00005004 options.GetStopOthers(),
5005 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005006 before_first_timeout,
5007 one_thread_timeout_usec,
5008 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005009
Jim Ingham1460e4b2014-01-10 23:46:59 +00005010 // This isn't going to work if there are unfetched events on the queue.
5011 // Are there cases where we might want to run the remaining events here, and then try to
5012 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005013
Jim Ingham1460e4b2014-01-10 23:46:59 +00005014 Event *other_events = listener.PeekAtNextEvent();
5015 if (other_events != NULL)
5016 {
5017 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005018 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005019 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005020
Jim Ingham1460e4b2014-01-10 23:46:59 +00005021 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5022 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5023 // event coalescing to cause us to lose OUR running event...
5024 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005025
Jim Ingham8559a352012-11-26 23:52:18 +00005026 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5027 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005028
5029#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5030 // It's pretty much impossible to write test cases for things like:
5031 // One thread timeout expires, I go to halt, but the process already stopped
5032 // on the function call stop breakpoint. Turning on this define will make us not
5033 // fetch the first event till after the halt. So if you run a quick function, it will have
5034 // completed, and the completion event will be waiting, when you interrupt for halt.
5035 // The expression evaluation should still succeed.
5036 bool miss_first_event = true;
5037#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005038 TimeValue one_thread_timeout;
5039 TimeValue final_timeout;
5040
Jim Ingham35878c42014-04-08 21:33:21 +00005041
Sean Callanana46ec452012-07-11 21:31:24 +00005042 while (1)
5043 {
5044 // We usually want to resume the process if we get to the top of the loop.
5045 // The only exception is if we get two running events with no intervening
5046 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005047 if (log)
5048 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5049 do_resume,
5050 handle_running_event,
5051 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005052
Jim Ingham184e9812013-01-15 02:47:48 +00005053 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005054 {
5055 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005056
Jim Ingham184e9812013-01-15 02:47:48 +00005057 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005058 {
Jim Ingham0161b492013-02-09 01:29:05 +00005059 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005060 Error resume_error = PrivateResume ();
5061 if (!resume_error.Success())
5062 {
Jim Ingham0161b492013-02-09 01:29:05 +00005063 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5064 num_resumes,
5065 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005066 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005067 break;
5068 }
Sean Callanana46ec452012-07-11 21:31:24 +00005069 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005070
Jim Ingham0161b492013-02-09 01:29:05 +00005071 TimeValue resume_timeout = TimeValue::Now();
5072 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005073
Jim Ingham0161b492013-02-09 01:29:05 +00005074 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005075 if (!got_event)
5076 {
5077 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005078 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5079 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005080
Jim Ingham0161b492013-02-09 01:29:05 +00005081 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005082 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005083 break;
5084 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005085
Sean Callanana46ec452012-07-11 21:31:24 +00005086 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005087
Sean Callanana46ec452012-07-11 21:31:24 +00005088 if (stop_state != eStateRunning)
5089 {
Jim Ingham0161b492013-02-09 01:29:05 +00005090 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005091
Jim Ingham0161b492013-02-09 01:29:05 +00005092 if (stop_state == eStateStopped)
5093 {
5094 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5095 if (log)
5096 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5097 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5098 num_resumes,
5099 StateAsCString(stop_state),
5100 restarted,
5101 do_resume,
5102 handle_running_event);
5103 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005104
Jim Ingham0161b492013-02-09 01:29:05 +00005105 if (restarted)
5106 {
5107 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5108 // event here. But if I do, the best thing is to Halt and then get out of here.
5109 Halt();
5110 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005111
Jim Ingham35e1bda2012-10-16 21:41:58 +00005112 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5113 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005114 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005115 break;
5116 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005117
Sean Callanana46ec452012-07-11 21:31:24 +00005118 if (log)
5119 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5120 // We need to call the function synchronously, so spin waiting for it to return.
5121 // If we get interrupted while executing, we're going to lose our context, and
5122 // won't be able to gather the result at this point.
5123 // We set the timeout AFTER the resume, since the resume takes some time and we
5124 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005125 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005126 else
5127 {
Sean Callanana46ec452012-07-11 21:31:24 +00005128 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005129 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005130 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005131
Jim Ingham0161b492013-02-09 01:29:05 +00005132 if (before_first_timeout)
5133 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005134 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005135 {
5136 one_thread_timeout = TimeValue::Now();
5137 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005138 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005139 }
Jim Ingham0161b492013-02-09 01:29:05 +00005140 else
5141 {
5142 if (timeout_usec == 0)
5143 timeout_ptr = NULL;
5144 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005145 {
5146 final_timeout = TimeValue::Now();
5147 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005148 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005149 }
Jim Ingham0161b492013-02-09 01:29:05 +00005150 }
5151 }
5152 else
5153 {
5154 if (timeout_usec == 0)
5155 timeout_ptr = NULL;
5156 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005157 {
5158 final_timeout = TimeValue::Now();
5159 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005160 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005161 }
Jim Ingham0161b492013-02-09 01:29:05 +00005162 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005163
Jim Ingham0161b492013-02-09 01:29:05 +00005164 do_resume = true;
5165 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005166
Sean Callanana46ec452012-07-11 21:31:24 +00005167 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005168 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005169
Jim Ingham0f16e732011-02-08 05:20:59 +00005170 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005171 {
Sean Callanana46ec452012-07-11 21:31:24 +00005172 if (timeout_ptr)
5173 {
Matt Kopec676a4872013-02-21 23:55:31 +00005174 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005175 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5176 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005177 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005178 else
Sean Callanana46ec452012-07-11 21:31:24 +00005179 {
5180 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5181 }
5182 }
Jim Ingham35878c42014-04-08 21:33:21 +00005183
5184#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5185 // See comment above...
5186 if (miss_first_event)
5187 {
5188 usleep(1000);
5189 miss_first_event = false;
5190 got_event = false;
5191 }
5192 else
5193#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005194 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005195
Sean Callanana46ec452012-07-11 21:31:24 +00005196 if (got_event)
5197 {
5198 if (event_sp.get())
5199 {
5200 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005201 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005202 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005203 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005204 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005205 errors.Printf ("Execution halted by user interrupt.");
5206 if (log)
5207 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005208 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005209 }
5210 else
5211 {
5212 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5213 if (log)
5214 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005215
Jim Inghamcfc09352012-07-27 23:57:19 +00005216 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005217 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005218 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005219 {
Jim Ingham0161b492013-02-09 01:29:05 +00005220 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005221 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5222 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005223 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005224 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005225 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005226 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005227 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005228 }
5229 else
5230 {
Jim Ingham0161b492013-02-09 01:29:05 +00005231 // If we were restarted, we just need to go back up to fetch another event.
5232 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005233 {
5234 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005235 {
5236 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5237 }
5238 keep_going = true;
5239 do_resume = false;
5240 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005241
Jim Inghamcfc09352012-07-27 23:57:19 +00005242 }
5243 else
5244 {
Jim Ingham0161b492013-02-09 01:29:05 +00005245 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5246 StopReason stop_reason = eStopReasonInvalid;
5247 if (stop_info_sp)
5248 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005249
Jim Ingham0161b492013-02-09 01:29:05 +00005250 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5251 // it is OUR plan that is complete?
5252 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005253 {
5254 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005255 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5256 // Now mark this plan as private so it doesn't get reported as the stop reason
5257 // after this point.
5258 if (thread_plan_sp)
5259 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005260 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005261 }
5262 else
5263 {
Jim Ingham0161b492013-02-09 01:29:05 +00005264 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005265 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005266 {
5267 if (log)
5268 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005269 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005270 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005271 {
5272 event_to_broadcast_sp = event_sp;
5273 }
Jim Ingham0161b492013-02-09 01:29:05 +00005274 }
Jim Ingham184e9812013-01-15 02:47:48 +00005275 else
Jim Ingham0161b492013-02-09 01:29:05 +00005276 {
5277 if (log)
5278 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005279 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005280 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005281 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005282 }
Jim Ingham184e9812013-01-15 02:47:48 +00005283 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005284 }
Sean Callanana46ec452012-07-11 21:31:24 +00005285 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005286 }
5287 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005288
Jim Inghamcfc09352012-07-27 23:57:19 +00005289 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005290 // This shouldn't really happen, but sometimes we do get two running events without an
5291 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005292 do_resume = false;
5293 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005294 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005295 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005296
Jim Inghamcfc09352012-07-27 23:57:19 +00005297 default:
5298 if (log)
5299 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005300
Jim Inghamcfc09352012-07-27 23:57:19 +00005301 if (stop_state == eStateExited)
5302 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005303
Sean Callananbf154da2012-08-08 17:35:10 +00005304 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005305 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005306 break;
5307 }
Sean Callanana46ec452012-07-11 21:31:24 +00005308 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005309
Sean Callanana46ec452012-07-11 21:31:24 +00005310 if (keep_going)
5311 continue;
5312 else
5313 break;
5314 }
5315 else
5316 {
5317 if (log)
5318 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005319 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005320 break;
5321 }
5322 }
5323 else
5324 {
5325 // If we didn't get an event that means we've timed out...
5326 // We will interrupt the process here. Depending on what we were asked to do we will
5327 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005328
Sean Callanana46ec452012-07-11 21:31:24 +00005329 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005330 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005331 {
Jim Ingham0161b492013-02-09 01:29:05 +00005332 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005333 {
5334 if (timeout_usec != 0)
5335 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005336 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005337 "running for %" PRIu32 " usec with all threads enabled.",
5338 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005339 }
5340 else
5341 {
5342 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005343 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005344 }
5345 }
Sean Callanana46ec452012-07-11 21:31:24 +00005346 else
5347 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005348 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005349 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005350 }
5351 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005352 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005353 "abandoning execution.",
5354 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005355 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005356
Jim Ingham0161b492013-02-09 01:29:05 +00005357 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5358 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5359 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5360 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5361 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005362
Jim Ingham0161b492013-02-09 01:29:05 +00005363 bool back_to_top = true;
5364 uint32_t try_halt_again = 0;
5365 bool do_halt = true;
5366 const uint32_t num_retries = 5;
5367 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005368 {
Jim Ingham0161b492013-02-09 01:29:05 +00005369 Error halt_error;
5370 if (do_halt)
5371 {
5372 if (log)
5373 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5374 halt_error = Halt();
5375 }
5376 if (halt_error.Success())
5377 {
5378 if (log)
5379 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005380
Jim Ingham0161b492013-02-09 01:29:05 +00005381 real_timeout = TimeValue::Now();
5382 real_timeout.OffsetWithMicroSeconds(500000);
5383
5384 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005385
Jim Ingham0161b492013-02-09 01:29:05 +00005386 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005387 {
Jim Ingham0161b492013-02-09 01:29:05 +00005388 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5389 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005390 {
Jim Ingham0161b492013-02-09 01:29:05 +00005391 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5392 if (stop_state == lldb::eStateStopped
5393 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5394 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005395 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005396
Jim Ingham0161b492013-02-09 01:29:05 +00005397 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005398 {
Jim Ingham0161b492013-02-09 01:29:05 +00005399 // Between the time we initiated the Halt and the time we delivered it, the process could have
5400 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005401
Jim Ingham0161b492013-02-09 01:29:05 +00005402 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5403 {
5404 if (log)
5405 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5406 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005407 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005408 back_to_top = false;
5409 break;
5410 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005411
Jim Ingham0161b492013-02-09 01:29:05 +00005412 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5413 {
5414 if (log)
5415 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5416 "Exiting wait loop.");
5417 try_halt_again++;
5418 do_halt = false;
5419 continue;
5420 }
Sean Callanana46ec452012-07-11 21:31:24 +00005421
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005422 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005423 {
5424 if (log)
5425 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005426 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005427 back_to_top = false;
5428 break;
5429 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005430
Jim Ingham0161b492013-02-09 01:29:05 +00005431 if (before_first_timeout)
5432 {
5433 // Set all the other threads to run, and return to the top of the loop, which will continue;
5434 before_first_timeout = false;
5435 thread_plan_sp->SetStopOthers (false);
5436 if (log)
5437 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005438
Jim Ingham0161b492013-02-09 01:29:05 +00005439 back_to_top = true;
5440 break;
5441 }
5442 else
5443 {
5444 // Running all threads failed, so return Interrupted.
5445 if (log)
5446 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005447 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005448 back_to_top = false;
5449 break;
5450 }
Sean Callanana46ec452012-07-11 21:31:24 +00005451 }
5452 }
5453 else
Jim Ingham0161b492013-02-09 01:29:05 +00005454 { if (log)
5455 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5456 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005457 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005458 back_to_top = false;
5459 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005460 }
5461 }
Jim Ingham0161b492013-02-09 01:29:05 +00005462 else
5463 {
5464 try_halt_again++;
5465 continue;
5466 }
Sean Callanana46ec452012-07-11 21:31:24 +00005467 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005468
Jim Ingham0161b492013-02-09 01:29:05 +00005469 if (!back_to_top || try_halt_again > num_retries)
5470 break;
5471 else
5472 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005473 }
Sean Callanana46ec452012-07-11 21:31:24 +00005474 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005475
Sean Callanana46ec452012-07-11 21:31:24 +00005476 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5477 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5478 {
5479 StopPrivateStateThread();
5480 Error error;
5481 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005482 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005483 {
5484 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5485 }
5486 m_public_state.SetValueNoLock(old_state);
5487
5488 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005489
Jim Ingham184e9812013-01-15 02:47:48 +00005490 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5491 // could happen:
5492 // 1) The execution successfully completed
5493 // 2) We hit a breakpoint, and ignore_breakpoints was true
5494 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005495 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5496 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005497
Jim Ingham8646d3c2014-05-05 02:47:44 +00005498 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005499 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005500 {
5501 thread_plan_sp->RestoreThreadState();
5502 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005503
Sean Callanana46ec452012-07-11 21:31:24 +00005504 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005505 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005506 {
5507 if (log)
5508 {
5509 StreamString s;
5510 if (event_sp)
5511 event_sp->Dump (&s);
5512 else
5513 {
5514 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5515 }
5516
5517 StreamString ts;
5518
5519 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005520
Sean Callanana46ec452012-07-11 21:31:24 +00005521 do
5522 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005523 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005524 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005525 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005526 break;
5527 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005528 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005529 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005530 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005531 break;
5532 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005533 else
Sean Callanana46ec452012-07-11 21:31:24 +00005534 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005535 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5536
5537 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005538 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005539 event_explanation = "<no event data>";
5540 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005541 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005542
Jim Inghamcfc09352012-07-27 23:57:19 +00005543 Process *process = event_data->GetProcessSP().get();
5544
5545 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005546 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005547 event_explanation = "<no process>";
5548 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005549 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005550
Jim Inghamcfc09352012-07-27 23:57:19 +00005551 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005552
Jim Inghamcfc09352012-07-27 23:57:19 +00005553 uint32_t num_threads = thread_list.GetSize();
5554 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005555
Jim Inghamcfc09352012-07-27 23:57:19 +00005556 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005557
Jim Inghamcfc09352012-07-27 23:57:19 +00005558 for (thread_index = 0;
5559 thread_index < num_threads;
5560 ++thread_index)
5561 {
5562 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005563
Jim Inghamcfc09352012-07-27 23:57:19 +00005564 if (!thread)
5565 {
5566 ts.Printf("<?> ");
5567 continue;
5568 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005569
Daniel Malead01b2952012-11-29 21:49:15 +00005570 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005571 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005572
Jim Inghamcfc09352012-07-27 23:57:19 +00005573 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005574 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005575 else
5576 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005577
Jim Inghamcfc09352012-07-27 23:57:19 +00005578 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5579 if (stop_info_sp)
5580 {
5581 const char *stop_desc = stop_info_sp->GetDescription();
5582 if (stop_desc)
5583 ts.PutCString (stop_desc);
5584 }
5585 ts.Printf(">");
5586 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005587
Jim Inghamcfc09352012-07-27 23:57:19 +00005588 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005589 }
Sean Callanana46ec452012-07-11 21:31:24 +00005590 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005591
Jim Inghamcfc09352012-07-27 23:57:19 +00005592 if (event_explanation)
5593 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005594 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005595 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5596 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005597
Jim Inghame4483cf2013-09-27 01:13:01 +00005598 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005599 {
5600 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005601 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5602 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005603 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5604 thread_plan_sp->SetPrivate (orig_plan_private);
5605 }
5606 else
5607 {
5608 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005609 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5610 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005611 }
5612 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005613 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005614 {
5615 if (log)
5616 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005617
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005618 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005619 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005620 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005621 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005622 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005623 }
5624 else
5625 {
Sean Callanana46ec452012-07-11 21:31:24 +00005626 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005627 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005628 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005629 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005630 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005631 }
5632 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5633 {
5634 if (log)
5635 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005636 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005637 }
5638 else
5639 {
5640 if (log)
5641 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005642 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005643 {
5644 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005645 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005646 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5647 thread_plan_sp->SetPrivate (orig_plan_private);
5648 }
5649 }
5650 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005651
Sean Callanana46ec452012-07-11 21:31:24 +00005652 // Thread we ran the function in may have gone away because we ran the target
5653 // Check that it's still there, and if it is put it back in the context. Also restore the
5654 // frame in the context if it is still present.
5655 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5656 if (thread)
5657 {
5658 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5659 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005660
Sean Callanana46ec452012-07-11 21:31:24 +00005661 // Also restore the current process'es selected frame & thread, since this function calling may
5662 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005663
Sean Callanana46ec452012-07-11 21:31:24 +00005664 if (selected_tid != LLDB_INVALID_THREAD_ID)
5665 {
5666 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5667 {
5668 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005669 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005670 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005671 if (old_frame_sp)
5672 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005673 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005674 }
5675 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005676
Sean Callanana46ec452012-07-11 21:31:24 +00005677 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005678
Sean Callanana46ec452012-07-11 21:31:24 +00005679 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005680 {
Sean Callanana46ec452012-07-11 21:31:24 +00005681 if (log)
5682 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5683 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005684 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005685
Jim Inghamf48169b2010-11-30 02:22:11 +00005686 return return_value;
5687}
5688
5689const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005690Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005691{
5692 const char *result_name;
5693
5694 switch (result)
5695 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005696 case eExpressionCompleted:
5697 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005698 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005699 case eExpressionDiscarded:
5700 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005701 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005702 case eExpressionInterrupted:
5703 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005704 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005705 case eExpressionHitBreakpoint:
5706 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005707 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005708 case eExpressionSetupError:
5709 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005710 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005711 case eExpressionParseError:
5712 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005713 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005714 case eExpressionResultUnavailable:
5715 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005716 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005717 case eExpressionTimedOut:
5718 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005719 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005720 case eExpressionStoppedForDebug:
5721 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005722 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005723 }
5724 return result_name;
5725}
5726
Greg Clayton7260f622011-04-18 08:33:37 +00005727void
5728Process::GetStatus (Stream &strm)
5729{
5730 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005731 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005732 {
5733 if (state == eStateExited)
5734 {
5735 int exit_status = GetExitStatus();
5736 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005737 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005738 GetID(),
5739 exit_status,
5740 exit_status,
5741 exit_description ? exit_description : "");
5742 }
5743 else
5744 {
5745 if (state == eStateConnected)
5746 strm.Printf ("Connected to remote target.\n");
5747 else
Daniel Malead01b2952012-11-29 21:49:15 +00005748 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005749 }
5750 }
5751 else
5752 {
Daniel Malead01b2952012-11-29 21:49:15 +00005753 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005754 }
5755}
5756
5757size_t
5758Process::GetThreadStatus (Stream &strm,
5759 bool only_threads_with_stop_reason,
5760 uint32_t start_frame,
5761 uint32_t num_frames,
5762 uint32_t num_frames_with_source)
5763{
5764 size_t num_thread_infos_dumped = 0;
5765
Jim Ingham4a65fb12014-03-07 11:20:03 +00005766 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5767 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5768 // ID's, and look them up one by one:
5769
5770 uint32_t num_threads;
5771 std::vector<uint32_t> thread_index_array;
5772 //Scope for thread list locker;
5773 {
5774 Mutex::Locker locker (GetThreadList().GetMutex());
5775 ThreadList &curr_thread_list = GetThreadList();
5776 num_threads = curr_thread_list.GetSize();
5777 uint32_t idx;
5778 thread_index_array.resize(num_threads);
5779 for (idx = 0; idx < num_threads; ++idx)
5780 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5781 }
5782
Greg Clayton7260f622011-04-18 08:33:37 +00005783 for (uint32_t i = 0; i < num_threads; i++)
5784 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005785 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5786 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005787 {
5788 if (only_threads_with_stop_reason)
5789 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005790 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005791 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005792 continue;
5793 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005794 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005795 start_frame,
5796 num_frames,
5797 num_frames_with_source);
5798 ++num_thread_infos_dumped;
5799 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005800 else
5801 {
5802 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5803 if (log)
5804 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5805
5806 }
Greg Clayton7260f622011-04-18 08:33:37 +00005807 }
5808 return num_thread_infos_dumped;
5809}
5810
Greg Claytona9f40ad2012-02-22 04:37:26 +00005811void
5812Process::AddInvalidMemoryRegion (const LoadRange &region)
5813{
5814 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5815}
5816
5817bool
5818Process::RemoveInvalidMemoryRange (const LoadRange &region)
5819{
5820 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5821}
5822
Jim Ingham372787f2012-04-07 00:00:41 +00005823void
5824Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5825{
5826 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5827}
5828
5829bool
5830Process::RunPreResumeActions ()
5831{
5832 bool result = true;
5833 while (!m_pre_resume_actions.empty())
5834 {
5835 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5836 m_pre_resume_actions.pop_back();
5837 bool this_result = action.callback (action.baton);
5838 if (result == true) result = this_result;
5839 }
5840 return result;
5841}
5842
5843void
5844Process::ClearPreResumeActions ()
5845{
5846 m_pre_resume_actions.clear();
5847}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005848
Greg Claytonfa559e52012-05-18 02:38:05 +00005849void
5850Process::Flush ()
5851{
5852 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005853 m_extended_thread_list.Flush();
5854 m_extended_thread_stop_id = 0;
5855 m_queue_list.Clear();
5856 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005857}
Greg Clayton90ba8112012-12-05 00:16:59 +00005858
5859void
5860Process::DidExec ()
5861{
5862 Target &target = GetTarget();
5863 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005864 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005865 m_dynamic_checkers_ap.reset();
5866 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005867 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005868 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005869 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005870 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005871 m_image_tokens.clear();
5872 m_allocated_memory_cache.Clear();
5873 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005874 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005875 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005876 DoDidExec();
5877 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005878 // Flush the process (threads and all stack frames) after running CompleteAttach()
5879 // in case the dynamic loader loaded things in new locations.
5880 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005881
5882 // After we figure out what was loaded/unloaded in CompleteAttach,
5883 // we need to let the target know so it can do any cleanup it needs to.
5884 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005885}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005886
Jim Ingham1460e4b2014-01-10 23:46:59 +00005887addr_t
5888Process::ResolveIndirectFunction(const Address *address, Error &error)
5889{
5890 if (address == nullptr)
5891 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005892 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005893 return LLDB_INVALID_ADDRESS;
5894 }
5895
5896 addr_t function_addr = LLDB_INVALID_ADDRESS;
5897
5898 addr_t addr = address->GetLoadAddress(&GetTarget());
5899 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5900 if (iter != m_resolved_indirect_addresses.end())
5901 {
5902 function_addr = (*iter).second;
5903 }
5904 else
5905 {
5906 if (!InferiorCall(this, address, function_addr))
5907 {
5908 Symbol *symbol = address->CalculateSymbolContextSymbol();
5909 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5910 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5911 function_addr = LLDB_INVALID_ADDRESS;
5912 }
5913 else
5914 {
5915 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5916 }
5917 }
5918 return function_addr;
5919}
5920
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005921void
5922Process::ModulesDidLoad (ModuleList &module_list)
5923{
5924 SystemRuntime *sys_runtime = GetSystemRuntime();
5925 if (sys_runtime)
5926 {
5927 sys_runtime->ModulesDidLoad (module_list);
5928 }
5929
5930 GetJITLoaders().ModulesDidLoad (module_list);
5931}