blob: 140b0d09fb1d67465b16da858f7c1e321b09dbd2 [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
Todd Fiala76e0fc92014-08-27 22:58:26 +00002894Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
2895 NextEventAction (process),
2896 m_exec_count (exec_count)
2897{
2898 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2899 if (log)
2900 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
2901}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002902
Jim Inghambb3a2832011-01-29 01:49:25 +00002903Process::NextEventAction::EventActionResult
2904Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905{
Todd Fiala76e0fc92014-08-27 22:58:26 +00002906 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2907
Jim Inghambb3a2832011-01-29 01:49:25 +00002908 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00002909 if (log)
2910 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
2911
2912 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002913 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002914 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002915 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002916 return eEventActionRetry;
2917
2918 case eStateStopped:
2919 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002920 {
2921 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002922 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002923 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002924 // We don't want these events to be reported, so go set the ShouldReportStop here:
2925 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2926
Greg Claytonc9ed4782011-11-12 02:10:56 +00002927 if (m_exec_count > 0)
2928 {
2929 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00002930
2931 if (log)
2932 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
2933
Jim Ingham221d51c2013-05-08 00:35:16 +00002934 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002935 return eEventActionRetry;
2936 }
2937 else
2938 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00002939 if (log)
2940 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
2941
Greg Claytonc9ed4782011-11-12 02:10:56 +00002942 m_process->CompleteAttach ();
2943 return eEventActionSuccess;
2944 }
2945 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002946 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002947
Greg Clayton513c26c2011-01-29 07:10:55 +00002948 default:
2949 case eStateExited:
2950 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002951 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002952 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002953
2954 m_exit_string.assign ("No valid Process");
2955 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002956}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002957
Jim Inghambb3a2832011-01-29 01:49:25 +00002958Process::NextEventAction::EventActionResult
2959Process::AttachCompletionHandler::HandleBeingInterrupted()
2960{
2961 return eEventActionSuccess;
2962}
2963
2964const char *
2965Process::AttachCompletionHandler::GetExitString ()
2966{
2967 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968}
2969
2970Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002971Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002973 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002974 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002975 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002976 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002977 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002978 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002979
Greg Clayton144f3a92011-11-15 03:53:30 +00002980 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002981 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002982 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002983 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002984 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002985
Greg Clayton144f3a92011-11-15 03:53:30 +00002986 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002987 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002988 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2989
2990 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002992 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2993 if (error.Success())
2994 {
Ed Maste64fad602013-07-29 20:58:06 +00002995 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002996 {
2997 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002998 const bool restarted = false;
2999 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003000 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003001 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003002 }
3003 else
3004 {
3005 // This shouldn't happen
3006 error.SetErrorString("failed to acquire process run lock");
3007 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003008
Greg Clayton144f3a92011-11-15 03:53:30 +00003009 if (error.Fail())
3010 {
3011 if (GetID() != LLDB_INVALID_PROCESS_ID)
3012 {
3013 SetID (LLDB_INVALID_PROCESS_ID);
3014 if (error.AsCString() == NULL)
3015 error.SetErrorString("attach failed");
3016
3017 SetExitStatus(-1, error.AsCString());
3018 }
3019 }
3020 else
3021 {
3022 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3023 StartPrivateStateThread();
3024 }
3025 return error;
3026 }
Greg Claytone996fd32011-03-08 22:40:15 +00003027 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003028 else
Greg Claytone996fd32011-03-08 22:40:15 +00003029 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003030 ProcessInstanceInfoList process_infos;
3031 PlatformSP platform_sp (m_target.GetPlatform ());
3032
3033 if (platform_sp)
3034 {
3035 ProcessInstanceInfoMatch match_info;
3036 match_info.GetProcessInfo() = attach_info;
3037 match_info.SetNameMatchType (eNameMatchEquals);
3038 platform_sp->FindProcesses (match_info, process_infos);
3039 const uint32_t num_matches = process_infos.GetSize();
3040 if (num_matches == 1)
3041 {
3042 attach_pid = process_infos.GetProcessIDAtIndex(0);
3043 // Fall through and attach using the above process ID
3044 }
3045 else
3046 {
3047 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3048 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003049 {
3050 StreamString s;
3051 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3052 for (size_t i = 0; i < num_matches; i++)
3053 {
3054 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3055 }
3056 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3057 process_name,
3058 s.GetData());
3059 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003060 else
3061 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3062 }
3063 }
3064 else
3065 {
3066 error.SetErrorString ("invalid platform, can't find processes by name");
3067 return error;
3068 }
Greg Claytone996fd32011-03-08 22:40:15 +00003069 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003070 }
3071 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003072 {
3073 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003074 }
3075 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003076
3077 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003078 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003079 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003080 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003082
Ed Maste64fad602013-07-29 20:58:06 +00003083 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003084 {
3085 // Now attach using these arguments.
3086 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003087 const bool restarted = false;
3088 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003089 error = DoAttachToProcessWithID (attach_pid, attach_info);
3090 }
3091 else
3092 {
3093 // This shouldn't happen
3094 error.SetErrorString("failed to acquire process run lock");
3095 }
3096
Greg Clayton144f3a92011-11-15 03:53:30 +00003097 if (error.Success())
3098 {
3099
3100 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3101 StartPrivateStateThread();
3102 }
3103 else
Greg Claytone996fd32011-03-08 22:40:15 +00003104 {
3105 if (GetID() != LLDB_INVALID_PROCESS_ID)
3106 {
3107 SetID (LLDB_INVALID_PROCESS_ID);
3108 const char *error_string = error.AsCString();
3109 if (error_string == NULL)
3110 error_string = "attach failed";
3111
3112 SetExitStatus(-1, error_string);
3113 }
3114 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115 }
3116 }
3117 return error;
3118}
3119
Greg Clayton93d3c8332011-02-16 04:46:07 +00003120void
3121Process::CompleteAttach ()
3122{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003123 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3124 if (log)
3125 log->Printf ("Process::%s()", __FUNCTION__);
3126
Greg Clayton93d3c8332011-02-16 04:46:07 +00003127 // Let the process subclass figure out at much as it can about the process
3128 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003129 ArchSpec process_arch;
3130 DidAttach(process_arch);
3131
3132 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003133 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003134 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003135 if (log)
3136 {
3137 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3138 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3139 __FUNCTION__,
3140 triple_str ? triple_str : "<null>");
3141 }
3142 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003143
Jim Ingham4299fdb2011-09-15 01:10:17 +00003144 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3145 // the same as the one we've already set, switch architectures.
3146 PlatformSP platform_sp (m_target.GetPlatform ());
3147 assert (platform_sp.get());
3148 if (platform_sp)
3149 {
Greg Clayton70512312012-05-08 01:45:38 +00003150 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003151 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003152 {
3153 ArchSpec platform_arch;
3154 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3155 if (platform_sp)
3156 {
3157 m_target.SetPlatform (platform_sp);
3158 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003159 if (log)
3160 log->Printf ("Process::%s switching platform to %s and architecture to %s based on info from attach", __FUNCTION__, platform_sp->GetName().AsCString (""), platform_arch.GetTriple().getTriple().c_str ());
Greg Clayton70512312012-05-08 01:45:38 +00003161 }
3162 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003163 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003164 {
3165 ProcessInstanceInfo process_info;
3166 platform_sp->GetProcessInfo (GetID(), process_info);
3167 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003168 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003169 {
Greg Clayton70512312012-05-08 01:45:38 +00003170 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003171 if (log)
3172 log->Printf ("Process::%s switching architecture to %s based on info the platform retrieved for pid %" PRIu64, __FUNCTION__, process_arch.GetTriple().getTriple().c_str (), GetID ());
3173 }
Greg Clayton70512312012-05-08 01:45:38 +00003174 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003175 }
3176
3177 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003178 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003179 DynamicLoader *dyld = GetDynamicLoader ();
3180 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003181 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003182 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003183 if (log)
3184 {
3185 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3186 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3187 __FUNCTION__,
3188 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3189 dyld->GetPluginName().AsCString ("<unnamed>"));
3190 }
3191 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003192
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003193 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003194
Jason Molendaeef51062013-11-05 03:57:19 +00003195 SystemRuntime *system_runtime = GetSystemRuntime ();
3196 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003197 {
Jason Molendaeef51062013-11-05 03:57:19 +00003198 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003199 if (log)
3200 {
3201 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3202 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3203 __FUNCTION__,
3204 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3205 system_runtime->GetPluginName().AsCString("<unnamed>"));
3206 }
3207 }
Jason Molendaeef51062013-11-05 03:57:19 +00003208
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003209 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003210 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003211 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003212 Mutex::Locker modules_locker(target_modules.GetMutex());
3213 size_t num_modules = target_modules.GetSize();
3214 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003215
Andy Gibbsa297a972013-06-19 19:04:53 +00003216 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003217 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003218 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003219 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003220 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003221 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003222 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003223 break;
3224 }
3225 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003226 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003227 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003228 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003229 if (log)
3230 {
3231 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3232 log->Printf ("Process::%s after looping through modules, target executable is %s",
3233 __FUNCTION__,
3234 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3235 }
3236 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003237}
3238
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003240Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003241{
Greg Claytonb766a732011-02-04 01:58:07 +00003242 m_abi_sp.reset();
3243 m_process_input_reader.reset();
3244
3245 // Find the process and its architecture. Make sure it matches the architecture
3246 // of the current Target, and if not adjust it.
3247
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003248 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003249 if (error.Success())
3250 {
Greg Clayton71337622011-02-24 22:24:29 +00003251 if (GetID() != LLDB_INVALID_PROCESS_ID)
3252 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003253 EventSP event_sp;
3254 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3255
3256 if (state == eStateStopped || state == eStateCrashed)
3257 {
3258 // If we attached and actually have a process on the other end, then
3259 // this ended up being the equivalent of an attach.
3260 CompleteAttach ();
3261
3262 // This delays passing the stopped event to listeners till
3263 // CompleteAttach gets a chance to complete...
3264 HandlePrivateEvent (event_sp);
3265
3266 }
Greg Clayton71337622011-02-24 22:24:29 +00003267 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003268
3269 if (PrivateStateThreadIsValid ())
3270 ResumePrivateStateThread ();
3271 else
3272 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003273 }
3274 return error;
3275}
3276
3277
3278Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003279Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280{
Greg Clayton5160ce52013-03-27 23:08:40 +00003281 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003282 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003283 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003284 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003285 StateAsCString(m_public_state.GetValue()),
3286 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287
3288 Error error (WillResume());
3289 // Tell the process it is about to resume before the thread list
3290 if (error.Success())
3291 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003292 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003293 // can let all of our threads know that they are about to be
3294 // resumed. Threads will each be called with
3295 // Thread::WillResume(StateType) where StateType contains the state
3296 // that they are supposed to have when the process is resumed
3297 // (suspended/running/stepping). Threads should also check
3298 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003299 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003300 if (m_thread_list.WillResume())
3301 {
Jim Ingham372787f2012-04-07 00:00:41 +00003302 // Last thing, do the PreResumeActions.
3303 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003304 {
Jim Ingham0161b492013-02-09 01:29:05 +00003305 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003306 }
3307 else
3308 {
3309 m_mod_id.BumpResumeID();
3310 error = DoResume();
3311 if (error.Success())
3312 {
3313 DidResume();
3314 m_thread_list.DidResume();
3315 if (log)
3316 log->Printf ("Process thinks the process has resumed.");
3317 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318 }
3319 }
3320 else
3321 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003322 // Somebody wanted to run without running. So generate a continue & a stopped event,
3323 // and let the world handle them.
3324 if (log)
3325 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3326
3327 SetPrivateState(eStateRunning);
3328 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003329 }
3330 }
Jim Ingham444586b2011-01-24 06:34:17 +00003331 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003332 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003333 return error;
3334}
3335
3336Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003337Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003338{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003339 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3340 // in case it was already set and some thread plan logic calls halt on its
3341 // own.
3342 m_clear_thread_plans_on_stop |= clear_thread_plans;
3343
Jim Inghamaacc3182012-06-06 00:29:30 +00003344 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3345 // we could just straightaway get another event. It just narrows the window...
3346 m_currently_handling_event.WaitForValueEqualTo(false);
3347
3348
Jim Inghambb3a2832011-01-29 01:49:25 +00003349 // Pause our private state thread so we can ensure no one else eats
3350 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003351 Listener halt_listener ("lldb.process.halt_listener");
3352 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003353
Jim Inghambb3a2832011-01-29 01:49:25 +00003354 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003355 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003356
Greg Clayton06357c92014-07-30 17:38:47 +00003357 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003358 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003359 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003360
Greg Clayton513c26c2011-01-29 07:10:55 +00003361 bool caused_stop = false;
3362
3363 // Ask the process subclass to actually halt our process
3364 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003366 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003367 if (m_public_state.GetValue() == eStateAttaching)
3368 {
Greg Clayton06357c92014-07-30 17:38:47 +00003369 // Don't hijack and eat the eStateExited as the code that was doing
3370 // the attach will be waiting for this event...
3371 RestorePrivateProcessEvents();
3372 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003373 SetExitStatus(SIGKILL, "Cancelled async attach.");
3374 Destroy ();
3375 }
3376 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003377 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003378 // If "caused_stop" is true, then DoHalt stopped the process. If
3379 // "caused_stop" is false, the process was already stopped.
3380 // If the DoHalt caused the process to stop, then we want to catch
3381 // this event and set the interrupted bool to true before we pass
3382 // this along so clients know that the process was interrupted by
3383 // a halt command.
3384 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003385 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003386 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003387 TimeValue timeout_time;
3388 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003389 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003390 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3391 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003392
Jim Ingham0f16e732011-02-08 05:20:59 +00003393 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003394 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003395 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003396 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003397 }
3398 else
3399 {
Greg Clayton2637f822011-11-17 01:23:07 +00003400 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003401 {
3402 // We caused the process to interrupt itself, so mark this
3403 // as such in the stop event so clients can tell an interrupted
3404 // process from a natural stop
3405 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3406 }
3407 else
3408 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003409 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003410 if (log)
3411 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3412 error.SetErrorString ("Did not get stopped event after halt.");
3413 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003414 }
3415 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003416 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003417 }
3418 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003420 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003421 if (!restored_process_events)
3422 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003423
3424 // Post any event we might have consumed. If all goes well, we will have
3425 // stopped the process, intercepted the event and set the interrupted
3426 // bool in the event. Post it to the private event queue and that will end up
3427 // correctly setting the state.
3428 if (event_sp)
3429 m_private_state_broadcaster.BroadcastEvent(event_sp);
3430
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003431 return error;
3432}
3433
3434Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003435Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3436{
3437 Error error;
3438 if (m_public_state.GetValue() == eStateRunning)
3439 {
3440 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3441 if (log)
3442 log->Printf("Process::Destroy() About to halt.");
3443 error = Halt();
3444 if (error.Success())
3445 {
3446 // Consume the halt event.
3447 TimeValue timeout (TimeValue::Now());
3448 timeout.OffsetWithSeconds(1);
3449 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3450
3451 // If the process exited while we were waiting for it to stop, put the exited event into
3452 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3453 // they don't have a process anymore...
3454
3455 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3456 {
3457 if (log)
3458 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3459 return error;
3460 }
3461 else
3462 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3463
3464 if (state != eStateStopped)
3465 {
3466 if (log)
3467 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3468 // If we really couldn't stop the process then we should just error out here, but if the
3469 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3470 StateType private_state = m_private_state.GetValue();
3471 if (private_state != eStateStopped)
3472 {
3473 return error;
3474 }
3475 }
3476 }
3477 else
3478 {
3479 if (log)
3480 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3481 }
3482 }
3483 return error;
3484}
3485
3486Error
Jim Inghamacff8952013-05-02 00:27:30 +00003487Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003489 EventSP exit_event_sp;
3490 Error error;
3491 m_destroy_in_process = true;
3492
3493 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003494
3495 if (error.Success())
3496 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003497 if (DetachRequiresHalt())
3498 {
3499 error = HaltForDestroyOrDetach (exit_event_sp);
3500 if (!error.Success())
3501 {
3502 m_destroy_in_process = false;
3503 return error;
3504 }
3505 else if (exit_event_sp)
3506 {
3507 // We shouldn't need to do anything else here. There's no process left to detach from...
3508 StopPrivateStateThread();
3509 m_destroy_in_process = false;
3510 return error;
3511 }
3512 }
3513
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003514 m_thread_list.DiscardThreadPlans();
3515 DisableAllBreakpointSites();
3516
Jim Inghamacff8952013-05-02 00:27:30 +00003517 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003518 if (error.Success())
3519 {
3520 DidDetach();
3521 StopPrivateStateThread();
3522 }
Jim Inghamacff8952013-05-02 00:27:30 +00003523 else
3524 {
3525 return error;
3526 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003527 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003528 m_destroy_in_process = false;
3529
3530 // If we exited when we were waiting for a process to stop, then
3531 // forward the event here so we don't lose the event
3532 if (exit_event_sp)
3533 {
3534 // Directly broadcast our exited event because we shut down our
3535 // private state thread above
3536 BroadcastEvent(exit_event_sp);
3537 }
3538
3539 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3540 // the last events through the event system, in which case we might strand the write lock. Unlock
3541 // it here so when we do to tear down the process we don't get an error destroying the lock.
3542
Ed Maste64fad602013-07-29 20:58:06 +00003543 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544 return error;
3545}
3546
3547Error
3548Process::Destroy ()
3549{
Jim Ingham09437922013-03-01 20:04:25 +00003550
3551 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3552 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3553 // failed and the process stays around for some reason it won't be in a confused state.
3554
3555 m_destroy_in_process = true;
3556
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003557 Error error (WillDestroy());
3558 if (error.Success())
3559 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003560 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003561 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003562 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003563 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003564 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003565
Jim Inghamaacc3182012-06-06 00:29:30 +00003566 if (m_public_state.GetValue() != eStateRunning)
3567 {
3568 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3569 // kill it, we don't want it hitting a breakpoint...
3570 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3571 // we're not going to have much luck doing this now.
3572 m_thread_list.DiscardThreadPlans();
3573 DisableAllBreakpointSites();
3574 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003575
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003576 error = DoDestroy();
3577 if (error.Success())
3578 {
3579 DidDestroy();
3580 StopPrivateStateThread();
3581 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003582 m_stdio_communication.StopReadThread();
3583 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003584
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003585 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003586 {
3587 m_process_input_reader->SetIsDone(true);
3588 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003589 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003590 }
3591
Greg Clayton85fb1b92012-09-11 02:33:37 +00003592 // If we exited when we were waiting for a process to stop, then
3593 // forward the event here so we don't lose the event
3594 if (exit_event_sp)
3595 {
3596 // Directly broadcast our exited event because we shut down our
3597 // private state thread above
3598 BroadcastEvent(exit_event_sp);
3599 }
3600
Jim Inghamb1e2e842012-04-12 18:49:31 +00003601 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3602 // the last events through the event system, in which case we might strand the write lock. Unlock
3603 // 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 +00003604 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003605 }
Jim Ingham09437922013-03-01 20:04:25 +00003606
3607 m_destroy_in_process = false;
3608
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003609 return error;
3610}
3611
3612Error
3613Process::Signal (int signal)
3614{
3615 Error error (WillSignal());
3616 if (error.Success())
3617 {
3618 error = DoSignal(signal);
3619 if (error.Success())
3620 DidSignal();
3621 }
3622 return error;
3623}
3624
Greg Clayton514487e2011-02-15 21:59:32 +00003625lldb::ByteOrder
3626Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003627{
Greg Clayton514487e2011-02-15 21:59:32 +00003628 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003629}
3630
3631uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003632Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003633{
Greg Clayton514487e2011-02-15 21:59:32 +00003634 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003635}
3636
Greg Clayton514487e2011-02-15 21:59:32 +00003637
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003638bool
3639Process::ShouldBroadcastEvent (Event *event_ptr)
3640{
3641 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3642 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003643 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003644
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645 switch (state)
3646 {
Greg Claytonb766a732011-02-04 01:58:07 +00003647 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648 case eStateAttaching:
3649 case eStateLaunching:
3650 case eStateDetached:
3651 case eStateExited:
3652 case eStateUnloaded:
3653 // These events indicate changes in the state of the debugging session, always report them.
3654 return_value = true;
3655 break;
3656 case eStateInvalid:
3657 // We stopped for no apparent reason, don't report it.
3658 return_value = false;
3659 break;
3660 case eStateRunning:
3661 case eStateStepping:
3662 // If we've started the target running, we handle the cases where we
3663 // are already running and where there is a transition from stopped to
3664 // running differently.
3665 // running -> running: Automatically suppress extra running events
3666 // stopped -> running: Report except when there is one or more no votes
3667 // and no yes votes.
3668 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003669 if (m_force_next_event_delivery)
3670 return_value = true;
3671 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003673 switch (m_last_broadcast_state)
3674 {
3675 case eStateRunning:
3676 case eStateStepping:
3677 // We always suppress multiple runnings with no PUBLIC stop in between.
3678 return_value = false;
3679 break;
3680 default:
3681 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003682 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003683 // events. If I run the lldb/test/thread/a.out file and
3684 // break at main.cpp:58, run and hit the breakpoints on
3685 // multiple threads, then somehow during the stepping over
3686 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003687
Jim Ingham1460e4b2014-01-10 23:46:59 +00003688 // This is a transition from stop to run.
3689 switch (m_thread_list.ShouldReportRun (event_ptr))
3690 {
3691 case eVoteYes:
3692 case eVoteNoOpinion:
3693 return_value = true;
3694 break;
3695 case eVoteNo:
3696 return_value = false;
3697 break;
3698 }
3699 break;
3700 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003701 }
3702 break;
3703 case eStateStopped:
3704 case eStateCrashed:
3705 case eStateSuspended:
3706 {
3707 // We've stopped. First see if we're going to restart the target.
3708 // If we are going to stop, then we always broadcast the event.
3709 // 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 +00003710 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003711
Jim Inghamcb4ca112012-05-16 01:32:14 +00003712 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003713 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003714 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003715 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003716 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003717 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003718 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003719 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3720 // so they can properly set their state.
3721 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003722 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003723 }
3724 else
3725 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003726 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3727 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003728
Jim Ingham0161b492013-02-09 01:29:05 +00003729 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3730 // Asking the thread list is also not likely to go well, since we are running again.
3731 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003732
Jim Ingham0161b492013-02-09 01:29:05 +00003733 if (!was_restarted)
3734 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003735
Jim Ingham221d51c2013-05-08 00:35:16 +00003736 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003737 {
Jim Ingham0161b492013-02-09 01:29:05 +00003738 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3739 if (log)
3740 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003741 should_resume, StateAsCString(state),
3742 was_restarted, stop_vote);
3743
Jim Ingham0161b492013-02-09 01:29:05 +00003744 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003745 {
3746 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003747 return_value = true;
3748 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003749 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003750 case eVoteNo:
3751 return_value = false;
3752 break;
3753 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003754
Jim Inghamcb95f342012-09-05 21:13:56 +00003755 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003756 {
3757 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003758 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3759 static_cast<void*>(event_ptr),
3760 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003761 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003762 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003763 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003764
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 }
3766 else
3767 {
3768 return_value = true;
3769 SynchronouslyNotifyStateChanged (state);
3770 }
3771 }
3772 }
Jim Ingham0161b492013-02-09 01:29:05 +00003773 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003775
Jim Ingham1460e4b2014-01-10 23:46:59 +00003776 // Forcing the next event delivery is a one shot deal. So reset it here.
3777 m_force_next_event_delivery = false;
3778
Jim Ingham0161b492013-02-09 01:29:05 +00003779 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3780 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3781 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3782 // because the PublicState reflects the last event pulled off the queue, and there may be several
3783 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3784 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003785
Jim Ingham0161b492013-02-09 01:29:05 +00003786 if (return_value)
3787 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003788
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003789 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003790 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003791 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003792 StateAsCString(m_last_broadcast_state),
3793 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003794 return return_value;
3795}
3796
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003797
3798bool
Jim Ingham372787f2012-04-07 00:00:41 +00003799Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003800{
Greg Clayton5160ce52013-03-27 23:08:40 +00003801 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802
Greg Clayton8b82f082011-04-12 05:54:46 +00003803 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003804 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003805 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3806
Jim Ingham372787f2012-04-07 00:00:41 +00003807 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003808 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003809
3810 // Create a thread that watches our internal state and controls which
3811 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003812 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003813
3814 if (Host::MAX_THREAD_NAME_LENGTH <= 16)
3815 {
3816 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3817 if (already_running)
3818 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3819 else
3820 snprintf(thread_name, sizeof(thread_name), "intern-state");
3821 }
Jim Ingham372787f2012-04-07 00:00:41 +00003822 else
Todd Fiala17096d72014-07-16 19:03:16 +00003823 {
3824 if (already_running)
3825 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3826 else
3827 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3828 }
3829
Jim Ingham076b3042012-04-10 01:21:57 +00003830 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003831 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003832 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3833 if (success)
3834 {
3835 ResumePrivateStateThread();
3836 return true;
3837 }
3838 else
3839 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840}
3841
3842void
3843Process::PausePrivateStateThread ()
3844{
3845 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3846}
3847
3848void
3849Process::ResumePrivateStateThread ()
3850{
3851 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3852}
3853
3854void
3855Process::StopPrivateStateThread ()
3856{
Greg Clayton8b82f082011-04-12 05:54:46 +00003857 if (PrivateStateThreadIsValid ())
3858 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003859 else
3860 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003861 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003862 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003863 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003864 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003865}
3866
3867void
3868Process::ControlPrivateStateThread (uint32_t signal)
3869{
Greg Clayton5160ce52013-03-27 23:08:40 +00003870 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871
3872 assert (signal == eBroadcastInternalStateControlStop ||
3873 signal == eBroadcastInternalStateControlPause ||
3874 signal == eBroadcastInternalStateControlResume);
3875
3876 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003877 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003878
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003879 // Signal the private state thread. First we should copy this is case the
3880 // thread starts exiting since the private state thread will NULL this out
3881 // when it exits
3882 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003883 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003884 {
3885 TimeValue timeout_time;
3886 bool timed_out;
3887
3888 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3889
3890 timeout_time = TimeValue::Now();
3891 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003892 if (log)
3893 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003894 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3895 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3896
3897 if (signal == eBroadcastInternalStateControlStop)
3898 {
3899 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003900 {
3901 Error error;
3902 Host::ThreadCancel (private_state_thread, &error);
3903 if (log)
3904 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3905 }
3906 else
3907 {
3908 if (log)
3909 log->Printf ("The control event killed the private state thread without having to cancel.");
3910 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003911
3912 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003913 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003914 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003915 }
3916 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003917 else
3918 {
3919 if (log)
3920 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3921 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003922}
3923
3924void
Jim Inghamcfc09352012-07-27 23:57:19 +00003925Process::SendAsyncInterrupt ()
3926{
3927 if (PrivateStateThreadIsValid())
3928 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3929 else
3930 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3931}
3932
3933void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003934Process::HandlePrivateEvent (EventSP &event_sp)
3935{
Greg Clayton5160ce52013-03-27 23:08:40 +00003936 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003937 m_resume_requested = false;
3938
Jim Inghamaacc3182012-06-06 00:29:30 +00003939 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003940
Greg Clayton414f5d32011-01-25 02:58:48 +00003941 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003942
3943 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003944 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003945 {
Jim Ingham754ab982011-01-29 04:05:41 +00003946 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003947 if (log)
3948 log->Printf ("Ran next event action, result was %d.", action_result);
3949
Jim Inghambb3a2832011-01-29 01:49:25 +00003950 switch (action_result)
3951 {
3952 case NextEventAction::eEventActionSuccess:
3953 SetNextEventAction(NULL);
3954 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003955
Jim Inghambb3a2832011-01-29 01:49:25 +00003956 case NextEventAction::eEventActionRetry:
3957 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003958
Jim Inghambb3a2832011-01-29 01:49:25 +00003959 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003960 // Handle Exiting Here. If we already got an exited event,
3961 // we should just propagate it. Otherwise, swallow this event,
3962 // and set our state to exit so the next event will kill us.
3963 if (new_state != eStateExited)
3964 {
3965 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003966 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003967 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003968 SetNextEventAction(NULL);
3969 return;
3970 }
3971 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003972 break;
3973 }
3974 }
3975
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003976 // See if we should broadcast this state to external clients?
3977 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978
3979 if (should_broadcast)
3980 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003981 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003982 if (log)
3983 {
Daniel Malead01b2952012-11-29 21:49:15 +00003984 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003985 __FUNCTION__,
3986 GetID(),
3987 StateAsCString(new_state),
3988 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003989 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003990 }
Jim Ingham9575d842011-03-11 03:53:59 +00003991 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003992 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003993 {
3994 // Only push the input handler if we aren't fowarding events,
3995 // as this means the curses GUI is in use...
3996 if (!GetTarget().GetDebugger().IsForwardingEvents())
3997 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00003998 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00003999 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004000 else if (StateIsStoppedState(new_state, false))
4001 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004002 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004003 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4004 {
4005 // If the lldb_private::Debugger is handling the events, we don't
4006 // want to pop the process IOHandler here, we want to do it when
4007 // we receive the stopped event so we can carefully control when
4008 // the process IOHandler is popped because when we stop we want to
4009 // display some text stating how and why we stopped, then maybe some
4010 // process/thread/frame info, and then we want the "(lldb) " prompt
4011 // to show up. If we pop the process IOHandler here, then we will
4012 // cause the command interpreter to become the top IOHandler after
4013 // the process pops off and it will update its prompt right away...
4014 // See the Debugger.cpp file where it calls the function as
4015 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4016 // Otherwise we end up getting overlapping "(lldb) " prompts and
4017 // garbled output.
4018 //
4019 // If we aren't handling the events in the debugger (which is indicated
4020 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4021 // are hijacked, then we always pop the process IO handler manually.
4022 // Hijacking happens when the internal process state thread is running
4023 // thread plans, or when commands want to run in synchronous mode
4024 // and they call "process->WaitForProcessToStop()". An example of something
4025 // that will hijack the events is a simple expression:
4026 //
4027 // (lldb) expr (int)puts("hello")
4028 //
4029 // This will cause the internal process state thread to resume and halt
4030 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4031 // events) and we do need the IO handler to be pushed and popped
4032 // correctly.
4033
4034 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4035 PopProcessIOHandler ();
4036 }
4037 }
Jim Ingham9575d842011-03-11 03:53:59 +00004038
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004039 BroadcastEvent (event_sp);
4040 }
4041 else
4042 {
4043 if (log)
4044 {
Daniel Malead01b2952012-11-29 21:49:15 +00004045 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004046 __FUNCTION__,
4047 GetID(),
4048 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004049 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050 }
4051 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004052 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053}
4054
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004055thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004056Process::PrivateStateThread (void *arg)
4057{
4058 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004059 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004060 return result;
4061}
4062
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004063thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004064Process::RunPrivateStateThread ()
4065{
Jim Ingham076b3042012-04-10 01:21:57 +00004066 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004067 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004068
Greg Clayton5160ce52013-03-27 23:08:40 +00004069 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004070 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004071 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4072 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004073
4074 bool exit_now = false;
4075 while (!exit_now)
4076 {
4077 EventSP event_sp;
4078 WaitForEventsPrivate (NULL, event_sp, control_only);
4079 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4080 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004081 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004082 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4083 __FUNCTION__, static_cast<void*>(this), GetID(),
4084 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004085
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086 switch (event_sp->GetType())
4087 {
4088 case eBroadcastInternalStateControlStop:
4089 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004090 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091
4092 case eBroadcastInternalStateControlPause:
4093 control_only = true;
4094 break;
4095
4096 case eBroadcastInternalStateControlResume:
4097 control_only = false;
4098 break;
4099 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004100
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004101 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004102 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004103 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004104 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4105 {
4106 if (m_public_state.GetValue() == eStateAttaching)
4107 {
4108 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004109 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4110 __FUNCTION__, static_cast<void*>(this),
4111 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004112 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4113 }
4114 else
4115 {
4116 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004117 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4118 __FUNCTION__, static_cast<void*>(this),
4119 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004120 Halt();
4121 }
4122 continue;
4123 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004124
4125 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4126
4127 if (internal_state != eStateInvalid)
4128 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004129 if (m_clear_thread_plans_on_stop &&
4130 StateIsStoppedState(internal_state, true))
4131 {
4132 m_clear_thread_plans_on_stop = false;
4133 m_thread_list.DiscardThreadPlans();
4134 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004135 HandlePrivateEvent (event_sp);
4136 }
4137
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004138 if (internal_state == eStateInvalid ||
4139 internal_state == eStateExited ||
4140 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004141 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004142 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004143 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4144 __FUNCTION__, static_cast<void*>(this), GetID(),
4145 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004146
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004148 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149 }
4150
Caroline Tice20ad3c42010-10-29 21:48:37 +00004151 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004152 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004153 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4154 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004155
Ed Maste64fad602013-07-29 20:58:06 +00004156 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004157 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4158 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004159 return NULL;
4160}
4161
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004162//------------------------------------------------------------------
4163// Process Event Data
4164//------------------------------------------------------------------
4165
4166Process::ProcessEventData::ProcessEventData () :
4167 EventData (),
4168 m_process_sp (),
4169 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004170 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004171 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004172 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004173{
4174}
4175
4176Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4177 EventData (),
4178 m_process_sp (process_sp),
4179 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004180 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004181 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004182 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183{
4184}
4185
4186Process::ProcessEventData::~ProcessEventData()
4187{
4188}
4189
4190const ConstString &
4191Process::ProcessEventData::GetFlavorString ()
4192{
4193 static ConstString g_flavor ("Process::ProcessEventData");
4194 return g_flavor;
4195}
4196
4197const ConstString &
4198Process::ProcessEventData::GetFlavor () const
4199{
4200 return ProcessEventData::GetFlavorString ();
4201}
4202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004203void
4204Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4205{
4206 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004207 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4208 // the public event queue, then other times when we're pretending that this is where we stopped at the
4209 // end of expression evaluation. m_update_state is used to distinguish these
4210 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004211 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004212 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004214
Jim Ingham221d51c2013-05-08 00:35:16 +00004215 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004216
4217 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4218 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4219 // end up restarting the process.
4220 if (m_interrupted)
4221 return;
4222
4223 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004224 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004225 {
4226 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004227 uint32_t num_threads = curr_thread_list.GetSize();
4228 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004229
Jim Ingham4b536182011-08-09 02:12:22 +00004230 // The actions might change one of the thread's stop_info's opinions about whether we should
4231 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004232
4233 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4234 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4235 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4236 // 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
4237 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004238 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004239 for (idx = 0; idx < num_threads; ++idx)
4240 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4241
Jim Inghamc7078c22012-12-13 22:24:15 +00004242 // Use this to track whether we should continue from here. We will only continue the target running if
4243 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4244 // then it doesn't matter what the other threads say...
4245
4246 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004247
Jim Ingham0ad7e052013-04-25 02:04:59 +00004248 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4249 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4250 // thing to do is, and it's better to let the user decide than continue behind their backs.
4251
4252 bool does_anybody_have_an_opinion = false;
4253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004254 for (idx = 0; idx < num_threads; ++idx)
4255 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004256 curr_thread_list = m_process_sp->GetThreadList();
4257 if (curr_thread_list.GetSize() != num_threads)
4258 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004259 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004260 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004261 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 +00004262 break;
4263 }
4264
4265 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4266
4267 if (thread_sp->GetIndexID() != thread_index_array[idx])
4268 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004269 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004270 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004271 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004272 idx,
4273 thread_index_array[idx],
4274 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004275 break;
4276 }
4277
Jim Inghamb15bfc72010-10-20 00:39:53 +00004278 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004279 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004280 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004281 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004282 bool this_thread_wants_to_stop;
4283 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004284 {
Jim Ingham0161b492013-02-09 01:29:05 +00004285 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4286 }
4287 else
4288 {
4289 stop_info_sp->PerformAction(event_ptr);
4290 // The stop action might restart the target. If it does, then we want to mark that in the
4291 // event so that whoever is receiving it will know to wait for the running event and reflect
4292 // that state appropriately.
4293 // We also need to stop processing actions, since they aren't expecting the target to be running.
4294
4295 // FIXME: we might have run.
4296 if (stop_info_sp->HasTargetRunSinceMe())
4297 {
4298 SetRestarted (true);
4299 break;
4300 }
4301
4302 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004303 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004304
Jim Inghamc7078c22012-12-13 22:24:15 +00004305 if (still_should_stop == false)
4306 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004307 }
4308 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004309
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004310
Jim Inghama8ca6e22013-05-03 23:04:37 +00004311 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004312 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004313 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004314 {
4315 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004316 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004317 // Use the public resume method here, since this is just
4318 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004319 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004320 }
4321 else
4322 {
4323 // If we didn't restart, run the Stop Hooks here:
4324 // They might also restart the target, so watch for that.
4325 m_process_sp->GetTarget().RunStopHooks();
4326 if (m_process_sp->GetPrivateState() == eStateRunning)
4327 SetRestarted(true);
4328 }
Jim Ingham9575d842011-03-11 03:53:59 +00004329 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004330 }
4331}
4332
4333void
4334Process::ProcessEventData::Dump (Stream *s) const
4335{
4336 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004337 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4338 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004339
Greg Clayton8b82f082011-04-12 05:54:46 +00004340 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004341}
4342
4343const Process::ProcessEventData *
4344Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4345{
4346 if (event_ptr)
4347 {
4348 const EventData *event_data = event_ptr->GetData();
4349 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4350 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4351 }
4352 return NULL;
4353}
4354
4355ProcessSP
4356Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4357{
4358 ProcessSP process_sp;
4359 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4360 if (data)
4361 process_sp = data->GetProcessSP();
4362 return process_sp;
4363}
4364
4365StateType
4366Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4367{
4368 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4369 if (data == NULL)
4370 return eStateInvalid;
4371 else
4372 return data->GetState();
4373}
4374
4375bool
4376Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4377{
4378 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4379 if (data == NULL)
4380 return false;
4381 else
4382 return data->GetRestarted();
4383}
4384
4385void
4386Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4387{
4388 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4389 if (data != NULL)
4390 data->SetRestarted(new_value);
4391}
4392
Jim Ingham0161b492013-02-09 01:29:05 +00004393size_t
4394Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4395{
4396 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4397 if (data != NULL)
4398 return data->GetNumRestartedReasons();
4399 else
4400 return 0;
4401}
4402
4403const char *
4404Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4405{
4406 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4407 if (data != NULL)
4408 return data->GetRestartedReasonAtIndex(idx);
4409 else
4410 return NULL;
4411}
4412
4413void
4414Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4415{
4416 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4417 if (data != NULL)
4418 data->AddRestartedReason(reason);
4419}
4420
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004421bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004422Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4423{
4424 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4425 if (data == NULL)
4426 return false;
4427 else
4428 return data->GetInterrupted ();
4429}
4430
4431void
4432Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4433{
4434 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4435 if (data != NULL)
4436 data->SetInterrupted(new_value);
4437}
4438
4439bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004440Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4441{
4442 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4443 if (data)
4444 {
4445 data->SetUpdateStateOnRemoval();
4446 return true;
4447 }
4448 return false;
4449}
4450
Greg Claytond9e416c2012-02-18 05:35:26 +00004451lldb::TargetSP
4452Process::CalculateTarget ()
4453{
4454 return m_target.shared_from_this();
4455}
4456
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004457void
Greg Clayton0603aa92010-10-04 01:05:56 +00004458Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004459{
Greg Claytonc14ee322011-09-22 04:58:26 +00004460 exe_ctx.SetTargetPtr (&m_target);
4461 exe_ctx.SetProcessPtr (this);
4462 exe_ctx.SetThreadPtr(NULL);
4463 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004464}
4465
Greg Claytone996fd32011-03-08 22:40:15 +00004466//uint32_t
4467//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4468//{
4469// return 0;
4470//}
4471//
4472//ArchSpec
4473//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4474//{
4475// return Host::GetArchSpecForExistingProcess (pid);
4476//}
4477//
4478//ArchSpec
4479//Process::GetArchSpecForExistingProcess (const char *process_name)
4480//{
4481// return Host::GetArchSpecForExistingProcess (process_name);
4482//}
4483//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004484void
4485Process::AppendSTDOUT (const char * s, size_t len)
4486{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004487 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004488 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004489 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004490}
4491
4492void
Greg Clayton93e86192011-11-13 04:45:22 +00004493Process::AppendSTDERR (const char * s, size_t len)
4494{
4495 Mutex::Locker locker (m_stdio_communication_mutex);
4496 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004497 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004498}
4499
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004500void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004501Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004502{
4503 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004504 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004505 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4506}
4507
4508size_t
4509Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4510{
4511 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004512 if (m_profile_data.empty())
4513 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004514
4515 std::string &one_profile_data = m_profile_data.front();
4516 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004517 if (bytes_available > 0)
4518 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004519 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004520 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004521 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4522 static_cast<void*>(buf),
4523 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004524 if (bytes_available > buf_size)
4525 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004526 memcpy(buf, one_profile_data.c_str(), buf_size);
4527 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004528 bytes_available = buf_size;
4529 }
4530 else
4531 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004532 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004533 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004534 }
4535 }
4536 return bytes_available;
4537}
4538
4539
Greg Clayton93e86192011-11-13 04:45:22 +00004540//------------------------------------------------------------------
4541// Process STDIO
4542//------------------------------------------------------------------
4543
4544size_t
4545Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4546{
4547 Mutex::Locker locker(m_stdio_communication_mutex);
4548 size_t bytes_available = m_stdout_data.size();
4549 if (bytes_available > 0)
4550 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004551 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004552 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004553 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4554 static_cast<void*>(buf),
4555 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004556 if (bytes_available > buf_size)
4557 {
4558 memcpy(buf, m_stdout_data.c_str(), buf_size);
4559 m_stdout_data.erase(0, buf_size);
4560 bytes_available = buf_size;
4561 }
4562 else
4563 {
4564 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4565 m_stdout_data.clear();
4566 }
4567 }
4568 return bytes_available;
4569}
4570
4571
4572size_t
4573Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4574{
4575 Mutex::Locker locker(m_stdio_communication_mutex);
4576 size_t bytes_available = m_stderr_data.size();
4577 if (bytes_available > 0)
4578 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004579 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004580 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004581 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4582 static_cast<void*>(buf),
4583 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004584 if (bytes_available > buf_size)
4585 {
4586 memcpy(buf, m_stderr_data.c_str(), buf_size);
4587 m_stderr_data.erase(0, buf_size);
4588 bytes_available = buf_size;
4589 }
4590 else
4591 {
4592 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4593 m_stderr_data.clear();
4594 }
4595 }
4596 return bytes_available;
4597}
4598
4599void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004600Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4601{
4602 Process *process = (Process *) baton;
4603 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4604}
4605
Greg Clayton44d93782014-01-27 23:43:24 +00004606class IOHandlerProcessSTDIO :
4607 public IOHandler
4608{
4609public:
4610 IOHandlerProcessSTDIO (Process *process,
4611 int write_fd) :
4612 IOHandler(process->GetTarget().GetDebugger()),
4613 m_process (process),
4614 m_read_file (),
4615 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004616 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004617 {
4618 m_read_file.SetDescriptor(GetInputFD(), false);
4619 }
4620
4621 virtual
4622 ~IOHandlerProcessSTDIO ()
4623 {
4624
4625 }
4626
4627 bool
4628 OpenPipes ()
4629 {
Greg Clayton100eb932014-07-02 21:10:39 +00004630 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004631 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004632 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004633 }
4634
4635 void
4636 ClosePipes()
4637 {
Greg Clayton100eb932014-07-02 21:10:39 +00004638 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004639 }
4640
4641 // Each IOHandler gets to run until it is done. It should read data
4642 // from the "in" and place output into "out" and "err and return
4643 // when done.
4644 virtual void
4645 Run ()
4646 {
4647 if (m_read_file.IsValid() && m_write_file.IsValid())
4648 {
4649 SetIsDone(false);
4650 if (OpenPipes())
4651 {
4652 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004653 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004654 TerminalState terminal_state;
4655 terminal_state.Save (read_fd, false);
4656 Terminal terminal(read_fd);
4657 terminal.SetCanonical(false);
4658 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004659// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004660#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004661 while (!GetIsDone())
4662 {
4663 fd_set read_fdset;
4664 FD_ZERO (&read_fdset);
4665 FD_SET (read_fd, &read_fdset);
4666 FD_SET (pipe_read_fd, &read_fdset);
4667 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4668 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4669 if (num_set_fds < 0)
4670 {
4671 const int select_errno = errno;
4672
4673 if (select_errno != EINTR)
4674 SetIsDone(true);
4675 }
4676 else if (num_set_fds > 0)
4677 {
4678 char ch = 0;
4679 size_t n;
4680 if (FD_ISSET (read_fd, &read_fdset))
4681 {
4682 n = 1;
4683 if (m_read_file.Read(&ch, n).Success() && n == 1)
4684 {
4685 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4686 SetIsDone(true);
4687 }
4688 else
4689 SetIsDone(true);
4690 }
4691 if (FD_ISSET (pipe_read_fd, &read_fdset))
4692 {
4693 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004694 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004695 {
Greg Clayton100eb932014-07-02 21:10:39 +00004696 switch (ch)
4697 {
4698 case 'q':
4699 SetIsDone(true);
4700 break;
4701 case 'i':
4702 if (StateIsRunningState(m_process->GetState()))
4703 m_process->Halt();
4704 break;
4705 }
Greg Clayton19e11352014-02-26 22:47:33 +00004706 }
Greg Clayton44d93782014-01-27 23:43:24 +00004707 }
4708 }
4709 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004710#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004711 terminal_state.Restore();
4712
4713 }
4714 else
4715 SetIsDone(true);
4716 }
4717 else
4718 SetIsDone(true);
4719 }
4720
4721 // Hide any characters that have been displayed so far so async
4722 // output can be displayed. Refresh() will be called after the
4723 // output has been displayed.
4724 virtual void
4725 Hide ()
4726 {
4727
4728 }
4729 // Called when the async output has been received in order to update
4730 // the input reader (refresh the prompt and redisplay any current
4731 // line(s) that are being edited
4732 virtual void
4733 Refresh ()
4734 {
4735
4736 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004737
Greg Clayton44d93782014-01-27 23:43:24 +00004738 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004739 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004740 {
Greg Clayton19e11352014-02-26 22:47:33 +00004741 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004742 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004743 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004744
Greg Claytonf0066ad2014-05-02 00:45:31 +00004745 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004746 Interrupt ()
4747 {
Greg Clayton19e11352014-02-26 22:47:33 +00004748 // Do only things that are safe to do in an interrupt context (like in
4749 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4750 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4751 // that was written to the pipe and then call m_process->Halt() from a
4752 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004753 if (m_active)
4754 {
4755 char ch = 'i'; // Send 'i' for interrupt
4756 return m_pipe.Write (&ch, 1) == 1;
4757 }
4758 else
4759 {
4760 // This IOHandler might be pushed on the stack, but not being run currently
4761 // so do the right thing if we aren't actively watching for STDIN by sending
4762 // the interrupt to the process. Otherwise the write to the pipe above would
4763 // do nothing. This can happen when the command interpreter is running and
4764 // gets a "expression ...". It will be on the IOHandler thread and sending
4765 // the input is complete to the delegate which will cause the expression to
4766 // run, which will push the process IO handler, but not run it.
4767
4768 if (StateIsRunningState(m_process->GetState()))
4769 {
4770 m_process->SendAsyncInterrupt();
4771 return true;
4772 }
4773 }
4774 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004775 }
Greg Clayton44d93782014-01-27 23:43:24 +00004776
4777 virtual void
4778 GotEOF()
4779 {
4780
4781 }
4782
4783protected:
4784 Process *m_process;
4785 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4786 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004787 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004788};
4789
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004790void
Greg Clayton44d93782014-01-27 23:43:24 +00004791Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004792{
4793 // First set up the Read Thread for reading/handling process I/O
4794
Greg Clayton44d93782014-01-27 23:43:24 +00004795 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004796
4797 if (conn_ap.get())
4798 {
4799 m_stdio_communication.SetConnection (conn_ap.release());
4800 if (m_stdio_communication.IsConnected())
4801 {
4802 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4803 m_stdio_communication.StartReadThread();
4804
4805 // Now read thread is set up, set up input reader.
4806
4807 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004808 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004809 }
4810 }
4811}
4812
Greg Claytonb4874f12014-02-28 18:22:24 +00004813bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004814Process::ProcessIOHandlerIsActive ()
4815{
4816 IOHandlerSP io_handler_sp (m_process_input_reader);
4817 if (io_handler_sp)
4818 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4819 return false;
4820}
4821bool
Greg Clayton44d93782014-01-27 23:43:24 +00004822Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004823{
Greg Clayton44d93782014-01-27 23:43:24 +00004824 IOHandlerSP io_handler_sp (m_process_input_reader);
4825 if (io_handler_sp)
4826 {
4827 io_handler_sp->SetIsDone(false);
4828 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004829 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004830 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004831 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004832}
4833
Greg Claytonb4874f12014-02-28 18:22:24 +00004834bool
Greg Clayton44d93782014-01-27 23:43:24 +00004835Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004836{
Greg Clayton44d93782014-01-27 23:43:24 +00004837 IOHandlerSP io_handler_sp (m_process_input_reader);
4838 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004839 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4840 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004841}
4842
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004843// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004844void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004845Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004846{
Greg Clayton6920b522012-08-22 18:39:03 +00004847 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004848}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004849
Greg Clayton99d0faf2010-11-18 23:32:35 +00004850void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004851Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004852{
Greg Clayton6920b522012-08-22 18:39:03 +00004853 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004854}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004855
Jim Ingham1624a2d2014-05-05 02:26:40 +00004856ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004857Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004858 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004859 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004860 Stream &errors)
4861{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004862 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004863
Jim Ingham77787032011-01-20 02:03:18 +00004864 if (thread_plan_sp.get() == NULL)
4865 {
4866 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004867 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004868 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004869
Jim Ingham7d7931d2013-03-28 00:05:34 +00004870 if (!thread_plan_sp->ValidatePlan(NULL))
4871 {
4872 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004873 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004874 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004875
Greg Claytonc14ee322011-09-22 04:58:26 +00004876 if (exe_ctx.GetProcessPtr() != this)
4877 {
4878 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004879 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004880 }
4881
4882 Thread *thread = exe_ctx.GetThreadPtr();
4883 if (thread == NULL)
4884 {
4885 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004886 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004887 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004888
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004889 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4890 // For that to be true the plan can't be private - since private plans suppress themselves in the
4891 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004892
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004893 bool orig_plan_private = thread_plan_sp->GetPrivate();
4894 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004895
Jim Ingham444586b2011-01-24 06:34:17 +00004896 if (m_private_state.GetValue() != eStateStopped)
4897 {
4898 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004899 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004900 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004901
Jim Ingham66243842011-08-13 00:56:10 +00004902 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004903 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004904 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004905 if (!selected_frame_sp)
4906 {
4907 thread->SetSelectedFrame(0);
4908 selected_frame_sp = thread->GetSelectedFrame();
4909 if (!selected_frame_sp)
4910 {
4911 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004912 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004913 }
4914 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004915
Jim Ingham11b0e052013-02-19 23:22:45 +00004916 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004917
4918 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4919 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004920
Greg Claytonc14ee322011-09-22 04:58:26 +00004921 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004922
Jim Ingham66243842011-08-13 00:56:10 +00004923 uint32_t selected_tid;
4924 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004925 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004926 {
4927 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004928 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004929 }
4930 else
4931 {
4932 selected_tid = LLDB_INVALID_THREAD_ID;
4933 }
4934
Jim Ingham372787f2012-04-07 00:00:41 +00004935 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004936 lldb::StateType old_state;
4937 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004938
Greg Clayton5160ce52013-03-27 23:08:40 +00004939 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004940 if (Host::GetCurrentThread() == m_private_state_thread)
4941 {
Jim Ingham076b3042012-04-10 01:21:57 +00004942 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4943 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004944 // 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 +00004945 // we are fielding public events here.
4946 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004947 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 +00004948
Jim Ingham372787f2012-04-07 00:00:41 +00004949 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004950
4951 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4952 // returning control here.
4953 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4954 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4955 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4956 // do just what we want.
4957 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4958 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4959 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4960 old_state = m_public_state.GetValue();
4961 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004962
Jim Ingham076b3042012-04-10 01:21:57 +00004963 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004964 StartPrivateStateThread(true);
4965 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004966
Jim Ingham372787f2012-04-07 00:00:41 +00004967 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004968
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004969 if (options.GetDebug())
4970 {
4971 // In this case, we aren't actually going to run, we just want to stop right away.
4972 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4973 // FIXME: To make this prettier we should invent some stop reason for this, but that
4974 // is only cosmetic, and this functionality is only of use to lldb developers who can
4975 // live with not pretty...
4976 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004977 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004978 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004979
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004980 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004981
Sean Callanana46ec452012-07-11 21:31:24 +00004982 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004983
Jim Ingham77787032011-01-20 02:03:18 +00004984 {
Sean Callanana46ec452012-07-11 21:31:24 +00004985 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4986 // restored on exit to the function.
4987 //
4988 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4989 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004990
Sean Callanana46ec452012-07-11 21:31:24 +00004991 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004992
Jim Inghamf48169b2010-11-30 02:22:11 +00004993 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004994 {
4995 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004996 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004997 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004998 thread->GetIndexID(),
4999 thread->GetID(),
5000 s.GetData());
5001 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005002
Sean Callanana46ec452012-07-11 21:31:24 +00005003 bool got_event;
5004 lldb::EventSP event_sp;
5005 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005006
Sean Callanana46ec452012-07-11 21:31:24 +00005007 TimeValue* timeout_ptr = NULL;
5008 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005009
Jim Ingham0161b492013-02-09 01:29:05 +00005010 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 +00005011 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005012 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005013 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005014
Jim Ingham0161b492013-02-09 01:29:05 +00005015 // This is just for accounting:
5016 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005017
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005018 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005019 uint32_t one_thread_timeout_usec;
5020 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005021
5022 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5023 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5024 // first timeout already.
5025
5026 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005027 {
5028 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005029 one_thread_timeout_usec = 0;
5030 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005031 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005032 else
Jim Ingham0161b492013-02-09 01:29:05 +00005033 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005034 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005035
Jim Ingham914f4e72014-03-28 21:58:28 +00005036 // If the overall wait is forever, then we only need to set the one thread timeout:
5037 if (timeout_usec == 0)
5038 {
Ed Maste801335c2014-03-31 19:28:14 +00005039 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005040 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005041 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005042 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005043 }
Jim Ingham0161b492013-02-09 01:29:05 +00005044 else
5045 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005046 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5047 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5048 uint64_t computed_one_thread_timeout;
5049 if (option_one_thread_timeout != 0)
5050 {
5051 if (timeout_usec < option_one_thread_timeout)
5052 {
5053 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005054 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005055 }
5056 computed_one_thread_timeout = option_one_thread_timeout;
5057 }
5058 else
5059 {
5060 computed_one_thread_timeout = timeout_usec / 2;
5061 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5062 computed_one_thread_timeout = default_one_thread_timeout_usec;
5063 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005064 one_thread_timeout_usec = computed_one_thread_timeout;
5065 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5066
Jim Ingham0161b492013-02-09 01:29:05 +00005067 }
Jim Ingham0161b492013-02-09 01:29:05 +00005068 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005069
5070 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005071 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 +00005072 options.GetStopOthers(),
5073 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005074 before_first_timeout,
5075 one_thread_timeout_usec,
5076 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005077
Jim Ingham1460e4b2014-01-10 23:46:59 +00005078 // This isn't going to work if there are unfetched events on the queue.
5079 // Are there cases where we might want to run the remaining events here, and then try to
5080 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005081
Jim Ingham1460e4b2014-01-10 23:46:59 +00005082 Event *other_events = listener.PeekAtNextEvent();
5083 if (other_events != NULL)
5084 {
5085 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005086 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005087 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005088
Jim Ingham1460e4b2014-01-10 23:46:59 +00005089 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5090 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5091 // event coalescing to cause us to lose OUR running event...
5092 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005093
Jim Ingham8559a352012-11-26 23:52:18 +00005094 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5095 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005096
5097#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5098 // It's pretty much impossible to write test cases for things like:
5099 // One thread timeout expires, I go to halt, but the process already stopped
5100 // on the function call stop breakpoint. Turning on this define will make us not
5101 // fetch the first event till after the halt. So if you run a quick function, it will have
5102 // completed, and the completion event will be waiting, when you interrupt for halt.
5103 // The expression evaluation should still succeed.
5104 bool miss_first_event = true;
5105#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005106 TimeValue one_thread_timeout;
5107 TimeValue final_timeout;
5108
Jim Ingham35878c42014-04-08 21:33:21 +00005109
Sean Callanana46ec452012-07-11 21:31:24 +00005110 while (1)
5111 {
5112 // We usually want to resume the process if we get to the top of the loop.
5113 // The only exception is if we get two running events with no intervening
5114 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005115 if (log)
5116 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5117 do_resume,
5118 handle_running_event,
5119 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005120
Jim Ingham184e9812013-01-15 02:47:48 +00005121 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005122 {
5123 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005124
Jim Ingham184e9812013-01-15 02:47:48 +00005125 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005126 {
Jim Ingham0161b492013-02-09 01:29:05 +00005127 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005128 Error resume_error = PrivateResume ();
5129 if (!resume_error.Success())
5130 {
Jim Ingham0161b492013-02-09 01:29:05 +00005131 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5132 num_resumes,
5133 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005134 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005135 break;
5136 }
Sean Callanana46ec452012-07-11 21:31:24 +00005137 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005138
Jim Ingham0161b492013-02-09 01:29:05 +00005139 TimeValue resume_timeout = TimeValue::Now();
5140 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005141
Jim Ingham0161b492013-02-09 01:29:05 +00005142 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005143 if (!got_event)
5144 {
5145 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005146 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5147 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005148
Jim Ingham0161b492013-02-09 01:29:05 +00005149 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005150 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005151 break;
5152 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005153
Sean Callanana46ec452012-07-11 21:31:24 +00005154 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005155
Sean Callanana46ec452012-07-11 21:31:24 +00005156 if (stop_state != eStateRunning)
5157 {
Jim Ingham0161b492013-02-09 01:29:05 +00005158 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005159
Jim Ingham0161b492013-02-09 01:29:05 +00005160 if (stop_state == eStateStopped)
5161 {
5162 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5163 if (log)
5164 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5165 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5166 num_resumes,
5167 StateAsCString(stop_state),
5168 restarted,
5169 do_resume,
5170 handle_running_event);
5171 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005172
Jim Ingham0161b492013-02-09 01:29:05 +00005173 if (restarted)
5174 {
5175 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5176 // event here. But if I do, the best thing is to Halt and then get out of here.
5177 Halt();
5178 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005179
Jim Ingham35e1bda2012-10-16 21:41:58 +00005180 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5181 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005182 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005183 break;
5184 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005185
Sean Callanana46ec452012-07-11 21:31:24 +00005186 if (log)
5187 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5188 // We need to call the function synchronously, so spin waiting for it to return.
5189 // If we get interrupted while executing, we're going to lose our context, and
5190 // won't be able to gather the result at this point.
5191 // We set the timeout AFTER the resume, since the resume takes some time and we
5192 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005193 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005194 else
5195 {
Sean Callanana46ec452012-07-11 21:31:24 +00005196 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005197 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005198 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005199
Jim Ingham0161b492013-02-09 01:29:05 +00005200 if (before_first_timeout)
5201 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005202 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005203 {
5204 one_thread_timeout = TimeValue::Now();
5205 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005206 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005207 }
Jim Ingham0161b492013-02-09 01:29:05 +00005208 else
5209 {
5210 if (timeout_usec == 0)
5211 timeout_ptr = NULL;
5212 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005213 {
5214 final_timeout = TimeValue::Now();
5215 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005216 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005217 }
Jim Ingham0161b492013-02-09 01:29:05 +00005218 }
5219 }
5220 else
5221 {
5222 if (timeout_usec == 0)
5223 timeout_ptr = NULL;
5224 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005225 {
5226 final_timeout = TimeValue::Now();
5227 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005228 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005229 }
Jim Ingham0161b492013-02-09 01:29:05 +00005230 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005231
Jim Ingham0161b492013-02-09 01:29:05 +00005232 do_resume = true;
5233 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005234
Sean Callanana46ec452012-07-11 21:31:24 +00005235 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005236 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005237
Jim Ingham0f16e732011-02-08 05:20:59 +00005238 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005239 {
Sean Callanana46ec452012-07-11 21:31:24 +00005240 if (timeout_ptr)
5241 {
Matt Kopec676a4872013-02-21 23:55:31 +00005242 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005243 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5244 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005245 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005246 else
Sean Callanana46ec452012-07-11 21:31:24 +00005247 {
5248 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5249 }
5250 }
Jim Ingham35878c42014-04-08 21:33:21 +00005251
5252#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5253 // See comment above...
5254 if (miss_first_event)
5255 {
5256 usleep(1000);
5257 miss_first_event = false;
5258 got_event = false;
5259 }
5260 else
5261#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005262 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005263
Sean Callanana46ec452012-07-11 21:31:24 +00005264 if (got_event)
5265 {
5266 if (event_sp.get())
5267 {
5268 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005269 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005270 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005271 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005272 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005273 errors.Printf ("Execution halted by user interrupt.");
5274 if (log)
5275 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005276 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005277 }
5278 else
5279 {
5280 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5281 if (log)
5282 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005283
Jim Inghamcfc09352012-07-27 23:57:19 +00005284 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005285 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005286 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005287 {
Jim Ingham0161b492013-02-09 01:29:05 +00005288 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005289 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5290 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005291 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005292 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005293 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005294 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005295 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005296 }
5297 else
5298 {
Jim Ingham0161b492013-02-09 01:29:05 +00005299 // If we were restarted, we just need to go back up to fetch another event.
5300 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005301 {
5302 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005303 {
5304 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5305 }
5306 keep_going = true;
5307 do_resume = false;
5308 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005309
Jim Inghamcfc09352012-07-27 23:57:19 +00005310 }
5311 else
5312 {
Jim Ingham0161b492013-02-09 01:29:05 +00005313 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5314 StopReason stop_reason = eStopReasonInvalid;
5315 if (stop_info_sp)
5316 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005317
Jim Ingham0161b492013-02-09 01:29:05 +00005318 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5319 // it is OUR plan that is complete?
5320 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005321 {
5322 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005323 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5324 // Now mark this plan as private so it doesn't get reported as the stop reason
5325 // after this point.
5326 if (thread_plan_sp)
5327 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005328 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005329 }
5330 else
5331 {
Jim Ingham0161b492013-02-09 01:29:05 +00005332 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005333 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005334 {
5335 if (log)
5336 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005337 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005338 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005339 {
5340 event_to_broadcast_sp = event_sp;
5341 }
Jim Ingham0161b492013-02-09 01:29:05 +00005342 }
Jim Ingham184e9812013-01-15 02:47:48 +00005343 else
Jim Ingham0161b492013-02-09 01:29:05 +00005344 {
5345 if (log)
5346 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005347 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005348 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005349 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005350 }
Jim Ingham184e9812013-01-15 02:47:48 +00005351 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005352 }
Sean Callanana46ec452012-07-11 21:31:24 +00005353 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005354 }
5355 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005356
Jim Inghamcfc09352012-07-27 23:57:19 +00005357 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005358 // This shouldn't really happen, but sometimes we do get two running events without an
5359 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005360 do_resume = false;
5361 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005362 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005363 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005364
Jim Inghamcfc09352012-07-27 23:57:19 +00005365 default:
5366 if (log)
5367 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005368
Jim Inghamcfc09352012-07-27 23:57:19 +00005369 if (stop_state == eStateExited)
5370 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005371
Sean Callananbf154da2012-08-08 17:35:10 +00005372 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005373 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005374 break;
5375 }
Sean Callanana46ec452012-07-11 21:31:24 +00005376 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005377
Sean Callanana46ec452012-07-11 21:31:24 +00005378 if (keep_going)
5379 continue;
5380 else
5381 break;
5382 }
5383 else
5384 {
5385 if (log)
5386 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005387 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005388 break;
5389 }
5390 }
5391 else
5392 {
5393 // If we didn't get an event that means we've timed out...
5394 // We will interrupt the process here. Depending on what we were asked to do we will
5395 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005396
Sean Callanana46ec452012-07-11 21:31:24 +00005397 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005398 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005399 {
Jim Ingham0161b492013-02-09 01:29:05 +00005400 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005401 {
5402 if (timeout_usec != 0)
5403 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005404 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005405 "running for %" PRIu32 " usec with all threads enabled.",
5406 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005407 }
5408 else
5409 {
5410 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005411 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005412 }
5413 }
Sean Callanana46ec452012-07-11 21:31:24 +00005414 else
5415 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005416 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005417 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005418 }
5419 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005420 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005421 "abandoning execution.",
5422 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005423 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005424
Jim Ingham0161b492013-02-09 01:29:05 +00005425 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5426 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5427 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5428 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5429 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005430
Jim Ingham0161b492013-02-09 01:29:05 +00005431 bool back_to_top = true;
5432 uint32_t try_halt_again = 0;
5433 bool do_halt = true;
5434 const uint32_t num_retries = 5;
5435 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005436 {
Jim Ingham0161b492013-02-09 01:29:05 +00005437 Error halt_error;
5438 if (do_halt)
5439 {
5440 if (log)
5441 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5442 halt_error = Halt();
5443 }
5444 if (halt_error.Success())
5445 {
5446 if (log)
5447 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005448
Jim Ingham0161b492013-02-09 01:29:05 +00005449 real_timeout = TimeValue::Now();
5450 real_timeout.OffsetWithMicroSeconds(500000);
5451
5452 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005453
Jim Ingham0161b492013-02-09 01:29:05 +00005454 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005455 {
Jim Ingham0161b492013-02-09 01:29:05 +00005456 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5457 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005458 {
Jim Ingham0161b492013-02-09 01:29:05 +00005459 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5460 if (stop_state == lldb::eStateStopped
5461 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5462 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005463 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005464
Jim Ingham0161b492013-02-09 01:29:05 +00005465 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005466 {
Jim Ingham0161b492013-02-09 01:29:05 +00005467 // Between the time we initiated the Halt and the time we delivered it, the process could have
5468 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005469
Jim Ingham0161b492013-02-09 01:29:05 +00005470 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5471 {
5472 if (log)
5473 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5474 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005475 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005476 back_to_top = false;
5477 break;
5478 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005479
Jim Ingham0161b492013-02-09 01:29:05 +00005480 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5481 {
5482 if (log)
5483 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5484 "Exiting wait loop.");
5485 try_halt_again++;
5486 do_halt = false;
5487 continue;
5488 }
Sean Callanana46ec452012-07-11 21:31:24 +00005489
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005490 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005491 {
5492 if (log)
5493 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005494 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005495 back_to_top = false;
5496 break;
5497 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005498
Jim Ingham0161b492013-02-09 01:29:05 +00005499 if (before_first_timeout)
5500 {
5501 // Set all the other threads to run, and return to the top of the loop, which will continue;
5502 before_first_timeout = false;
5503 thread_plan_sp->SetStopOthers (false);
5504 if (log)
5505 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005506
Jim Ingham0161b492013-02-09 01:29:05 +00005507 back_to_top = true;
5508 break;
5509 }
5510 else
5511 {
5512 // Running all threads failed, so return Interrupted.
5513 if (log)
5514 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005515 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005516 back_to_top = false;
5517 break;
5518 }
Sean Callanana46ec452012-07-11 21:31:24 +00005519 }
5520 }
5521 else
Jim Ingham0161b492013-02-09 01:29:05 +00005522 { if (log)
5523 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5524 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005525 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005526 back_to_top = false;
5527 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005528 }
5529 }
Jim Ingham0161b492013-02-09 01:29:05 +00005530 else
5531 {
5532 try_halt_again++;
5533 continue;
5534 }
Sean Callanana46ec452012-07-11 21:31:24 +00005535 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005536
Jim Ingham0161b492013-02-09 01:29:05 +00005537 if (!back_to_top || try_halt_again > num_retries)
5538 break;
5539 else
5540 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005541 }
Sean Callanana46ec452012-07-11 21:31:24 +00005542 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005543
Sean Callanana46ec452012-07-11 21:31:24 +00005544 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5545 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5546 {
5547 StopPrivateStateThread();
5548 Error error;
5549 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005550 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005551 {
5552 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5553 }
5554 m_public_state.SetValueNoLock(old_state);
5555
5556 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005557
Jim Ingham184e9812013-01-15 02:47:48 +00005558 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5559 // could happen:
5560 // 1) The execution successfully completed
5561 // 2) We hit a breakpoint, and ignore_breakpoints was true
5562 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005563 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5564 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005565
Jim Ingham8646d3c2014-05-05 02:47:44 +00005566 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005567 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005568 {
5569 thread_plan_sp->RestoreThreadState();
5570 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005571
Sean Callanana46ec452012-07-11 21:31:24 +00005572 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005573 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005574 {
5575 if (log)
5576 {
5577 StreamString s;
5578 if (event_sp)
5579 event_sp->Dump (&s);
5580 else
5581 {
5582 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5583 }
5584
5585 StreamString ts;
5586
5587 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005588
Sean Callanana46ec452012-07-11 21:31:24 +00005589 do
5590 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005591 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005592 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005593 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005594 break;
5595 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005596 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005597 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005598 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005599 break;
5600 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005601 else
Sean Callanana46ec452012-07-11 21:31:24 +00005602 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005603 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5604
5605 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005606 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005607 event_explanation = "<no event data>";
5608 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005609 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005610
Jim Inghamcfc09352012-07-27 23:57:19 +00005611 Process *process = event_data->GetProcessSP().get();
5612
5613 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005614 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005615 event_explanation = "<no process>";
5616 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005617 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005618
Jim Inghamcfc09352012-07-27 23:57:19 +00005619 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005620
Jim Inghamcfc09352012-07-27 23:57:19 +00005621 uint32_t num_threads = thread_list.GetSize();
5622 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005623
Jim Inghamcfc09352012-07-27 23:57:19 +00005624 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005625
Jim Inghamcfc09352012-07-27 23:57:19 +00005626 for (thread_index = 0;
5627 thread_index < num_threads;
5628 ++thread_index)
5629 {
5630 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005631
Jim Inghamcfc09352012-07-27 23:57:19 +00005632 if (!thread)
5633 {
5634 ts.Printf("<?> ");
5635 continue;
5636 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005637
Daniel Malead01b2952012-11-29 21:49:15 +00005638 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005639 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005640
Jim Inghamcfc09352012-07-27 23:57:19 +00005641 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005642 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005643 else
5644 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005645
Jim Inghamcfc09352012-07-27 23:57:19 +00005646 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5647 if (stop_info_sp)
5648 {
5649 const char *stop_desc = stop_info_sp->GetDescription();
5650 if (stop_desc)
5651 ts.PutCString (stop_desc);
5652 }
5653 ts.Printf(">");
5654 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005655
Jim Inghamcfc09352012-07-27 23:57:19 +00005656 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005657 }
Sean Callanana46ec452012-07-11 21:31:24 +00005658 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005659
Jim Inghamcfc09352012-07-27 23:57:19 +00005660 if (event_explanation)
5661 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005662 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005663 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5664 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005665
Jim Inghame4483cf2013-09-27 01:13:01 +00005666 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005667 {
5668 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005669 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5670 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005671 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5672 thread_plan_sp->SetPrivate (orig_plan_private);
5673 }
5674 else
5675 {
5676 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005677 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5678 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005679 }
5680 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005681 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005682 {
5683 if (log)
5684 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005685
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005686 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005687 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005688 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005689 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005690 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005691 }
5692 else
5693 {
Sean Callanana46ec452012-07-11 21:31:24 +00005694 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005695 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005696 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005697 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005698 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005699 }
5700 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5701 {
5702 if (log)
5703 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005704 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005705 }
5706 else
5707 {
5708 if (log)
5709 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005710 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005711 {
5712 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005713 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005714 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5715 thread_plan_sp->SetPrivate (orig_plan_private);
5716 }
5717 }
5718 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005719
Sean Callanana46ec452012-07-11 21:31:24 +00005720 // Thread we ran the function in may have gone away because we ran the target
5721 // Check that it's still there, and if it is put it back in the context. Also restore the
5722 // frame in the context if it is still present.
5723 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5724 if (thread)
5725 {
5726 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5727 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005728
Sean Callanana46ec452012-07-11 21:31:24 +00005729 // Also restore the current process'es selected frame & thread, since this function calling may
5730 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005731
Sean Callanana46ec452012-07-11 21:31:24 +00005732 if (selected_tid != LLDB_INVALID_THREAD_ID)
5733 {
5734 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5735 {
5736 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005737 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005738 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005739 if (old_frame_sp)
5740 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005741 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005742 }
5743 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005744
Sean Callanana46ec452012-07-11 21:31:24 +00005745 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005746
Sean Callanana46ec452012-07-11 21:31:24 +00005747 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005748 {
Sean Callanana46ec452012-07-11 21:31:24 +00005749 if (log)
5750 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5751 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005752 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005753
Jim Inghamf48169b2010-11-30 02:22:11 +00005754 return return_value;
5755}
5756
5757const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005758Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005759{
5760 const char *result_name;
5761
5762 switch (result)
5763 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005764 case eExpressionCompleted:
5765 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005766 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005767 case eExpressionDiscarded:
5768 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005769 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005770 case eExpressionInterrupted:
5771 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005772 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005773 case eExpressionHitBreakpoint:
5774 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005775 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005776 case eExpressionSetupError:
5777 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005778 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005779 case eExpressionParseError:
5780 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005781 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005782 case eExpressionResultUnavailable:
5783 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005784 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005785 case eExpressionTimedOut:
5786 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005787 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005788 case eExpressionStoppedForDebug:
5789 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005790 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005791 }
5792 return result_name;
5793}
5794
Greg Clayton7260f622011-04-18 08:33:37 +00005795void
5796Process::GetStatus (Stream &strm)
5797{
5798 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005799 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005800 {
5801 if (state == eStateExited)
5802 {
5803 int exit_status = GetExitStatus();
5804 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005805 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005806 GetID(),
5807 exit_status,
5808 exit_status,
5809 exit_description ? exit_description : "");
5810 }
5811 else
5812 {
5813 if (state == eStateConnected)
5814 strm.Printf ("Connected to remote target.\n");
5815 else
Daniel Malead01b2952012-11-29 21:49:15 +00005816 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005817 }
5818 }
5819 else
5820 {
Daniel Malead01b2952012-11-29 21:49:15 +00005821 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005822 }
5823}
5824
5825size_t
5826Process::GetThreadStatus (Stream &strm,
5827 bool only_threads_with_stop_reason,
5828 uint32_t start_frame,
5829 uint32_t num_frames,
5830 uint32_t num_frames_with_source)
5831{
5832 size_t num_thread_infos_dumped = 0;
5833
Jim Ingham4a65fb12014-03-07 11:20:03 +00005834 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5835 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5836 // ID's, and look them up one by one:
5837
5838 uint32_t num_threads;
5839 std::vector<uint32_t> thread_index_array;
5840 //Scope for thread list locker;
5841 {
5842 Mutex::Locker locker (GetThreadList().GetMutex());
5843 ThreadList &curr_thread_list = GetThreadList();
5844 num_threads = curr_thread_list.GetSize();
5845 uint32_t idx;
5846 thread_index_array.resize(num_threads);
5847 for (idx = 0; idx < num_threads; ++idx)
5848 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5849 }
5850
Greg Clayton7260f622011-04-18 08:33:37 +00005851 for (uint32_t i = 0; i < num_threads; i++)
5852 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005853 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5854 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005855 {
5856 if (only_threads_with_stop_reason)
5857 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005858 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005859 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005860 continue;
5861 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005862 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005863 start_frame,
5864 num_frames,
5865 num_frames_with_source);
5866 ++num_thread_infos_dumped;
5867 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005868 else
5869 {
5870 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5871 if (log)
5872 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5873
5874 }
Greg Clayton7260f622011-04-18 08:33:37 +00005875 }
5876 return num_thread_infos_dumped;
5877}
5878
Greg Claytona9f40ad2012-02-22 04:37:26 +00005879void
5880Process::AddInvalidMemoryRegion (const LoadRange &region)
5881{
5882 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5883}
5884
5885bool
5886Process::RemoveInvalidMemoryRange (const LoadRange &region)
5887{
5888 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5889}
5890
Jim Ingham372787f2012-04-07 00:00:41 +00005891void
5892Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5893{
5894 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5895}
5896
5897bool
5898Process::RunPreResumeActions ()
5899{
5900 bool result = true;
5901 while (!m_pre_resume_actions.empty())
5902 {
5903 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5904 m_pre_resume_actions.pop_back();
5905 bool this_result = action.callback (action.baton);
5906 if (result == true) result = this_result;
5907 }
5908 return result;
5909}
5910
5911void
5912Process::ClearPreResumeActions ()
5913{
5914 m_pre_resume_actions.clear();
5915}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005916
Greg Claytonfa559e52012-05-18 02:38:05 +00005917void
5918Process::Flush ()
5919{
5920 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005921 m_extended_thread_list.Flush();
5922 m_extended_thread_stop_id = 0;
5923 m_queue_list.Clear();
5924 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005925}
Greg Clayton90ba8112012-12-05 00:16:59 +00005926
5927void
5928Process::DidExec ()
5929{
Todd Fiala76e0fc92014-08-27 22:58:26 +00005930 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5931 if (log)
5932 log->Printf ("Process::%s()", __FUNCTION__);
5933
Greg Clayton90ba8112012-12-05 00:16:59 +00005934 Target &target = GetTarget();
5935 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005936 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005937 m_dynamic_checkers_ap.reset();
5938 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005939 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005940 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005941 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005942 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005943 m_image_tokens.clear();
5944 m_allocated_memory_cache.Clear();
5945 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005946 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005947 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005948 DoDidExec();
5949 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005950 // Flush the process (threads and all stack frames) after running CompleteAttach()
5951 // in case the dynamic loader loaded things in new locations.
5952 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005953
5954 // After we figure out what was loaded/unloaded in CompleteAttach,
5955 // we need to let the target know so it can do any cleanup it needs to.
5956 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005957}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005958
Jim Ingham1460e4b2014-01-10 23:46:59 +00005959addr_t
5960Process::ResolveIndirectFunction(const Address *address, Error &error)
5961{
5962 if (address == nullptr)
5963 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005964 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005965 return LLDB_INVALID_ADDRESS;
5966 }
5967
5968 addr_t function_addr = LLDB_INVALID_ADDRESS;
5969
5970 addr_t addr = address->GetLoadAddress(&GetTarget());
5971 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5972 if (iter != m_resolved_indirect_addresses.end())
5973 {
5974 function_addr = (*iter).second;
5975 }
5976 else
5977 {
5978 if (!InferiorCall(this, address, function_addr))
5979 {
5980 Symbol *symbol = address->CalculateSymbolContextSymbol();
5981 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5982 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5983 function_addr = LLDB_INVALID_ADDRESS;
5984 }
5985 else
5986 {
5987 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5988 }
5989 }
5990 return function_addr;
5991}
5992
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005993void
5994Process::ModulesDidLoad (ModuleList &module_list)
5995{
5996 SystemRuntime *sys_runtime = GetSystemRuntime();
5997 if (sys_runtime)
5998 {
5999 sys_runtime->ModulesDidLoad (module_list);
6000 }
6001
6002 GetJITLoaders().ModulesDidLoad (module_list);
6003}