blob: 3d44b24073540329e9ce3b56a1969d4936fe12b2 [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
457 case 'A':
458 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
459 break;
460
Greg Clayton982c9762011-11-03 21:22:33 +0000461 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000462 if (option_arg && option_arg[0])
463 launch_info.SetShell (option_arg);
464 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000465 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000466 break;
467
Greg Clayton8b82f082011-04-12 05:54:46 +0000468 case 'v':
469 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
470 break;
471
472 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000473 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000474 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 }
476 return error;
477}
478
479OptionDefinition
480ProcessLaunchCommandOptions::g_option_table[] =
481{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000482{ 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."},
483{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
484{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
485{ 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."},
486{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
487{ 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."},
488{ 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 +0000489
Zachary Turnerd37221d2014-07-09 16:31:49 +0000490{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
491{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
492{ 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 +0000493
Zachary Turnerd37221d2014-07-09 16:31:49 +0000494{ 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 +0000495
Zachary Turnerd37221d2014-07-09 16:31:49 +0000496{ 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 +0000497
Zachary Turnerd37221d2014-07-09 16:31:49 +0000498{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000499};
500
501
502
503bool
504ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000505{
506 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
507 return true;
508 const char *match_name = m_match_info.GetName();
509 if (!match_name)
510 return true;
511
512 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
513}
514
515bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000516ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000517{
518 if (!NameMatches (proc_info.GetName()))
519 return false;
520
521 if (m_match_info.ProcessIDIsValid() &&
522 m_match_info.GetProcessID() != proc_info.GetProcessID())
523 return false;
524
525 if (m_match_info.ParentProcessIDIsValid() &&
526 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
527 return false;
528
Greg Clayton8b82f082011-04-12 05:54:46 +0000529 if (m_match_info.UserIDIsValid () &&
530 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000531 return false;
532
Greg Clayton8b82f082011-04-12 05:54:46 +0000533 if (m_match_info.GroupIDIsValid () &&
534 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000535 return false;
536
537 if (m_match_info.EffectiveUserIDIsValid () &&
538 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
539 return false;
540
541 if (m_match_info.EffectiveGroupIDIsValid () &&
542 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
543 return false;
544
545 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000546 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000547 return false;
548 return true;
549}
550
551bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000552ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000553{
554 if (m_name_match_type != eNameMatchIgnore)
555 return false;
556
557 if (m_match_info.ProcessIDIsValid())
558 return false;
559
560 if (m_match_info.ParentProcessIDIsValid())
561 return false;
562
Greg Clayton8b82f082011-04-12 05:54:46 +0000563 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000564 return false;
565
Greg Clayton8b82f082011-04-12 05:54:46 +0000566 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000567 return false;
568
569 if (m_match_info.EffectiveUserIDIsValid ())
570 return false;
571
572 if (m_match_info.EffectiveGroupIDIsValid ())
573 return false;
574
575 if (m_match_info.GetArchitecture().IsValid())
576 return false;
577
578 if (m_match_all_users)
579 return false;
580
581 return true;
582
583}
584
585void
Greg Clayton8b82f082011-04-12 05:54:46 +0000586ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000587{
588 m_match_info.Clear();
589 m_name_match_type = eNameMatchIgnore;
590 m_match_all_users = false;
591}
Greg Clayton58be07b2011-01-07 06:08:19 +0000592
Greg Claytonc3776bf2012-02-09 06:16:32 +0000593ProcessSP
594Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595{
Greg Clayton949e8222013-01-16 17:29:04 +0000596 static uint32_t g_process_unique_id = 0;
597
Greg Claytonc3776bf2012-02-09 06:16:32 +0000598 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000599 ProcessCreateInstance create_callback = NULL;
600 if (plugin_name)
601 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000602 ConstString const_plugin_name(plugin_name);
603 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604 if (create_callback)
605 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000606 process_sp = create_callback(target, listener, crash_file_path);
607 if (process_sp)
608 {
Greg Clayton949e8222013-01-16 17:29:04 +0000609 if (process_sp->CanDebug(target, true))
610 {
611 process_sp->m_process_unique_id = ++g_process_unique_id;
612 }
613 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000614 process_sp.reset();
615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000616 }
617 }
618 else
619 {
Greg Claytonc982c762010-07-09 20:39:50 +0000620 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000621 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000622 process_sp = create_callback(target, listener, crash_file_path);
623 if (process_sp)
624 {
Greg Clayton949e8222013-01-16 17:29:04 +0000625 if (process_sp->CanDebug(target, false))
626 {
627 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000628 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000629 }
630 else
631 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000632 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000633 }
634 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000635 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636}
637
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000638ConstString &
639Process::GetStaticBroadcasterClass ()
640{
641 static ConstString class_name ("lldb.process");
642 return class_name;
643}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000644
645//----------------------------------------------------------------------
646// Process constructor
647//----------------------------------------------------------------------
648Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000649 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000651 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653 m_public_state (eStateUnloaded),
654 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000655 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
656 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 m_private_state_listener ("lldb.process.internal_state_listener"),
658 m_private_state_control_wait(),
659 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000660 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000661 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000663 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 m_exit_status (-1),
665 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000666 m_thread_mutex (Mutex::eMutexTypeRecursive),
667 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000669 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000670 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000671 m_queue_list (this),
672 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000674 m_image_tokens (),
675 m_listener (listener),
676 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000677 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000678 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000679 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000680 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000681 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000682 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000683 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000684 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000685 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
686 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000687 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000688 m_memory_cache (*this),
689 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000690 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000691 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000692 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000693 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000694 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000695 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000696 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000697 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000698 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000699 m_destroy_in_process (false),
700 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000702 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000703
Greg Clayton5160ce52013-03-27 23:08:40 +0000704 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000706 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000708 SetEventName (eBroadcastBitStateChanged, "state-changed");
709 SetEventName (eBroadcastBitInterrupt, "interrupt");
710 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
711 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000712 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000713
Greg Clayton35a4cc52012-10-29 20:52:08 +0000714 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
715 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
716 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
717
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 listener.StartListeningForEvents (this,
719 eBroadcastBitStateChanged |
720 eBroadcastBitInterrupt |
721 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000722 eBroadcastBitSTDERR |
723 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724
725 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000726 eBroadcastBitStateChanged |
727 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728
729 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
730 eBroadcastInternalStateControlStop |
731 eBroadcastInternalStateControlPause |
732 eBroadcastInternalStateControlResume);
733}
734
735//----------------------------------------------------------------------
736// Destructor
737//----------------------------------------------------------------------
738Process::~Process()
739{
Greg Clayton5160ce52013-03-27 23:08:40 +0000740 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000742 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 StopPrivateStateThread();
744}
745
Greg Clayton67cc0632012-08-22 17:17:09 +0000746const ProcessPropertiesSP &
747Process::GetGlobalProperties()
748{
749 static ProcessPropertiesSP g_settings_sp;
750 if (!g_settings_sp)
751 g_settings_sp.reset (new ProcessProperties (true));
752 return g_settings_sp;
753}
754
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755void
756Process::Finalize()
757{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000758 switch (GetPrivateState())
759 {
760 case eStateConnected:
761 case eStateAttaching:
762 case eStateLaunching:
763 case eStateStopped:
764 case eStateRunning:
765 case eStateStepping:
766 case eStateCrashed:
767 case eStateSuspended:
768 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000769 {
770 // FIXME: This will have to be a process setting:
771 bool keep_stopped = false;
772 Detach(keep_stopped);
773 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000774 else
775 Destroy();
776 break;
777
778 case eStateInvalid:
779 case eStateUnloaded:
780 case eStateDetached:
781 case eStateExited:
782 break;
783 }
784
Greg Clayton1ed54f52011-10-01 00:45:15 +0000785 // Clear our broadcaster before we proceed with destroying
786 Broadcaster::Clear();
787
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788 // Do any cleanup needed prior to being destructed... Subclasses
789 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000790
791 // We need to destroy the loader before the derived Process class gets destroyed
792 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000793 m_dynamic_checkers_ap.reset();
794 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000795 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000796 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000797 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000798 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000799 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000800 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000801 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000802 m_queue_list.Clear();
803 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000804 std::vector<Notifications> empty_notifications;
805 m_notifications.swap(empty_notifications);
806 m_image_tokens.clear();
807 m_memory_cache.Clear();
808 m_allocated_memory_cache.Clear();
809 m_language_runtimes.clear();
810 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000811//#ifdef LLDB_CONFIGURATION_DEBUG
812// StreamFile s(stdout, false);
813// EventSP event_sp;
814// while (m_private_state_listener.GetNextEvent(event_sp))
815// {
816// event_sp->Dump (&s);
817// s.EOL();
818// }
819//#endif
820 // We have to be very careful here as the m_private_state_listener might
821 // contain events that have ProcessSP values in them which can keep this
822 // process around forever. These events need to be cleared out.
823 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000824 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
825 m_public_run_lock.SetStopped();
826 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
827 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000828 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829}
830
831void
832Process::RegisterNotificationCallbacks (const Notifications& callbacks)
833{
834 m_notifications.push_back(callbacks);
835 if (callbacks.initialize != NULL)
836 callbacks.initialize (callbacks.baton, this);
837}
838
839bool
840Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
841{
842 std::vector<Notifications>::iterator pos, end = m_notifications.end();
843 for (pos = m_notifications.begin(); pos != end; ++pos)
844 {
845 if (pos->baton == callbacks.baton &&
846 pos->initialize == callbacks.initialize &&
847 pos->process_state_changed == callbacks.process_state_changed)
848 {
849 m_notifications.erase(pos);
850 return true;
851 }
852 }
853 return false;
854}
855
856void
857Process::SynchronouslyNotifyStateChanged (StateType state)
858{
859 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
860 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
861 {
862 if (notification_pos->process_state_changed)
863 notification_pos->process_state_changed (notification_pos->baton, this, state);
864 }
865}
866
867// FIXME: We need to do some work on events before the general Listener sees them.
868// For instance if we are continuing from a breakpoint, we need to ensure that we do
869// the little "insert real insn, step & stop" trick. But we can't do that when the
870// event is delivered by the broadcaster - since that is done on the thread that is
871// waiting for new events, so if we needed more than one event for our handling, we would
872// stall. So instead we do it when we fetch the event off of the queue.
873//
874
875StateType
876Process::GetNextEvent (EventSP &event_sp)
877{
878 StateType state = eStateInvalid;
879
880 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
881 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
882
883 return state;
884}
885
Todd Fialaa3b89e22014-08-12 14:33:19 +0000886bool
887Process::SyncIOHandler (uint64_t timeout_msec)
888{
889 bool timed_out = false;
890
891 // don't sync (potentially context switch) in case where there is no process IO
892 if (m_process_input_reader)
893 {
894 TimeValue timeout = TimeValue::Now();
895 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
896
897 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
898
899 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
900 if(log)
901 {
902 if(timed_out)
903 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
904 else
905 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
906 }
907
908 // reset sync one-shot so it will be ready for next time
909 m_iohandler_sync.SetValue(false, eBroadcastNever);
910 }
911
912 return !timed_out;
913}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000914
915StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000916Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000917{
Jim Ingham4b536182011-08-09 02:12:22 +0000918 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
919 // We have to actually check each event, and in the case of a stopped event check the restarted flag
920 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000921 if (event_sp_ptr)
922 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000923 StateType state = GetState();
924 // If we are exited or detached, we won't ever get back to any
925 // other valid state...
926 if (state == eStateDetached || state == eStateExited)
927 return state;
928
Daniel Malea9e9919f2013-10-09 16:56:28 +0000929 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
930 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000931 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
932 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000933
934 if (!wait_always &&
935 StateIsStoppedState(state, true) &&
936 StateIsStoppedState(GetPrivateState(), true)) {
937 if (log)
938 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
939 __FUNCTION__);
940 return state;
941 }
942
Jim Ingham4b536182011-08-09 02:12:22 +0000943 while (state != eStateInvalid)
944 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000945 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000946 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000947 if (event_sp_ptr && event_sp)
948 *event_sp_ptr = event_sp;
949
Jim Ingham4b536182011-08-09 02:12:22 +0000950 switch (state)
951 {
952 case eStateCrashed:
953 case eStateDetached:
954 case eStateExited:
955 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000956 // We need to toggle the run lock as this won't get done in
957 // SetPublicState() if the process is hijacked.
958 if (hijack_listener)
959 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000960 return state;
961 case eStateStopped:
962 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
963 continue;
964 else
Greg Clayton44d93782014-01-27 23:43:24 +0000965 {
966 // We need to toggle the run lock as this won't get done in
967 // SetPublicState() if the process is hijacked.
968 if (hijack_listener)
969 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000970 return state;
Greg Clayton44d93782014-01-27 23:43:24 +0000971 }
Jim Ingham4b536182011-08-09 02:12:22 +0000972 default:
973 continue;
974 }
975 }
976 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977}
978
979
980StateType
981Process::WaitForState
982(
983 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +0000984 const StateType *match_states,
985 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986)
987{
988 EventSP event_sp;
989 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000990 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991 while (state != eStateInvalid)
992 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000993 // If we are exited or detached, we won't ever get back to any
994 // other valid state...
995 if (state == eStateDetached || state == eStateExited)
996 return state;
997
Greg Clayton44d93782014-01-27 23:43:24 +0000998 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000999
1000 for (i=0; i<num_match_states; ++i)
1001 {
1002 if (match_states[i] == state)
1003 return state;
1004 }
1005 }
1006 return state;
1007}
1008
Jim Ingham30f9b212010-10-11 23:53:14 +00001009bool
1010Process::HijackProcessEvents (Listener *listener)
1011{
1012 if (listener != NULL)
1013 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001014 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001015 }
1016 else
1017 return false;
1018}
1019
1020void
1021Process::RestoreProcessEvents ()
1022{
1023 RestoreBroadcaster();
1024}
1025
Jim Ingham0f16e732011-02-08 05:20:59 +00001026bool
1027Process::HijackPrivateProcessEvents (Listener *listener)
1028{
1029 if (listener != NULL)
1030 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001031 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001032 }
1033 else
1034 return false;
1035}
1036
1037void
1038Process::RestorePrivateProcessEvents ()
1039{
1040 m_private_state_broadcaster.RestoreBroadcaster();
1041}
1042
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001044Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045{
Greg Clayton5160ce52013-03-27 23:08:40 +00001046 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047
1048 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001049 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1050 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051
Greg Clayton44d93782014-01-27 23:43:24 +00001052 Listener *listener = hijack_listener;
1053 if (listener == NULL)
1054 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001055
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001057 if (listener->WaitForEventForBroadcasterWithType (timeout,
1058 this,
1059 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1060 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001061 {
1062 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1063 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1064 else if (log)
1065 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001067
1068 if (log)
1069 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001070 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 StateAsCString(state));
1072 return state;
1073}
1074
1075Event *
1076Process::PeekAtStateChangedEvents ()
1077{
Greg Clayton5160ce52013-03-27 23:08:40 +00001078 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079
1080 if (log)
1081 log->Printf ("Process::%s...", __FUNCTION__);
1082
1083 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001084 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1085 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 if (log)
1087 {
1088 if (event_ptr)
1089 {
1090 log->Printf ("Process::%s (event_ptr) => %s",
1091 __FUNCTION__,
1092 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1093 }
1094 else
1095 {
1096 log->Printf ("Process::%s no events found",
1097 __FUNCTION__);
1098 }
1099 }
1100 return event_ptr;
1101}
1102
1103StateType
1104Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1105{
Greg Clayton5160ce52013-03-27 23:08:40 +00001106 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107
1108 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001109 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1110 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111
1112 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001113 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1114 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001115 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001116 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001117 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1118 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119
1120 // This is a bit of a hack, but when we wait here we could very well return
1121 // to the command-line, and that could disable the log, which would render the
1122 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001124 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1125 __FUNCTION__, static_cast<const void *>(timeout),
1126 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127 return state;
1128}
1129
1130bool
1131Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1132{
Greg Clayton5160ce52013-03-27 23:08:40 +00001133 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134
1135 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001136 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1137 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138
1139 if (control_only)
1140 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1141 else
1142 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1143}
1144
1145bool
1146Process::IsRunning () const
1147{
1148 return StateIsRunningState (m_public_state.GetValue());
1149}
1150
1151int
1152Process::GetExitStatus ()
1153{
1154 if (m_public_state.GetValue() == eStateExited)
1155 return m_exit_status;
1156 return -1;
1157}
1158
Greg Clayton85851dd2010-12-04 00:10:17 +00001159
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001160const char *
1161Process::GetExitDescription ()
1162{
1163 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1164 return m_exit_string.c_str();
1165 return NULL;
1166}
1167
Greg Clayton6779606a2011-01-22 23:43:18 +00001168bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001169Process::SetExitStatus (int status, const char *cstr)
1170{
Greg Clayton5160ce52013-03-27 23:08:40 +00001171 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001172 if (log)
1173 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1174 status, status,
1175 cstr ? "\"" : "",
1176 cstr ? cstr : "NULL",
1177 cstr ? "\"" : "");
1178
Greg Clayton6779606a2011-01-22 23:43:18 +00001179 // We were already in the exited state
1180 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001181 {
Greg Clayton385d6032011-01-26 23:47:29 +00001182 if (log)
1183 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001184 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001185 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001186
1187 m_exit_status = status;
1188 if (cstr)
1189 m_exit_string = cstr;
1190 else
1191 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192
Greg Clayton6779606a2011-01-22 23:43:18 +00001193 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001194
Greg Clayton6779606a2011-01-22 23:43:18 +00001195 SetPrivateState (eStateExited);
1196 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197}
1198
1199// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001200// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201// found in the global target list (we want to be completely sure that the
1202// lldb_private::Process doesn't go away before we can deliver the signal.
1203bool
Greg Claytone4e45922011-11-16 05:37:56 +00001204Process::SetProcessExitStatus (void *callback_baton,
1205 lldb::pid_t pid,
1206 bool exited,
1207 int signo, // Zero for no signal
1208 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209)
1210{
Greg Clayton5160ce52013-03-27 23:08:40 +00001211 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001212 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001213 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001214 callback_baton,
1215 pid,
1216 exited,
1217 signo,
1218 exit_status);
1219
1220 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001221 {
Greg Clayton66111032010-06-23 01:19:29 +00001222 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001223 if (target_sp)
1224 {
1225 ProcessSP process_sp (target_sp->GetProcessSP());
1226 if (process_sp)
1227 {
1228 const char *signal_cstr = NULL;
1229 if (signo)
1230 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1231
1232 process_sp->SetExitStatus (exit_status, signal_cstr);
1233 }
1234 }
1235 return true;
1236 }
1237 return false;
1238}
1239
1240
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001241void
1242Process::UpdateThreadListIfNeeded ()
1243{
1244 const uint32_t stop_id = GetStopID();
1245 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1246 {
Greg Clayton2637f822011-11-17 01:23:07 +00001247 const StateType state = GetPrivateState();
1248 if (StateIsStoppedState (state, true))
1249 {
1250 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001251 // m_thread_list does have its own mutex, but we need to
1252 // hold onto the mutex between the call to UpdateThreadList(...)
1253 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001254 ThreadList &old_thread_list = m_thread_list;
1255 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001256 ThreadList new_thread_list(this);
1257 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001258 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001259 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001260 {
Jim Ingham09437922013-03-01 20:04:25 +00001261 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1262 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1263 // shutting us down, causing a deadlock.
1264 if (!m_destroy_in_process)
1265 {
1266 OperatingSystem *os = GetOperatingSystem ();
1267 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001268 {
1269 // Clear any old backing threads where memory threads might have been
1270 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001271 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001272 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001273 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001274
1275 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001276 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1277 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1278 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 +00001279 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001280 else
1281 {
1282 // No OS plug-in, the new thread list is the same as the real thread list
1283 new_thread_list = real_thread_list;
1284 }
Jim Ingham09437922013-03-01 20:04:25 +00001285 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001286
1287 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001288 m_thread_list.Update (new_thread_list);
1289 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001290
Jason Molenda4ff13262013-11-20 00:31:38 +00001291 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1292 {
1293 // Clear any extended threads that we may have accumulated previously
1294 m_extended_thread_list.Clear();
1295 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001296
1297 m_queue_list.Clear();
1298 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001299 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001300 }
Greg Clayton2637f822011-11-17 01:23:07 +00001301 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001302 }
1303}
1304
Jason Molenda5e8dce42013-12-13 00:29:16 +00001305void
1306Process::UpdateQueueListIfNeeded ()
1307{
1308 if (m_system_runtime_ap.get())
1309 {
1310 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1311 {
1312 const StateType state = GetPrivateState();
1313 if (StateIsStoppedState (state, true))
1314 {
1315 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1316 m_queue_list_stop_id = GetLastNaturalStopID();
1317 }
1318 }
1319 }
1320}
1321
Greg Claytona4d87472013-01-18 23:41:08 +00001322ThreadSP
1323Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1324{
1325 OperatingSystem *os = GetOperatingSystem ();
1326 if (os)
1327 return os->CreateThread(tid, context);
1328 return ThreadSP();
1329}
1330
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001331uint32_t
1332Process::GetNextThreadIndexID (uint64_t thread_id)
1333{
1334 return AssignIndexIDToThread(thread_id);
1335}
1336
1337bool
1338Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1339{
1340 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1341 if (iterator == m_thread_id_to_index_id_map.end())
1342 {
1343 return false;
1344 }
1345 else
1346 {
1347 return true;
1348 }
1349}
1350
1351uint32_t
1352Process::AssignIndexIDToThread(uint64_t thread_id)
1353{
1354 uint32_t result = 0;
1355 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1356 if (iterator == m_thread_id_to_index_id_map.end())
1357 {
1358 result = ++m_thread_index_id;
1359 m_thread_id_to_index_id_map[thread_id] = result;
1360 }
1361 else
1362 {
1363 result = iterator->second;
1364 }
1365
1366 return result;
1367}
1368
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001369StateType
1370Process::GetState()
1371{
1372 // If any other threads access this we will need a mutex for it
1373 return m_public_state.GetValue ();
1374}
1375
1376void
Jim Ingham221d51c2013-05-08 00:35:16 +00001377Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378{
Greg Clayton5160ce52013-03-27 23:08:40 +00001379 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001381 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001382 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001384
1385 // On the transition from Run to Stopped, we unlock the writer end of the
1386 // run lock. The lock gets locked in Resume, which is the public API
1387 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001388 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1389 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001390 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001391 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001392 if (log)
1393 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001394 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001395 }
1396 else
1397 {
1398 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1399 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001400 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001401 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001402 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001403 {
1404 if (log)
1405 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001406 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001407 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001408 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001409 }
1410 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411}
1412
Jim Ingham3b8285d2012-04-19 01:40:33 +00001413Error
1414Process::Resume ()
1415{
Greg Clayton5160ce52013-03-27 23:08:40 +00001416 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001417 if (log)
1418 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001419 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001420 {
1421 Error error("Resume request failed - process still running.");
1422 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001423 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001424 return error;
1425 }
1426 return PrivateResume();
1427}
1428
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001429StateType
1430Process::GetPrivateState ()
1431{
1432 return m_private_state.GetValue();
1433}
1434
1435void
1436Process::SetPrivateState (StateType new_state)
1437{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001438 if (m_finalize_called)
1439 return;
1440
Greg Clayton5160ce52013-03-27 23:08:40 +00001441 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001442 bool state_changed = false;
1443
1444 if (log)
1445 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1446
Andrew Kaylor29d65742013-05-10 17:19:04 +00001447 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448 Mutex::Locker locker(m_private_state.GetMutex());
1449
1450 const StateType old_state = m_private_state.GetValueNoLock ();
1451 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001452
Greg Claytonaa49c832013-05-03 22:25:56 +00001453 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1454 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1455 if (old_state_is_stopped != new_state_is_stopped)
1456 {
1457 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001458 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001459 else
Ed Maste64fad602013-07-29 20:58:06 +00001460 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001461 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001462
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001463 if (state_changed)
1464 {
1465 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001466 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001468 // Note, this currently assumes that all threads in the list
1469 // stop when the process stops. In the future we will want to
1470 // support a debugging model where some threads continue to run
1471 // while others are stopped. When that happens we will either need
1472 // a way for the thread list to identify which threads are stopping
1473 // or create a special thread list containing only threads which
1474 // actually stopped.
1475 //
1476 // The process plugin is responsible for managing the actual
1477 // behavior of the threads and should have stopped any threads
1478 // that are going to stop before we get here.
1479 m_thread_list.DidStop();
1480
Jim Ingham4b536182011-08-09 02:12:22 +00001481 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001482 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001483 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001484 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485 }
1486 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001487 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1488 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1489 else
1490 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001491 }
1492 else
1493 {
1494 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001495 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496 }
1497}
1498
Jim Ingham0faa43f2011-11-08 03:00:11 +00001499void
1500Process::SetRunningUserExpression (bool on)
1501{
1502 m_mod_id.SetRunningUserExpression (on);
1503}
1504
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505addr_t
1506Process::GetImageInfoAddress()
1507{
1508 return LLDB_INVALID_ADDRESS;
1509}
1510
Greg Clayton8f343b02010-11-04 01:54:29 +00001511//----------------------------------------------------------------------
1512// LoadImage
1513//
1514// This function provides a default implementation that works for most
1515// unix variants. Any Process subclasses that need to do shared library
1516// loading differently should override LoadImage and UnloadImage and
1517// do what is needed.
1518//----------------------------------------------------------------------
1519uint32_t
1520Process::LoadImage (const FileSpec &image_spec, Error &error)
1521{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001522 char path[PATH_MAX];
1523 image_spec.GetPath(path, sizeof(path));
1524
Greg Clayton8f343b02010-11-04 01:54:29 +00001525 DynamicLoader *loader = GetDynamicLoader();
1526 if (loader)
1527 {
1528 error = loader->CanLoadImage();
1529 if (error.Fail())
1530 return LLDB_INVALID_IMAGE_TOKEN;
1531 }
1532
1533 if (error.Success())
1534 {
1535 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001536
1537 if (thread_sp)
1538 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001539 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001540
1541 if (frame_sp)
1542 {
1543 ExecutionContext exe_ctx;
1544 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001545 EvaluateExpressionOptions expr_options;
1546 expr_options.SetUnwindOnError(true);
1547 expr_options.SetIgnoreBreakpoints(true);
1548 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001549 expr_options.SetResultIsInternal(true);
1550
Greg Clayton8f343b02010-11-04 01:54:29 +00001551 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001552 expr.Printf(R"(
1553 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1554 the_result.image_ptr = dlopen ("%s", 2);
1555 if (the_result.image_ptr == (void *) 0x0)
1556 {
1557 the_result.error_str = dlerror();
1558 }
1559 else
1560 {
1561 the_result.error_str = (const char *) 0x0;
1562 }
1563 the_result;
1564 )",
1565 path);
1566 const char *prefix = R"(
1567 extern "C" void* dlopen (const char *path, int mode);
1568 extern "C" const char *dlerror (void);
1569 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001570 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001571 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001572 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001573 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001574 expr.GetData(),
1575 prefix,
1576 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001577 expr_error);
1578 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001579 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001580 error = result_valobj_sp->GetError();
1581 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001582 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001583 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001584 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1585 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001586 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001587 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1588 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1589 {
1590 uint32_t image_token = m_image_tokens.size();
1591 m_image_tokens.push_back (image_ptr);
1592 return image_token;
1593 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001594 else if (image_ptr == 0)
1595 {
Jim Ingham6971b862014-07-19 00:37:06 +00001596 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1597 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001598 {
Jim Ingham6971b862014-07-19 00:37:06 +00001599 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001600 {
Jim Inghamcf973792014-07-17 21:53:48 +00001601 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001602 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001603 if (error.Success() && num_chars > 0)
1604 {
1605 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001606 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001607 }
1608 }
1609 }
1610 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001611 }
1612 }
1613 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001614 else
1615 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001616 }
1617 }
1618 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001619 if (!error.AsCString())
1620 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001621 return LLDB_INVALID_IMAGE_TOKEN;
1622}
1623
1624//----------------------------------------------------------------------
1625// UnloadImage
1626//
1627// This function provides a default implementation that works for most
1628// unix variants. Any Process subclasses that need to do shared library
1629// loading differently should override LoadImage and UnloadImage and
1630// do what is needed.
1631//----------------------------------------------------------------------
1632Error
1633Process::UnloadImage (uint32_t image_token)
1634{
1635 Error error;
1636 if (image_token < m_image_tokens.size())
1637 {
1638 const addr_t image_addr = m_image_tokens[image_token];
1639 if (image_addr == LLDB_INVALID_ADDRESS)
1640 {
1641 error.SetErrorString("image already unloaded");
1642 }
1643 else
1644 {
1645 DynamicLoader *loader = GetDynamicLoader();
1646 if (loader)
1647 error = loader->CanLoadImage();
1648
1649 if (error.Success())
1650 {
1651 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001652
1653 if (thread_sp)
1654 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001655 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001656
1657 if (frame_sp)
1658 {
1659 ExecutionContext exe_ctx;
1660 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001661 EvaluateExpressionOptions expr_options;
1662 expr_options.SetUnwindOnError(true);
1663 expr_options.SetIgnoreBreakpoints(true);
1664 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001665 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001666 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001667 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001668 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001669 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001670 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001671 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001672 expr.GetData(),
1673 prefix,
1674 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001675 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001676 if (result_valobj_sp->GetError().Success())
1677 {
1678 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001679 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001680 {
1681 if (scalar.UInt(1))
1682 {
1683 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1684 }
1685 else
1686 {
1687 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1688 }
1689 }
1690 }
1691 else
1692 {
1693 error = result_valobj_sp->GetError();
1694 }
1695 }
1696 }
1697 }
1698 }
1699 }
1700 else
1701 {
1702 error.SetErrorString("invalid image token");
1703 }
1704 return error;
1705}
1706
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001707const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001708Process::GetABI()
1709{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001710 if (!m_abi_sp)
1711 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1712 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713}
1714
Jim Ingham22777012010-09-23 02:01:19 +00001715LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001716Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001717{
1718 LanguageRuntimeCollection::iterator pos;
1719 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001720 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001721 {
Jim Inghamab175242012-03-10 00:22:19 +00001722 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001723
Jim Inghamab175242012-03-10 00:22:19 +00001724 m_language_runtimes[language] = runtime_sp;
1725 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001726 }
1727 else
1728 return (*pos).second.get();
1729}
1730
1731CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001732Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001733{
Jim Inghamab175242012-03-10 00:22:19 +00001734 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001735 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1736 return static_cast<CPPLanguageRuntime *> (runtime);
1737 return NULL;
1738}
1739
1740ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001741Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001742{
Jim Inghamab175242012-03-10 00:22:19 +00001743 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001744 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1745 return static_cast<ObjCLanguageRuntime *> (runtime);
1746 return NULL;
1747}
1748
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001749bool
1750Process::IsPossibleDynamicValue (ValueObject& in_value)
1751{
1752 if (in_value.IsDynamic())
1753 return false;
1754 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1755
1756 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1757 {
1758 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1759 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1760 }
1761
1762 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1763 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1764 return true;
1765
1766 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1767 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1768}
1769
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001770BreakpointSiteList &
1771Process::GetBreakpointSiteList()
1772{
1773 return m_breakpoint_site_list;
1774}
1775
1776const BreakpointSiteList &
1777Process::GetBreakpointSiteList() const
1778{
1779 return m_breakpoint_site_list;
1780}
1781
1782
1783void
1784Process::DisableAllBreakpointSites ()
1785{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001786 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1787// bp_site->SetEnabled(true);
1788 DisableBreakpointSite(bp_site);
1789 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790}
1791
1792Error
1793Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1794{
1795 Error error (DisableBreakpointSiteByID (break_id));
1796
1797 if (error.Success())
1798 m_breakpoint_site_list.Remove(break_id);
1799
1800 return error;
1801}
1802
1803Error
1804Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1805{
1806 Error error;
1807 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1808 if (bp_site_sp)
1809 {
1810 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001811 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 }
1813 else
1814 {
Daniel Malead01b2952012-11-29 21:49:15 +00001815 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816 }
1817
1818 return error;
1819}
1820
1821Error
1822Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1823{
1824 Error error;
1825 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1826 if (bp_site_sp)
1827 {
1828 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001829 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 }
1831 else
1832 {
Daniel Malead01b2952012-11-29 21:49:15 +00001833 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834 }
1835 return error;
1836}
1837
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001838lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001839Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001840{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001841 addr_t load_addr = LLDB_INVALID_ADDRESS;
1842
1843 bool show_error = true;
1844 switch (GetState())
1845 {
1846 case eStateInvalid:
1847 case eStateUnloaded:
1848 case eStateConnected:
1849 case eStateAttaching:
1850 case eStateLaunching:
1851 case eStateDetached:
1852 case eStateExited:
1853 show_error = false;
1854 break;
1855
1856 case eStateStopped:
1857 case eStateRunning:
1858 case eStateStepping:
1859 case eStateCrashed:
1860 case eStateSuspended:
1861 show_error = IsAlive();
1862 break;
1863 }
1864
1865 // Reset the IsIndirect flag here, in case the location changes from
1866 // pointing to a indirect symbol to a regular symbol.
1867 owner->SetIsIndirect (false);
1868
1869 if (owner->ShouldResolveIndirectFunctions())
1870 {
1871 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1872 if (symbol && symbol->IsIndirect())
1873 {
1874 Error error;
1875 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1876 if (!error.Success() && show_error)
1877 {
Greg Clayton44d93782014-01-27 23:43:24 +00001878 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1879 symbol->GetAddress().GetLoadAddress(&m_target),
1880 owner->GetBreakpoint().GetID(),
1881 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001882 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001883 return LLDB_INVALID_BREAK_ID;
1884 }
1885 Address resolved_address(load_addr);
1886 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1887 owner->SetIsIndirect(true);
1888 }
1889 else
1890 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1891 }
1892 else
1893 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1894
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001895 if (load_addr != LLDB_INVALID_ADDRESS)
1896 {
1897 BreakpointSiteSP bp_site_sp;
1898
1899 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1900 // create a new breakpoint site and add it.
1901
1902 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1903
1904 if (bp_site_sp)
1905 {
1906 bp_site_sp->AddOwner (owner);
1907 owner->SetBreakpointSite (bp_site_sp);
1908 return bp_site_sp->GetID();
1909 }
1910 else
1911 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001912 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001913 if (bp_site_sp)
1914 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001915 Error error = EnableBreakpointSite (bp_site_sp.get());
1916 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001917 {
1918 owner->SetBreakpointSite (bp_site_sp);
1919 return m_breakpoint_site_list.Add (bp_site_sp);
1920 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001921 else
1922 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001923 if (show_error)
1924 {
1925 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001926 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1927 load_addr,
1928 owner->GetBreakpoint().GetID(),
1929 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001930 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001931 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001932 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001933 }
1934 }
1935 }
1936 // We failed to enable the breakpoint
1937 return LLDB_INVALID_BREAK_ID;
1938
1939}
1940
1941void
1942Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1943{
1944 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1945 if (num_owners == 0)
1946 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001947 // Don't try to disable the site if we don't have a live process anymore.
1948 if (IsAlive())
1949 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1951 }
1952}
1953
1954
1955size_t
1956Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1957{
1958 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001959 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960
Jim Ingham20c77192011-06-29 19:42:28 +00001961 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001962 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001963 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1964 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001965 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001966 addr_t intersect_addr;
1967 size_t intersect_size;
1968 size_t opcode_offset;
1969 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001970 {
1971 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1972 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00001973 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001974 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00001975 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001976 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00001978 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979 }
1980 return bytes_removed;
1981}
1982
1983
Greg Claytonded470d2011-03-19 01:12:21 +00001984
1985size_t
1986Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1987{
1988 PlatformSP platform_sp (m_target.GetPlatform());
1989 if (platform_sp)
1990 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1991 return 0;
1992}
1993
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001994Error
1995Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1996{
1997 Error error;
1998 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00001999 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000 const addr_t bp_addr = bp_site->GetLoadAddress();
2001 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002002 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003 if (bp_site->IsEnabled())
2004 {
2005 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002006 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 +00002007 return error;
2008 }
2009
2010 if (bp_addr == LLDB_INVALID_ADDRESS)
2011 {
2012 error.SetErrorString("BreakpointSite contains an invalid load address.");
2013 return error;
2014 }
2015 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2016 // trap for the breakpoint site
2017 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2018
2019 if (bp_opcode_size == 0)
2020 {
Daniel Malead01b2952012-11-29 21:49:15 +00002021 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002022 }
2023 else
2024 {
2025 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2026
2027 if (bp_opcode_bytes == NULL)
2028 {
2029 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2030 return error;
2031 }
2032
2033 // Save the original opcode by reading it
2034 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2035 {
2036 // Write a software breakpoint in place of the original opcode
2037 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2038 {
2039 uint8_t verify_bp_opcode_bytes[64];
2040 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2041 {
2042 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2043 {
2044 bp_site->SetEnabled(true);
2045 bp_site->SetType (BreakpointSite::eSoftware);
2046 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002047 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048 bp_site->GetID(),
2049 (uint64_t)bp_addr);
2050 }
2051 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002052 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053 }
2054 else
2055 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2056 }
2057 else
2058 error.SetErrorString("Unable to write breakpoint trap to memory.");
2059 }
2060 else
2061 error.SetErrorString("Unable to read memory at breakpoint address.");
2062 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002063 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002064 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002065 bp_site->GetID(),
2066 (uint64_t)bp_addr,
2067 error.AsCString());
2068 return error;
2069}
2070
2071Error
2072Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2073{
2074 Error error;
2075 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002076 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002077 addr_t bp_addr = bp_site->GetLoadAddress();
2078 lldb::user_id_t breakID = bp_site->GetID();
2079 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002080 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081
2082 if (bp_site->IsHardware())
2083 {
2084 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2085 }
2086 else if (bp_site->IsEnabled())
2087 {
2088 const size_t break_op_size = bp_site->GetByteSize();
2089 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2090 if (break_op_size > 0)
2091 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002092 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002093 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002094 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095 bool break_op_found = false;
2096
2097 // Read the breakpoint opcode
2098 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2099 {
2100 bool verify = false;
2101 // Make sure we have the a breakpoint opcode exists at this address
2102 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2103 {
2104 break_op_found = true;
2105 // We found a valid breakpoint opcode at this address, now restore
2106 // the saved opcode.
2107 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2108 {
2109 verify = true;
2110 }
2111 else
2112 error.SetErrorString("Memory write failed when restoring original opcode.");
2113 }
2114 else
2115 {
2116 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2117 // Set verify to true and so we can check if the original opcode has already been restored
2118 verify = true;
2119 }
2120
2121 if (verify)
2122 {
Greg Claytonc982c762010-07-09 20:39:50 +00002123 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002124 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 // Verify that our original opcode made it back to the inferior
2126 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2127 {
2128 // compare the memory we just read with the original opcode
2129 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2130 {
2131 // SUCCESS
2132 bp_site->SetEnabled(false);
2133 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002134 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 +00002135 return error;
2136 }
2137 else
2138 {
2139 if (break_op_found)
2140 error.SetErrorString("Failed to restore original opcode.");
2141 }
2142 }
2143 else
2144 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2145 }
2146 }
2147 else
2148 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2149 }
2150 }
2151 else
2152 {
2153 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002154 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 +00002155 return error;
2156 }
2157
2158 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002159 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002160 bp_site->GetID(),
2161 (uint64_t)bp_addr,
2162 error.AsCString());
2163 return error;
2164
2165}
2166
Greg Clayton58be07b2011-01-07 06:08:19 +00002167// Uncomment to verify memory caching works after making changes to caching code
2168//#define VERIFY_MEMORY_READS
2169
Sean Callanan64c0cf22012-06-07 22:26:42 +00002170size_t
2171Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2172{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002173 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002174 if (!GetDisableMemoryCache())
2175 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002176#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002177 // Memory caching is enabled, with debug verification
2178
2179 if (buf && size)
2180 {
2181 // Uncomment the line below to make sure memory caching is working.
2182 // I ran this through the test suite and got no assertions, so I am
2183 // pretty confident this is working well. If any changes are made to
2184 // memory caching, uncomment the line below and test your changes!
2185
2186 // Verify all memory reads by using the cache first, then redundantly
2187 // reading the same memory from the inferior and comparing to make sure
2188 // everything is exactly the same.
2189 std::string verify_buf (size, '\0');
2190 assert (verify_buf.size() == size);
2191 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2192 Error verify_error;
2193 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2194 assert (cache_bytes_read == verify_bytes_read);
2195 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2196 assert (verify_error.Success() == error.Success());
2197 return cache_bytes_read;
2198 }
2199 return 0;
2200#else // !defined(VERIFY_MEMORY_READS)
2201 // Memory caching is enabled, without debug verification
2202
2203 return m_memory_cache.Read (addr, buf, size, error);
2204#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002205 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002206 else
2207 {
2208 // Memory caching is disabled
2209
2210 return ReadMemoryFromInferior (addr, buf, size, error);
2211 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002212}
Greg Clayton58be07b2011-01-07 06:08:19 +00002213
Greg Clayton4c82d422012-05-18 23:20:01 +00002214size_t
2215Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2216{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002217 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002218 out_str.clear();
2219 addr_t curr_addr = addr;
2220 while (1)
2221 {
2222 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2223 if (length == 0)
2224 break;
2225 out_str.append(buf, length);
2226 // If we got "length - 1" bytes, we didn't get the whole C string, we
2227 // need to read some more characters
2228 if (length == sizeof(buf) - 1)
2229 curr_addr += length;
2230 else
2231 break;
2232 }
2233 return out_str.size();
2234}
2235
Greg Clayton58be07b2011-01-07 06:08:19 +00002236
2237size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002238Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2239 size_t type_width)
2240{
2241 size_t total_bytes_read = 0;
2242 if (dst && max_bytes && type_width && max_bytes >= type_width)
2243 {
2244 // Ensure a null terminator independent of the number of bytes that is read.
2245 memset (dst, 0, max_bytes);
2246 size_t bytes_left = max_bytes - type_width;
2247
2248 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2249 assert(sizeof(terminator) >= type_width &&
2250 "Attempting to validate a string with more than 4 bytes per character!");
2251
2252 addr_t curr_addr = addr;
2253 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2254 char *curr_dst = dst;
2255
2256 error.Clear();
2257 while (bytes_left > 0 && error.Success())
2258 {
2259 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2260 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2261 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2262
2263 if (bytes_read == 0)
2264 break;
2265
2266 // Search for a null terminator of correct size and alignment in bytes_read
2267 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2268 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2269 if (::strncmp(&dst[i], terminator, type_width) == 0)
2270 {
2271 error.Clear();
2272 return i;
2273 }
2274
2275 total_bytes_read += bytes_read;
2276 curr_dst += bytes_read;
2277 curr_addr += bytes_read;
2278 bytes_left -= bytes_read;
2279 }
2280 }
2281 else
2282 {
2283 if (max_bytes)
2284 error.SetErrorString("invalid arguments");
2285 }
2286 return total_bytes_read;
2287}
2288
2289// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2290// null terminators.
2291size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002292Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002293{
2294 size_t total_cstr_len = 0;
2295 if (dst && dst_max_len)
2296 {
Greg Claytone91b7952011-12-15 03:14:23 +00002297 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002298 // NULL out everything just to be safe
2299 memset (dst, 0, dst_max_len);
2300 Error error;
2301 addr_t curr_addr = addr;
2302 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2303 size_t bytes_left = dst_max_len - 1;
2304 char *curr_dst = dst;
2305
2306 while (bytes_left > 0)
2307 {
2308 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2309 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2310 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2311
2312 if (bytes_read == 0)
2313 {
Greg Claytone91b7952011-12-15 03:14:23 +00002314 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002315 dst[total_cstr_len] = '\0';
2316 break;
2317 }
2318 const size_t len = strlen(curr_dst);
2319
2320 total_cstr_len += len;
2321
2322 if (len < bytes_to_read)
2323 break;
2324
2325 curr_dst += bytes_read;
2326 curr_addr += bytes_read;
2327 bytes_left -= bytes_read;
2328 }
2329 }
Greg Claytone91b7952011-12-15 03:14:23 +00002330 else
2331 {
2332 if (dst == NULL)
2333 result_error.SetErrorString("invalid arguments");
2334 else
2335 result_error.Clear();
2336 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002337 return total_cstr_len;
2338}
2339
2340size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002341Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2342{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002343 if (buf == NULL || size == 0)
2344 return 0;
2345
2346 size_t bytes_read = 0;
2347 uint8_t *bytes = (uint8_t *)buf;
2348
2349 while (bytes_read < size)
2350 {
2351 const size_t curr_size = size - bytes_read;
2352 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2353 bytes + bytes_read,
2354 curr_size,
2355 error);
2356 bytes_read += curr_bytes_read;
2357 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2358 break;
2359 }
2360
2361 // Replace any software breakpoint opcodes that fall into this range back
2362 // into "buf" before we return
2363 if (bytes_read > 0)
2364 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2365 return bytes_read;
2366}
2367
Greg Clayton58a4c462010-12-16 20:01:20 +00002368uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002369Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002370{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002371 Scalar scalar;
2372 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2373 return scalar.ULongLong(fail_value);
2374 return fail_value;
2375}
2376
2377addr_t
2378Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2379{
2380 Scalar scalar;
2381 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2382 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2383 return LLDB_INVALID_ADDRESS;
2384}
2385
2386
2387bool
2388Process::WritePointerToMemory (lldb::addr_t vm_addr,
2389 lldb::addr_t ptr_value,
2390 Error &error)
2391{
2392 Scalar scalar;
2393 const uint32_t addr_byte_size = GetAddressByteSize();
2394 if (addr_byte_size <= 4)
2395 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002396 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002397 scalar = ptr_value;
2398 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002399}
2400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401size_t
2402Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2403{
2404 size_t bytes_written = 0;
2405 const uint8_t *bytes = (const uint8_t *)buf;
2406
2407 while (bytes_written < size)
2408 {
2409 const size_t curr_size = size - bytes_written;
2410 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2411 bytes + bytes_written,
2412 curr_size,
2413 error);
2414 bytes_written += curr_bytes_written;
2415 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2416 break;
2417 }
2418 return bytes_written;
2419}
2420
2421size_t
2422Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2423{
Greg Clayton58be07b2011-01-07 06:08:19 +00002424#if defined (ENABLE_MEMORY_CACHING)
2425 m_memory_cache.Flush (addr, size);
2426#endif
2427
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 if (buf == NULL || size == 0)
2429 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002430
Jim Ingham4b536182011-08-09 02:12:22 +00002431 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002432
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 // We need to write any data that would go where any current software traps
2434 // (enabled software breakpoints) any software traps (breakpoints) that we
2435 // may have placed in our tasks memory.
2436
Greg Claytond8cf1a12013-06-12 00:46:38 +00002437 BreakpointSiteList bp_sites_in_range;
2438
2439 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002441 // No breakpoint sites overlap
2442 if (bp_sites_in_range.IsEmpty())
2443 return WriteMemoryPrivate (addr, buf, size, error);
2444 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002445 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002446 const uint8_t *ubuf = (const uint8_t *)buf;
2447 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448
Greg Claytond8cf1a12013-06-12 00:46:38 +00002449 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2450
2451 if (error.Success())
2452 {
2453 addr_t intersect_addr;
2454 size_t intersect_size;
2455 size_t opcode_offset;
2456 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2457 assert(intersects);
2458 assert(addr <= intersect_addr && intersect_addr < addr + size);
2459 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2460 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2461
2462 // Check for bytes before this breakpoint
2463 const addr_t curr_addr = addr + bytes_written;
2464 if (intersect_addr > curr_addr)
2465 {
2466 // There are some bytes before this breakpoint that we need to
2467 // just write to memory
2468 size_t curr_size = intersect_addr - curr_addr;
2469 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2470 ubuf + bytes_written,
2471 curr_size,
2472 error);
2473 bytes_written += curr_bytes_written;
2474 if (curr_bytes_written != curr_size)
2475 {
2476 // We weren't able to write all of the requested bytes, we
2477 // are done looping and will return the number of bytes that
2478 // we have written so far.
2479 if (error.Success())
2480 error.SetErrorToGenericError();
2481 }
2482 }
2483 // Now write any bytes that would cover up any software breakpoints
2484 // directly into the breakpoint opcode buffer
2485 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2486 bytes_written += intersect_size;
2487 }
2488 });
2489
2490 if (bytes_written < size)
2491 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2492 ubuf + bytes_written,
2493 size - bytes_written,
2494 error);
2495 }
2496 }
2497 else
2498 {
2499 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 }
2501
2502 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002503 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002504}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002505
2506size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002507Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002508{
2509 if (byte_size == UINT32_MAX)
2510 byte_size = scalar.GetByteSize();
2511 if (byte_size > 0)
2512 {
2513 uint8_t buf[32];
2514 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2515 if (mem_size > 0)
2516 return WriteMemory(addr, buf, mem_size, error);
2517 else
2518 error.SetErrorString ("failed to get scalar as memory data");
2519 }
2520 else
2521 {
2522 error.SetErrorString ("invalid scalar value");
2523 }
2524 return 0;
2525}
2526
2527size_t
2528Process::ReadScalarIntegerFromMemory (addr_t addr,
2529 uint32_t byte_size,
2530 bool is_signed,
2531 Scalar &scalar,
2532 Error &error)
2533{
Greg Clayton7060f892013-05-01 23:41:30 +00002534 uint64_t uval = 0;
2535 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002536 {
Greg Clayton7060f892013-05-01 23:41:30 +00002537 error.SetErrorString ("byte size is zero");
2538 }
2539 else if (byte_size & (byte_size - 1))
2540 {
2541 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2542 }
2543 else if (byte_size <= sizeof(uval))
2544 {
2545 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002546 if (bytes_read == byte_size)
2547 {
2548 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002549 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002550 if (byte_size <= 4)
2551 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002552 else
Greg Clayton7060f892013-05-01 23:41:30 +00002553 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002554 if (is_signed)
2555 scalar.SignExtend(byte_size * 8);
2556 return bytes_read;
2557 }
2558 }
2559 else
2560 {
2561 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2562 }
2563 return 0;
2564}
2565
Greg Claytond495c532011-05-17 03:37:42 +00002566#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002567addr_t
2568Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2569{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002570 if (GetPrivateState() != eStateStopped)
2571 return LLDB_INVALID_ADDRESS;
2572
Greg Claytond495c532011-05-17 03:37:42 +00002573#if defined (USE_ALLOCATE_MEMORY_CACHE)
2574 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2575#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002576 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002577 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002578 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002579 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 +00002580 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002581 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002582 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002583 m_mod_id.GetStopID(),
2584 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002585 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002586#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002587}
2588
Sean Callanan90539452011-09-20 23:01:51 +00002589bool
2590Process::CanJIT ()
2591{
Sean Callanana7b443a2012-02-14 22:50:38 +00002592 if (m_can_jit == eCanJITDontKnow)
2593 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002594 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002595 Error err;
2596
2597 uint64_t allocated_memory = AllocateMemory(8,
2598 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2599 err);
2600
2601 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002602 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002603 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002604 if (log)
2605 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2606 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002607 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002608 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002609 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002610 if (log)
2611 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2612 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002613
2614 DeallocateMemory (allocated_memory);
2615 }
2616
Sean Callanan90539452011-09-20 23:01:51 +00002617 return m_can_jit == eCanJITYes;
2618}
2619
2620void
2621Process::SetCanJIT (bool can_jit)
2622{
2623 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2624}
2625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626Error
2627Process::DeallocateMemory (addr_t ptr)
2628{
Greg Claytond495c532011-05-17 03:37:42 +00002629 Error error;
2630#if defined (USE_ALLOCATE_MEMORY_CACHE)
2631 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2632 {
Daniel Malead01b2952012-11-29 21:49:15 +00002633 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002634 }
2635#else
2636 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002637
Greg Clayton5160ce52013-03-27 23:08:40 +00002638 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002639 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002640 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 +00002641 ptr,
2642 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002643 m_mod_id.GetStopID(),
2644 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002645#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002646 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647}
2648
Han Ming Ongc811d382012-11-17 00:33:14 +00002649
Greg Claytonc9660542012-02-05 02:38:54 +00002650ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002651Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002652 lldb::addr_t header_addr,
2653 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002654{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002655 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002656 if (module_sp)
2657 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002658 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002659 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002660 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002661 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002662 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002663 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002664}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002665
2666Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002667Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002668{
2669 Error error;
2670 error.SetErrorString("watchpoints are not supported");
2671 return error;
2672}
2673
2674Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002675Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002676{
2677 Error error;
2678 error.SetErrorString("watchpoints are not supported");
2679 return error;
2680}
2681
2682StateType
2683Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2684{
2685 StateType state;
2686 // Now wait for the process to launch and return control to us, and then
2687 // call DidLaunch:
2688 while (1)
2689 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002690 event_sp.reset();
2691 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2692
Greg Clayton2637f822011-11-17 01:23:07 +00002693 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002695
2696 // If state is invalid, then we timed out
2697 if (state == eStateInvalid)
2698 break;
2699
2700 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701 HandlePrivateEvent (event_sp);
2702 }
2703 return state;
2704}
2705
2706Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002707Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708{
2709 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002711 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002712 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002713 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002714 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002715 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002716
Greg Claytonaa149cb2011-08-11 02:48:45 +00002717 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718 if (exe_module)
2719 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002720 char local_exec_file_path[PATH_MAX];
2721 char platform_exec_file_path[PATH_MAX];
2722 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2723 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724 if (exe_module->GetFileSpec().Exists())
2725 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002726 // Install anything that might need to be installed prior to launching.
2727 // For host systems, this will do nothing, but if we are connected to a
2728 // remote platform it will install any needed binaries
2729 error = GetTarget().Install(&launch_info);
2730 if (error.Fail())
2731 return error;
2732
Greg Clayton71337622011-02-24 22:24:29 +00002733 if (PrivateStateThreadIsValid ())
2734 PausePrivateStateThread ();
2735
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736 error = WillLaunch (exe_module);
2737 if (error.Success())
2738 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002739 const bool restarted = false;
2740 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002741 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742
Ed Maste64fad602013-07-29 20:58:06 +00002743 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002744 {
2745 // Now launch using these arguments.
2746 error = DoLaunch (exe_module, launch_info);
2747 }
2748 else
2749 {
2750 // This shouldn't happen
2751 error.SetErrorString("failed to acquire process run lock");
2752 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753
2754 if (error.Fail())
2755 {
2756 if (GetID() != LLDB_INVALID_PROCESS_ID)
2757 {
2758 SetID (LLDB_INVALID_PROCESS_ID);
2759 const char *error_string = error.AsCString();
2760 if (error_string == NULL)
2761 error_string = "launch failed";
2762 SetExitStatus (-1, error_string);
2763 }
2764 }
2765 else
2766 {
2767 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002768 TimeValue timeout_time;
2769 timeout_time = TimeValue::Now();
2770 timeout_time.OffsetWithSeconds(10);
2771 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002772
Greg Clayton1a38ea72011-06-22 01:42:17 +00002773 if (state == eStateInvalid || event_sp.get() == NULL)
2774 {
2775 // We were able to launch the process, but we failed to
2776 // catch the initial stop.
2777 SetExitStatus (0, "failed to catch stop after launch");
2778 Destroy();
2779 }
2780 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002782
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002783 DidLaunch ();
2784
Greg Claytonc859e2d2012-02-13 23:10:39 +00002785 DynamicLoader *dyld = GetDynamicLoader ();
2786 if (dyld)
2787 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002788
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002789 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002790
Jason Molendaeef51062013-11-05 03:57:19 +00002791 SystemRuntime *system_runtime = GetSystemRuntime ();
2792 if (system_runtime)
2793 system_runtime->DidLaunch();
2794
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002795 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002796 // This delays passing the stopped event to listeners till DidLaunch gets
2797 // a chance to complete...
2798 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002799
2800 if (PrivateStateThreadIsValid ())
2801 ResumePrivateStateThread ();
2802 else
2803 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804 }
2805 else if (state == eStateExited)
2806 {
2807 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2808 // not likely to work, and return an invalid pid.
2809 HandlePrivateEvent (event_sp);
2810 }
2811 }
2812 }
2813 }
2814 else
2815 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002816 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002817 }
2818 }
2819 return error;
2820}
2821
Greg Claytonc3776bf2012-02-09 06:16:32 +00002822
2823Error
2824Process::LoadCore ()
2825{
2826 Error error = DoLoadCore();
2827 if (error.Success())
2828 {
2829 if (PrivateStateThreadIsValid ())
2830 ResumePrivateStateThread ();
2831 else
2832 StartPrivateStateThread ();
2833
Greg Claytonc859e2d2012-02-13 23:10:39 +00002834 DynamicLoader *dyld = GetDynamicLoader ();
2835 if (dyld)
2836 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002837
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002838 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002839
Jason Molendaeef51062013-11-05 03:57:19 +00002840 SystemRuntime *system_runtime = GetSystemRuntime ();
2841 if (system_runtime)
2842 system_runtime->DidAttach();
2843
Greg Claytonc859e2d2012-02-13 23:10:39 +00002844 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002845 // We successfully loaded a core file, now pretend we stopped so we can
2846 // show all of the threads in the core file and explore the crashed
2847 // state.
2848 SetPrivateState (eStateStopped);
2849
2850 }
2851 return error;
2852}
2853
Greg Claytonc859e2d2012-02-13 23:10:39 +00002854DynamicLoader *
2855Process::GetDynamicLoader ()
2856{
2857 if (m_dyld_ap.get() == NULL)
2858 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2859 return m_dyld_ap.get();
2860}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002861
Todd Fialaaf245d12014-06-30 21:05:18 +00002862const lldb::DataBufferSP
2863Process::GetAuxvData()
2864{
2865 return DataBufferSP ();
2866}
2867
Andrew MacPherson17220c12014-03-05 10:12:43 +00002868JITLoaderList &
2869Process::GetJITLoaders ()
2870{
2871 if (!m_jit_loaders_ap)
2872 {
2873 m_jit_loaders_ap.reset(new JITLoaderList());
2874 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2875 }
2876 return *m_jit_loaders_ap;
2877}
2878
Jason Molendaeef51062013-11-05 03:57:19 +00002879SystemRuntime *
2880Process::GetSystemRuntime ()
2881{
2882 if (m_system_runtime_ap.get() == NULL)
2883 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2884 return m_system_runtime_ap.get();
2885}
2886
Greg Claytonc3776bf2012-02-09 06:16:32 +00002887
Jim Inghambb3a2832011-01-29 01:49:25 +00002888Process::NextEventAction::EventActionResult
2889Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890{
Jim Inghambb3a2832011-01-29 01:49:25 +00002891 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2892 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002893 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002894 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002895 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002896 return eEventActionRetry;
2897
2898 case eStateStopped:
2899 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002900 {
2901 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002902 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002903 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002904 // We don't want these events to be reported, so go set the ShouldReportStop here:
2905 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2906
Greg Claytonc9ed4782011-11-12 02:10:56 +00002907 if (m_exec_count > 0)
2908 {
2909 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00002910 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002911 return eEventActionRetry;
2912 }
2913 else
2914 {
2915 m_process->CompleteAttach ();
2916 return eEventActionSuccess;
2917 }
2918 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002919 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002920
Greg Clayton513c26c2011-01-29 07:10:55 +00002921 default:
2922 case eStateExited:
2923 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002924 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002925 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002926
2927 m_exit_string.assign ("No valid Process");
2928 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002929}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930
Jim Inghambb3a2832011-01-29 01:49:25 +00002931Process::NextEventAction::EventActionResult
2932Process::AttachCompletionHandler::HandleBeingInterrupted()
2933{
2934 return eEventActionSuccess;
2935}
2936
2937const char *
2938Process::AttachCompletionHandler::GetExitString ()
2939{
2940 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941}
2942
2943Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002944Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002947 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002948 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002949 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002950 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002951 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002952
Greg Clayton144f3a92011-11-15 03:53:30 +00002953 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002954 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002955 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002956 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002957 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002958
Greg Clayton144f3a92011-11-15 03:53:30 +00002959 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002960 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002961 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2962
2963 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002965 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2966 if (error.Success())
2967 {
Ed Maste64fad602013-07-29 20:58:06 +00002968 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00002969 {
2970 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00002971 const bool restarted = false;
2972 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00002973 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00002974 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00002975 }
2976 else
2977 {
2978 // This shouldn't happen
2979 error.SetErrorString("failed to acquire process run lock");
2980 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002981
Greg Clayton144f3a92011-11-15 03:53:30 +00002982 if (error.Fail())
2983 {
2984 if (GetID() != LLDB_INVALID_PROCESS_ID)
2985 {
2986 SetID (LLDB_INVALID_PROCESS_ID);
2987 if (error.AsCString() == NULL)
2988 error.SetErrorString("attach failed");
2989
2990 SetExitStatus(-1, error.AsCString());
2991 }
2992 }
2993 else
2994 {
2995 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2996 StartPrivateStateThread();
2997 }
2998 return error;
2999 }
Greg Claytone996fd32011-03-08 22:40:15 +00003000 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003001 else
Greg Claytone996fd32011-03-08 22:40:15 +00003002 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003003 ProcessInstanceInfoList process_infos;
3004 PlatformSP platform_sp (m_target.GetPlatform ());
3005
3006 if (platform_sp)
3007 {
3008 ProcessInstanceInfoMatch match_info;
3009 match_info.GetProcessInfo() = attach_info;
3010 match_info.SetNameMatchType (eNameMatchEquals);
3011 platform_sp->FindProcesses (match_info, process_infos);
3012 const uint32_t num_matches = process_infos.GetSize();
3013 if (num_matches == 1)
3014 {
3015 attach_pid = process_infos.GetProcessIDAtIndex(0);
3016 // Fall through and attach using the above process ID
3017 }
3018 else
3019 {
3020 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3021 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003022 {
3023 StreamString s;
3024 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3025 for (size_t i = 0; i < num_matches; i++)
3026 {
3027 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3028 }
3029 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3030 process_name,
3031 s.GetData());
3032 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003033 else
3034 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3035 }
3036 }
3037 else
3038 {
3039 error.SetErrorString ("invalid platform, can't find processes by name");
3040 return error;
3041 }
Greg Claytone996fd32011-03-08 22:40:15 +00003042 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043 }
3044 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003045 {
3046 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003047 }
3048 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003049
3050 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003051 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003052 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003053 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003055
Ed Maste64fad602013-07-29 20:58:06 +00003056 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003057 {
3058 // Now attach using these arguments.
3059 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003060 const bool restarted = false;
3061 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003062 error = DoAttachToProcessWithID (attach_pid, attach_info);
3063 }
3064 else
3065 {
3066 // This shouldn't happen
3067 error.SetErrorString("failed to acquire process run lock");
3068 }
3069
Greg Clayton144f3a92011-11-15 03:53:30 +00003070 if (error.Success())
3071 {
3072
3073 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3074 StartPrivateStateThread();
3075 }
3076 else
Greg Claytone996fd32011-03-08 22:40:15 +00003077 {
3078 if (GetID() != LLDB_INVALID_PROCESS_ID)
3079 {
3080 SetID (LLDB_INVALID_PROCESS_ID);
3081 const char *error_string = error.AsCString();
3082 if (error_string == NULL)
3083 error_string = "attach failed";
3084
3085 SetExitStatus(-1, error_string);
3086 }
3087 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088 }
3089 }
3090 return error;
3091}
3092
Greg Clayton93d3c8332011-02-16 04:46:07 +00003093void
3094Process::CompleteAttach ()
3095{
3096 // Let the process subclass figure out at much as it can about the process
3097 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003098 ArchSpec process_arch;
3099 DidAttach(process_arch);
3100
3101 if (process_arch.IsValid())
3102 m_target.SetArchitecture(process_arch);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003103
Jim Ingham4299fdb2011-09-15 01:10:17 +00003104 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3105 // the same as the one we've already set, switch architectures.
3106 PlatformSP platform_sp (m_target.GetPlatform ());
3107 assert (platform_sp.get());
3108 if (platform_sp)
3109 {
Greg Clayton70512312012-05-08 01:45:38 +00003110 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003111 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003112 {
3113 ArchSpec platform_arch;
3114 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3115 if (platform_sp)
3116 {
3117 m_target.SetPlatform (platform_sp);
3118 m_target.SetArchitecture(platform_arch);
3119 }
3120 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003121 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003122 {
3123 ProcessInstanceInfo process_info;
3124 platform_sp->GetProcessInfo (GetID(), process_info);
3125 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003126 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003127 m_target.SetArchitecture (process_arch);
3128 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003129 }
3130
3131 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003132 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003133 DynamicLoader *dyld = GetDynamicLoader ();
3134 if (dyld)
3135 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003136
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003137 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003138
Jason Molendaeef51062013-11-05 03:57:19 +00003139 SystemRuntime *system_runtime = GetSystemRuntime ();
3140 if (system_runtime)
3141 system_runtime->DidAttach();
3142
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003143 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003144 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003145 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003146 Mutex::Locker modules_locker(target_modules.GetMutex());
3147 size_t num_modules = target_modules.GetSize();
3148 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003149
Andy Gibbsa297a972013-06-19 19:04:53 +00003150 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003151 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003152 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003153 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003154 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003155 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003156 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003157 break;
3158 }
3159 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003160 if (new_executable_module_sp)
3161 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003162}
3163
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003164Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003165Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003166{
Greg Claytonb766a732011-02-04 01:58:07 +00003167 m_abi_sp.reset();
3168 m_process_input_reader.reset();
3169
3170 // Find the process and its architecture. Make sure it matches the architecture
3171 // of the current Target, and if not adjust it.
3172
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003173 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003174 if (error.Success())
3175 {
Greg Clayton71337622011-02-24 22:24:29 +00003176 if (GetID() != LLDB_INVALID_PROCESS_ID)
3177 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003178 EventSP event_sp;
3179 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3180
3181 if (state == eStateStopped || state == eStateCrashed)
3182 {
3183 // If we attached and actually have a process on the other end, then
3184 // this ended up being the equivalent of an attach.
3185 CompleteAttach ();
3186
3187 // This delays passing the stopped event to listeners till
3188 // CompleteAttach gets a chance to complete...
3189 HandlePrivateEvent (event_sp);
3190
3191 }
Greg Clayton71337622011-02-24 22:24:29 +00003192 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003193
3194 if (PrivateStateThreadIsValid ())
3195 ResumePrivateStateThread ();
3196 else
3197 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003198 }
3199 return error;
3200}
3201
3202
3203Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003204Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205{
Greg Clayton5160ce52013-03-27 23:08:40 +00003206 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003208 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003209 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003210 StateAsCString(m_public_state.GetValue()),
3211 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003212
3213 Error error (WillResume());
3214 // Tell the process it is about to resume before the thread list
3215 if (error.Success())
3216 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003217 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218 // can let all of our threads know that they are about to be
3219 // resumed. Threads will each be called with
3220 // Thread::WillResume(StateType) where StateType contains the state
3221 // that they are supposed to have when the process is resumed
3222 // (suspended/running/stepping). Threads should also check
3223 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003224 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003225 if (m_thread_list.WillResume())
3226 {
Jim Ingham372787f2012-04-07 00:00:41 +00003227 // Last thing, do the PreResumeActions.
3228 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003229 {
Jim Ingham0161b492013-02-09 01:29:05 +00003230 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003231 }
3232 else
3233 {
3234 m_mod_id.BumpResumeID();
3235 error = DoResume();
3236 if (error.Success())
3237 {
3238 DidResume();
3239 m_thread_list.DidResume();
3240 if (log)
3241 log->Printf ("Process thinks the process has resumed.");
3242 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003243 }
3244 }
3245 else
3246 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003247 // Somebody wanted to run without running. So generate a continue & a stopped event,
3248 // and let the world handle them.
3249 if (log)
3250 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3251
3252 SetPrivateState(eStateRunning);
3253 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254 }
3255 }
Jim Ingham444586b2011-01-24 06:34:17 +00003256 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003257 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258 return error;
3259}
3260
3261Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003262Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003264 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3265 // in case it was already set and some thread plan logic calls halt on its
3266 // own.
3267 m_clear_thread_plans_on_stop |= clear_thread_plans;
3268
Jim Inghamaacc3182012-06-06 00:29:30 +00003269 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3270 // we could just straightaway get another event. It just narrows the window...
3271 m_currently_handling_event.WaitForValueEqualTo(false);
3272
3273
Jim Inghambb3a2832011-01-29 01:49:25 +00003274 // Pause our private state thread so we can ensure no one else eats
3275 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003276 Listener halt_listener ("lldb.process.halt_listener");
3277 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003278
Jim Inghambb3a2832011-01-29 01:49:25 +00003279 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003280 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003281
Greg Clayton06357c92014-07-30 17:38:47 +00003282 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003283 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003284 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003285
Greg Clayton513c26c2011-01-29 07:10:55 +00003286 bool caused_stop = false;
3287
3288 // Ask the process subclass to actually halt our process
3289 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003291 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003292 if (m_public_state.GetValue() == eStateAttaching)
3293 {
Greg Clayton06357c92014-07-30 17:38:47 +00003294 // Don't hijack and eat the eStateExited as the code that was doing
3295 // the attach will be waiting for this event...
3296 RestorePrivateProcessEvents();
3297 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003298 SetExitStatus(SIGKILL, "Cancelled async attach.");
3299 Destroy ();
3300 }
3301 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003302 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003303 // If "caused_stop" is true, then DoHalt stopped the process. If
3304 // "caused_stop" is false, the process was already stopped.
3305 // If the DoHalt caused the process to stop, then we want to catch
3306 // this event and set the interrupted bool to true before we pass
3307 // this along so clients know that the process was interrupted by
3308 // a halt command.
3309 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003310 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003311 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003312 TimeValue timeout_time;
3313 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003314 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003315 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3316 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003317
Jim Ingham0f16e732011-02-08 05:20:59 +00003318 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003319 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003320 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003321 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003322 }
3323 else
3324 {
Greg Clayton2637f822011-11-17 01:23:07 +00003325 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003326 {
3327 // We caused the process to interrupt itself, so mark this
3328 // as such in the stop event so clients can tell an interrupted
3329 // process from a natural stop
3330 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3331 }
3332 else
3333 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003334 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003335 if (log)
3336 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3337 error.SetErrorString ("Did not get stopped event after halt.");
3338 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003339 }
3340 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003341 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003342 }
3343 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003344 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003345 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003346 if (!restored_process_events)
3347 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003348
3349 // Post any event we might have consumed. If all goes well, we will have
3350 // stopped the process, intercepted the event and set the interrupted
3351 // bool in the event. Post it to the private event queue and that will end up
3352 // correctly setting the state.
3353 if (event_sp)
3354 m_private_state_broadcaster.BroadcastEvent(event_sp);
3355
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356 return error;
3357}
3358
3359Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003360Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3361{
3362 Error error;
3363 if (m_public_state.GetValue() == eStateRunning)
3364 {
3365 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3366 if (log)
3367 log->Printf("Process::Destroy() About to halt.");
3368 error = Halt();
3369 if (error.Success())
3370 {
3371 // Consume the halt event.
3372 TimeValue timeout (TimeValue::Now());
3373 timeout.OffsetWithSeconds(1);
3374 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3375
3376 // If the process exited while we were waiting for it to stop, put the exited event into
3377 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3378 // they don't have a process anymore...
3379
3380 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3381 {
3382 if (log)
3383 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3384 return error;
3385 }
3386 else
3387 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3388
3389 if (state != eStateStopped)
3390 {
3391 if (log)
3392 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3393 // If we really couldn't stop the process then we should just error out here, but if the
3394 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3395 StateType private_state = m_private_state.GetValue();
3396 if (private_state != eStateStopped)
3397 {
3398 return error;
3399 }
3400 }
3401 }
3402 else
3403 {
3404 if (log)
3405 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3406 }
3407 }
3408 return error;
3409}
3410
3411Error
Jim Inghamacff8952013-05-02 00:27:30 +00003412Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003413{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003414 EventSP exit_event_sp;
3415 Error error;
3416 m_destroy_in_process = true;
3417
3418 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419
3420 if (error.Success())
3421 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003422 if (DetachRequiresHalt())
3423 {
3424 error = HaltForDestroyOrDetach (exit_event_sp);
3425 if (!error.Success())
3426 {
3427 m_destroy_in_process = false;
3428 return error;
3429 }
3430 else if (exit_event_sp)
3431 {
3432 // We shouldn't need to do anything else here. There's no process left to detach from...
3433 StopPrivateStateThread();
3434 m_destroy_in_process = false;
3435 return error;
3436 }
3437 }
3438
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003439 m_thread_list.DiscardThreadPlans();
3440 DisableAllBreakpointSites();
3441
Jim Inghamacff8952013-05-02 00:27:30 +00003442 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003443 if (error.Success())
3444 {
3445 DidDetach();
3446 StopPrivateStateThread();
3447 }
Jim Inghamacff8952013-05-02 00:27:30 +00003448 else
3449 {
3450 return error;
3451 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003453 m_destroy_in_process = false;
3454
3455 // If we exited when we were waiting for a process to stop, then
3456 // forward the event here so we don't lose the event
3457 if (exit_event_sp)
3458 {
3459 // Directly broadcast our exited event because we shut down our
3460 // private state thread above
3461 BroadcastEvent(exit_event_sp);
3462 }
3463
3464 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3465 // the last events through the event system, in which case we might strand the write lock. Unlock
3466 // it here so when we do to tear down the process we don't get an error destroying the lock.
3467
Ed Maste64fad602013-07-29 20:58:06 +00003468 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003469 return error;
3470}
3471
3472Error
3473Process::Destroy ()
3474{
Jim Ingham09437922013-03-01 20:04:25 +00003475
3476 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3477 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3478 // failed and the process stays around for some reason it won't be in a confused state.
3479
3480 m_destroy_in_process = true;
3481
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003482 Error error (WillDestroy());
3483 if (error.Success())
3484 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003485 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003486 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003487 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003488 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003489 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003490
Jim Inghamaacc3182012-06-06 00:29:30 +00003491 if (m_public_state.GetValue() != eStateRunning)
3492 {
3493 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3494 // kill it, we don't want it hitting a breakpoint...
3495 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3496 // we're not going to have much luck doing this now.
3497 m_thread_list.DiscardThreadPlans();
3498 DisableAllBreakpointSites();
3499 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003500
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003501 error = DoDestroy();
3502 if (error.Success())
3503 {
3504 DidDestroy();
3505 StopPrivateStateThread();
3506 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003507 m_stdio_communication.StopReadThread();
3508 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003509
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003510 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003511 {
3512 m_process_input_reader->SetIsDone(true);
3513 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003514 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003515 }
3516
Greg Clayton85fb1b92012-09-11 02:33:37 +00003517 // If we exited when we were waiting for a process to stop, then
3518 // forward the event here so we don't lose the event
3519 if (exit_event_sp)
3520 {
3521 // Directly broadcast our exited event because we shut down our
3522 // private state thread above
3523 BroadcastEvent(exit_event_sp);
3524 }
3525
Jim Inghamb1e2e842012-04-12 18:49:31 +00003526 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3527 // the last events through the event system, in which case we might strand the write lock. Unlock
3528 // 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 +00003529 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003530 }
Jim Ingham09437922013-03-01 20:04:25 +00003531
3532 m_destroy_in_process = false;
3533
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003534 return error;
3535}
3536
3537Error
3538Process::Signal (int signal)
3539{
3540 Error error (WillSignal());
3541 if (error.Success())
3542 {
3543 error = DoSignal(signal);
3544 if (error.Success())
3545 DidSignal();
3546 }
3547 return error;
3548}
3549
Greg Clayton514487e2011-02-15 21:59:32 +00003550lldb::ByteOrder
3551Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003552{
Greg Clayton514487e2011-02-15 21:59:32 +00003553 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003554}
3555
3556uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003557Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003558{
Greg Clayton514487e2011-02-15 21:59:32 +00003559 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560}
3561
Greg Clayton514487e2011-02-15 21:59:32 +00003562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003563bool
3564Process::ShouldBroadcastEvent (Event *event_ptr)
3565{
3566 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3567 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003568 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003569
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003570 switch (state)
3571 {
Greg Claytonb766a732011-02-04 01:58:07 +00003572 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003573 case eStateAttaching:
3574 case eStateLaunching:
3575 case eStateDetached:
3576 case eStateExited:
3577 case eStateUnloaded:
3578 // These events indicate changes in the state of the debugging session, always report them.
3579 return_value = true;
3580 break;
3581 case eStateInvalid:
3582 // We stopped for no apparent reason, don't report it.
3583 return_value = false;
3584 break;
3585 case eStateRunning:
3586 case eStateStepping:
3587 // If we've started the target running, we handle the cases where we
3588 // are already running and where there is a transition from stopped to
3589 // running differently.
3590 // running -> running: Automatically suppress extra running events
3591 // stopped -> running: Report except when there is one or more no votes
3592 // and no yes votes.
3593 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003594 if (m_force_next_event_delivery)
3595 return_value = true;
3596 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003597 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003598 switch (m_last_broadcast_state)
3599 {
3600 case eStateRunning:
3601 case eStateStepping:
3602 // We always suppress multiple runnings with no PUBLIC stop in between.
3603 return_value = false;
3604 break;
3605 default:
3606 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003607 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003608 // events. If I run the lldb/test/thread/a.out file and
3609 // break at main.cpp:58, run and hit the breakpoints on
3610 // multiple threads, then somehow during the stepping over
3611 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003612
Jim Ingham1460e4b2014-01-10 23:46:59 +00003613 // This is a transition from stop to run.
3614 switch (m_thread_list.ShouldReportRun (event_ptr))
3615 {
3616 case eVoteYes:
3617 case eVoteNoOpinion:
3618 return_value = true;
3619 break;
3620 case eVoteNo:
3621 return_value = false;
3622 break;
3623 }
3624 break;
3625 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626 }
3627 break;
3628 case eStateStopped:
3629 case eStateCrashed:
3630 case eStateSuspended:
3631 {
3632 // We've stopped. First see if we're going to restart the target.
3633 // If we are going to stop, then we always broadcast the event.
3634 // 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 +00003635 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003636
Jim Inghamcb4ca112012-05-16 01:32:14 +00003637 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003638 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003639 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003640 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003641 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003642 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003643 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003644 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3645 // so they can properly set their state.
3646 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003647 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003648 }
3649 else
3650 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003651 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3652 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003653
Jim Ingham0161b492013-02-09 01:29:05 +00003654 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3655 // Asking the thread list is also not likely to go well, since we are running again.
3656 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003657
Jim Ingham0161b492013-02-09 01:29:05 +00003658 if (!was_restarted)
3659 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003660
Jim Ingham221d51c2013-05-08 00:35:16 +00003661 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003662 {
Jim Ingham0161b492013-02-09 01:29:05 +00003663 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3664 if (log)
3665 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003666 should_resume, StateAsCString(state),
3667 was_restarted, stop_vote);
3668
Jim Ingham0161b492013-02-09 01:29:05 +00003669 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003670 {
3671 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003672 return_value = true;
3673 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003674 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675 case eVoteNo:
3676 return_value = false;
3677 break;
3678 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003679
Jim Inghamcb95f342012-09-05 21:13:56 +00003680 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003681 {
3682 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003683 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3684 static_cast<void*>(event_ptr),
3685 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003686 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003687 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003688 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003690 }
3691 else
3692 {
3693 return_value = true;
3694 SynchronouslyNotifyStateChanged (state);
3695 }
3696 }
3697 }
Jim Ingham0161b492013-02-09 01:29:05 +00003698 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003700
Jim Ingham1460e4b2014-01-10 23:46:59 +00003701 // Forcing the next event delivery is a one shot deal. So reset it here.
3702 m_force_next_event_delivery = false;
3703
Jim Ingham0161b492013-02-09 01:29:05 +00003704 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3705 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3706 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3707 // because the PublicState reflects the last event pulled off the queue, and there may be several
3708 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3709 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003710
Jim Ingham0161b492013-02-09 01:29:05 +00003711 if (return_value)
3712 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003713
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003714 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003715 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003716 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003717 StateAsCString(m_last_broadcast_state),
3718 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719 return return_value;
3720}
3721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722
3723bool
Jim Ingham372787f2012-04-07 00:00:41 +00003724Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725{
Greg Clayton5160ce52013-03-27 23:08:40 +00003726 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003727
Greg Clayton8b82f082011-04-12 05:54:46 +00003728 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003730 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3731
Jim Ingham372787f2012-04-07 00:00:41 +00003732 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003733 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003734
3735 // Create a thread that watches our internal state and controls which
3736 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003737 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003738
3739 if (Host::MAX_THREAD_NAME_LENGTH <= 16)
3740 {
3741 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3742 if (already_running)
3743 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3744 else
3745 snprintf(thread_name, sizeof(thread_name), "intern-state");
3746 }
Jim Ingham372787f2012-04-07 00:00:41 +00003747 else
Todd Fiala17096d72014-07-16 19:03:16 +00003748 {
3749 if (already_running)
3750 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
3751 else
3752 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3753 }
3754
Jim Ingham076b3042012-04-10 01:21:57 +00003755 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003756 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003757 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3758 if (success)
3759 {
3760 ResumePrivateStateThread();
3761 return true;
3762 }
3763 else
3764 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765}
3766
3767void
3768Process::PausePrivateStateThread ()
3769{
3770 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3771}
3772
3773void
3774Process::ResumePrivateStateThread ()
3775{
3776 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3777}
3778
3779void
3780Process::StopPrivateStateThread ()
3781{
Greg Clayton8b82f082011-04-12 05:54:46 +00003782 if (PrivateStateThreadIsValid ())
3783 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003784 else
3785 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003786 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003787 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003788 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003789 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790}
3791
3792void
3793Process::ControlPrivateStateThread (uint32_t signal)
3794{
Greg Clayton5160ce52013-03-27 23:08:40 +00003795 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003796
3797 assert (signal == eBroadcastInternalStateControlStop ||
3798 signal == eBroadcastInternalStateControlPause ||
3799 signal == eBroadcastInternalStateControlResume);
3800
3801 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003802 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003803
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003804 // Signal the private state thread. First we should copy this is case the
3805 // thread starts exiting since the private state thread will NULL this out
3806 // when it exits
3807 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003808 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003809 {
3810 TimeValue timeout_time;
3811 bool timed_out;
3812
3813 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3814
3815 timeout_time = TimeValue::Now();
3816 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003817 if (log)
3818 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003819 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3820 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3821
3822 if (signal == eBroadcastInternalStateControlStop)
3823 {
3824 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003825 {
3826 Error error;
3827 Host::ThreadCancel (private_state_thread, &error);
3828 if (log)
3829 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3830 }
3831 else
3832 {
3833 if (log)
3834 log->Printf ("The control event killed the private state thread without having to cancel.");
3835 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003836
3837 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003838 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003839 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840 }
3841 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003842 else
3843 {
3844 if (log)
3845 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3846 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847}
3848
3849void
Jim Inghamcfc09352012-07-27 23:57:19 +00003850Process::SendAsyncInterrupt ()
3851{
3852 if (PrivateStateThreadIsValid())
3853 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3854 else
3855 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3856}
3857
3858void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003859Process::HandlePrivateEvent (EventSP &event_sp)
3860{
Greg Clayton5160ce52013-03-27 23:08:40 +00003861 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003862 m_resume_requested = false;
3863
Jim Inghamaacc3182012-06-06 00:29:30 +00003864 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003865
Greg Clayton414f5d32011-01-25 02:58:48 +00003866 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003867
3868 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003869 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003870 {
Jim Ingham754ab982011-01-29 04:05:41 +00003871 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003872 if (log)
3873 log->Printf ("Ran next event action, result was %d.", action_result);
3874
Jim Inghambb3a2832011-01-29 01:49:25 +00003875 switch (action_result)
3876 {
3877 case NextEventAction::eEventActionSuccess:
3878 SetNextEventAction(NULL);
3879 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003880
Jim Inghambb3a2832011-01-29 01:49:25 +00003881 case NextEventAction::eEventActionRetry:
3882 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003883
Jim Inghambb3a2832011-01-29 01:49:25 +00003884 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003885 // Handle Exiting Here. If we already got an exited event,
3886 // we should just propagate it. Otherwise, swallow this event,
3887 // and set our state to exit so the next event will kill us.
3888 if (new_state != eStateExited)
3889 {
3890 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003891 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003892 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003893 SetNextEventAction(NULL);
3894 return;
3895 }
3896 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003897 break;
3898 }
3899 }
3900
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003901 // See if we should broadcast this state to external clients?
3902 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003903
3904 if (should_broadcast)
3905 {
Greg Claytonb4874f12014-02-28 18:22:24 +00003906 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003907 if (log)
3908 {
Daniel Malead01b2952012-11-29 21:49:15 +00003909 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003910 __FUNCTION__,
3911 GetID(),
3912 StateAsCString(new_state),
3913 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00003914 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003915 }
Jim Ingham9575d842011-03-11 03:53:59 +00003916 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003917 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00003918 {
3919 // Only push the input handler if we aren't fowarding events,
3920 // as this means the curses GUI is in use...
3921 if (!GetTarget().GetDebugger().IsForwardingEvents())
3922 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00003923 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00003924 }
Greg Claytonb4874f12014-02-28 18:22:24 +00003925 else if (StateIsStoppedState(new_state, false))
3926 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00003927 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00003928 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
3929 {
3930 // If the lldb_private::Debugger is handling the events, we don't
3931 // want to pop the process IOHandler here, we want to do it when
3932 // we receive the stopped event so we can carefully control when
3933 // the process IOHandler is popped because when we stop we want to
3934 // display some text stating how and why we stopped, then maybe some
3935 // process/thread/frame info, and then we want the "(lldb) " prompt
3936 // to show up. If we pop the process IOHandler here, then we will
3937 // cause the command interpreter to become the top IOHandler after
3938 // the process pops off and it will update its prompt right away...
3939 // See the Debugger.cpp file where it calls the function as
3940 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3941 // Otherwise we end up getting overlapping "(lldb) " prompts and
3942 // garbled output.
3943 //
3944 // If we aren't handling the events in the debugger (which is indicated
3945 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
3946 // are hijacked, then we always pop the process IO handler manually.
3947 // Hijacking happens when the internal process state thread is running
3948 // thread plans, or when commands want to run in synchronous mode
3949 // and they call "process->WaitForProcessToStop()". An example of something
3950 // that will hijack the events is a simple expression:
3951 //
3952 // (lldb) expr (int)puts("hello")
3953 //
3954 // This will cause the internal process state thread to resume and halt
3955 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3956 // events) and we do need the IO handler to be pushed and popped
3957 // correctly.
3958
3959 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
3960 PopProcessIOHandler ();
3961 }
3962 }
Jim Ingham9575d842011-03-11 03:53:59 +00003963
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964 BroadcastEvent (event_sp);
3965 }
3966 else
3967 {
3968 if (log)
3969 {
Daniel Malead01b2952012-11-29 21:49:15 +00003970 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003971 __FUNCTION__,
3972 GetID(),
3973 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003974 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003975 }
3976 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003977 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978}
3979
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003980thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981Process::PrivateStateThread (void *arg)
3982{
3983 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003984 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003985 return result;
3986}
3987
Virgile Bellob2f1fb22013-08-23 12:44:05 +00003988thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003989Process::RunPrivateStateThread ()
3990{
Jim Ingham076b3042012-04-10 01:21:57 +00003991 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003992 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003993
Greg Clayton5160ce52013-03-27 23:08:40 +00003994 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003995 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003996 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3997 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003998
3999 bool exit_now = false;
4000 while (!exit_now)
4001 {
4002 EventSP event_sp;
4003 WaitForEventsPrivate (NULL, event_sp, control_only);
4004 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4005 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004006 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004007 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4008 __FUNCTION__, static_cast<void*>(this), GetID(),
4009 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004010
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011 switch (event_sp->GetType())
4012 {
4013 case eBroadcastInternalStateControlStop:
4014 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004015 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016
4017 case eBroadcastInternalStateControlPause:
4018 control_only = true;
4019 break;
4020
4021 case eBroadcastInternalStateControlResume:
4022 control_only = false;
4023 break;
4024 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004025
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004026 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004027 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004028 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004029 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4030 {
4031 if (m_public_state.GetValue() == eStateAttaching)
4032 {
4033 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004034 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4035 __FUNCTION__, static_cast<void*>(this),
4036 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004037 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4038 }
4039 else
4040 {
4041 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004042 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4043 __FUNCTION__, static_cast<void*>(this),
4044 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004045 Halt();
4046 }
4047 continue;
4048 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004049
4050 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4051
4052 if (internal_state != eStateInvalid)
4053 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004054 if (m_clear_thread_plans_on_stop &&
4055 StateIsStoppedState(internal_state, true))
4056 {
4057 m_clear_thread_plans_on_stop = false;
4058 m_thread_list.DiscardThreadPlans();
4059 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004060 HandlePrivateEvent (event_sp);
4061 }
4062
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004063 if (internal_state == eStateInvalid ||
4064 internal_state == eStateExited ||
4065 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004066 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004067 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004068 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4069 __FUNCTION__, static_cast<void*>(this), GetID(),
4070 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004071
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004072 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004073 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074 }
4075
Caroline Tice20ad3c42010-10-29 21:48:37 +00004076 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004077 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004078 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4079 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004080
Ed Maste64fad602013-07-29 20:58:06 +00004081 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004082 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4083 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004084 return NULL;
4085}
4086
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004087//------------------------------------------------------------------
4088// Process Event Data
4089//------------------------------------------------------------------
4090
4091Process::ProcessEventData::ProcessEventData () :
4092 EventData (),
4093 m_process_sp (),
4094 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004095 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004096 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004097 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098{
4099}
4100
4101Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4102 EventData (),
4103 m_process_sp (process_sp),
4104 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004105 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004106 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004107 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004108{
4109}
4110
4111Process::ProcessEventData::~ProcessEventData()
4112{
4113}
4114
4115const ConstString &
4116Process::ProcessEventData::GetFlavorString ()
4117{
4118 static ConstString g_flavor ("Process::ProcessEventData");
4119 return g_flavor;
4120}
4121
4122const ConstString &
4123Process::ProcessEventData::GetFlavor () const
4124{
4125 return ProcessEventData::GetFlavorString ();
4126}
4127
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128void
4129Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4130{
4131 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004132 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4133 // the public event queue, then other times when we're pretending that this is where we stopped at the
4134 // end of expression evaluation. m_update_state is used to distinguish these
4135 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004136 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004137 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004138 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004139
Jim Ingham221d51c2013-05-08 00:35:16 +00004140 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004141
4142 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4143 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4144 // end up restarting the process.
4145 if (m_interrupted)
4146 return;
4147
4148 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004149 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004150 {
4151 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004152 uint32_t num_threads = curr_thread_list.GetSize();
4153 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004154
Jim Ingham4b536182011-08-09 02:12:22 +00004155 // The actions might change one of the thread's stop_info's opinions about whether we should
4156 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004157
4158 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4159 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4160 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4161 // 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
4162 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004163 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004164 for (idx = 0; idx < num_threads; ++idx)
4165 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4166
Jim Inghamc7078c22012-12-13 22:24:15 +00004167 // Use this to track whether we should continue from here. We will only continue the target running if
4168 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4169 // then it doesn't matter what the other threads say...
4170
4171 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004172
Jim Ingham0ad7e052013-04-25 02:04:59 +00004173 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4174 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4175 // thing to do is, and it's better to let the user decide than continue behind their backs.
4176
4177 bool does_anybody_have_an_opinion = false;
4178
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004179 for (idx = 0; idx < num_threads; ++idx)
4180 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004181 curr_thread_list = m_process_sp->GetThreadList();
4182 if (curr_thread_list.GetSize() != num_threads)
4183 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004184 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004185 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004186 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 +00004187 break;
4188 }
4189
4190 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4191
4192 if (thread_sp->GetIndexID() != thread_index_array[idx])
4193 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004194 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004195 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004196 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004197 idx,
4198 thread_index_array[idx],
4199 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004200 break;
4201 }
4202
Jim Inghamb15bfc72010-10-20 00:39:53 +00004203 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004204 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004205 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004206 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004207 bool this_thread_wants_to_stop;
4208 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004209 {
Jim Ingham0161b492013-02-09 01:29:05 +00004210 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4211 }
4212 else
4213 {
4214 stop_info_sp->PerformAction(event_ptr);
4215 // The stop action might restart the target. If it does, then we want to mark that in the
4216 // event so that whoever is receiving it will know to wait for the running event and reflect
4217 // that state appropriately.
4218 // We also need to stop processing actions, since they aren't expecting the target to be running.
4219
4220 // FIXME: we might have run.
4221 if (stop_info_sp->HasTargetRunSinceMe())
4222 {
4223 SetRestarted (true);
4224 break;
4225 }
4226
4227 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004228 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004229
Jim Inghamc7078c22012-12-13 22:24:15 +00004230 if (still_should_stop == false)
4231 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004232 }
4233 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004234
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004235
Jim Inghama8ca6e22013-05-03 23:04:37 +00004236 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004237 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004238 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004239 {
4240 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004241 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004242 // Use the public resume method here, since this is just
4243 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004244 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004245 }
4246 else
4247 {
4248 // If we didn't restart, run the Stop Hooks here:
4249 // They might also restart the target, so watch for that.
4250 m_process_sp->GetTarget().RunStopHooks();
4251 if (m_process_sp->GetPrivateState() == eStateRunning)
4252 SetRestarted(true);
4253 }
Jim Ingham9575d842011-03-11 03:53:59 +00004254 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004255 }
4256}
4257
4258void
4259Process::ProcessEventData::Dump (Stream *s) const
4260{
4261 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004262 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4263 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004264
Greg Clayton8b82f082011-04-12 05:54:46 +00004265 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004266}
4267
4268const Process::ProcessEventData *
4269Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4270{
4271 if (event_ptr)
4272 {
4273 const EventData *event_data = event_ptr->GetData();
4274 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4275 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4276 }
4277 return NULL;
4278}
4279
4280ProcessSP
4281Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4282{
4283 ProcessSP process_sp;
4284 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4285 if (data)
4286 process_sp = data->GetProcessSP();
4287 return process_sp;
4288}
4289
4290StateType
4291Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4292{
4293 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4294 if (data == NULL)
4295 return eStateInvalid;
4296 else
4297 return data->GetState();
4298}
4299
4300bool
4301Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4302{
4303 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4304 if (data == NULL)
4305 return false;
4306 else
4307 return data->GetRestarted();
4308}
4309
4310void
4311Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4312{
4313 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4314 if (data != NULL)
4315 data->SetRestarted(new_value);
4316}
4317
Jim Ingham0161b492013-02-09 01:29:05 +00004318size_t
4319Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4320{
4321 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4322 if (data != NULL)
4323 return data->GetNumRestartedReasons();
4324 else
4325 return 0;
4326}
4327
4328const char *
4329Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4330{
4331 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4332 if (data != NULL)
4333 return data->GetRestartedReasonAtIndex(idx);
4334 else
4335 return NULL;
4336}
4337
4338void
4339Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4340{
4341 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4342 if (data != NULL)
4343 data->AddRestartedReason(reason);
4344}
4345
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004346bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004347Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4348{
4349 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4350 if (data == NULL)
4351 return false;
4352 else
4353 return data->GetInterrupted ();
4354}
4355
4356void
4357Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4358{
4359 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4360 if (data != NULL)
4361 data->SetInterrupted(new_value);
4362}
4363
4364bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004365Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4366{
4367 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4368 if (data)
4369 {
4370 data->SetUpdateStateOnRemoval();
4371 return true;
4372 }
4373 return false;
4374}
4375
Greg Claytond9e416c2012-02-18 05:35:26 +00004376lldb::TargetSP
4377Process::CalculateTarget ()
4378{
4379 return m_target.shared_from_this();
4380}
4381
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004382void
Greg Clayton0603aa92010-10-04 01:05:56 +00004383Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004384{
Greg Claytonc14ee322011-09-22 04:58:26 +00004385 exe_ctx.SetTargetPtr (&m_target);
4386 exe_ctx.SetProcessPtr (this);
4387 exe_ctx.SetThreadPtr(NULL);
4388 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004389}
4390
Greg Claytone996fd32011-03-08 22:40:15 +00004391//uint32_t
4392//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4393//{
4394// return 0;
4395//}
4396//
4397//ArchSpec
4398//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4399//{
4400// return Host::GetArchSpecForExistingProcess (pid);
4401//}
4402//
4403//ArchSpec
4404//Process::GetArchSpecForExistingProcess (const char *process_name)
4405//{
4406// return Host::GetArchSpecForExistingProcess (process_name);
4407//}
4408//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004409void
4410Process::AppendSTDOUT (const char * s, size_t len)
4411{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004412 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004413 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004414 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004415}
4416
4417void
Greg Clayton93e86192011-11-13 04:45:22 +00004418Process::AppendSTDERR (const char * s, size_t len)
4419{
4420 Mutex::Locker locker (m_stdio_communication_mutex);
4421 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004422 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004423}
4424
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004425void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004426Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004427{
4428 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004429 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004430 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4431}
4432
4433size_t
4434Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4435{
4436 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004437 if (m_profile_data.empty())
4438 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004439
4440 std::string &one_profile_data = m_profile_data.front();
4441 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004442 if (bytes_available > 0)
4443 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004444 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004445 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004446 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4447 static_cast<void*>(buf),
4448 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004449 if (bytes_available > buf_size)
4450 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004451 memcpy(buf, one_profile_data.c_str(), buf_size);
4452 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004453 bytes_available = buf_size;
4454 }
4455 else
4456 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004457 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004458 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004459 }
4460 }
4461 return bytes_available;
4462}
4463
4464
Greg Clayton93e86192011-11-13 04:45:22 +00004465//------------------------------------------------------------------
4466// Process STDIO
4467//------------------------------------------------------------------
4468
4469size_t
4470Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4471{
4472 Mutex::Locker locker(m_stdio_communication_mutex);
4473 size_t bytes_available = m_stdout_data.size();
4474 if (bytes_available > 0)
4475 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004476 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004477 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004478 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4479 static_cast<void*>(buf),
4480 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004481 if (bytes_available > buf_size)
4482 {
4483 memcpy(buf, m_stdout_data.c_str(), buf_size);
4484 m_stdout_data.erase(0, buf_size);
4485 bytes_available = buf_size;
4486 }
4487 else
4488 {
4489 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4490 m_stdout_data.clear();
4491 }
4492 }
4493 return bytes_available;
4494}
4495
4496
4497size_t
4498Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4499{
4500 Mutex::Locker locker(m_stdio_communication_mutex);
4501 size_t bytes_available = m_stderr_data.size();
4502 if (bytes_available > 0)
4503 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004504 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004505 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004506 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4507 static_cast<void*>(buf),
4508 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004509 if (bytes_available > buf_size)
4510 {
4511 memcpy(buf, m_stderr_data.c_str(), buf_size);
4512 m_stderr_data.erase(0, buf_size);
4513 bytes_available = buf_size;
4514 }
4515 else
4516 {
4517 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4518 m_stderr_data.clear();
4519 }
4520 }
4521 return bytes_available;
4522}
4523
4524void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004525Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4526{
4527 Process *process = (Process *) baton;
4528 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4529}
4530
Greg Clayton44d93782014-01-27 23:43:24 +00004531class IOHandlerProcessSTDIO :
4532 public IOHandler
4533{
4534public:
4535 IOHandlerProcessSTDIO (Process *process,
4536 int write_fd) :
4537 IOHandler(process->GetTarget().GetDebugger()),
4538 m_process (process),
4539 m_read_file (),
4540 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004541 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004542 {
4543 m_read_file.SetDescriptor(GetInputFD(), false);
4544 }
4545
4546 virtual
4547 ~IOHandlerProcessSTDIO ()
4548 {
4549
4550 }
4551
4552 bool
4553 OpenPipes ()
4554 {
Greg Clayton100eb932014-07-02 21:10:39 +00004555 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004556 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004557 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004558 }
4559
4560 void
4561 ClosePipes()
4562 {
Greg Clayton100eb932014-07-02 21:10:39 +00004563 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004564 }
4565
4566 // Each IOHandler gets to run until it is done. It should read data
4567 // from the "in" and place output into "out" and "err and return
4568 // when done.
4569 virtual void
4570 Run ()
4571 {
4572 if (m_read_file.IsValid() && m_write_file.IsValid())
4573 {
4574 SetIsDone(false);
4575 if (OpenPipes())
4576 {
4577 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004578 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004579 TerminalState terminal_state;
4580 terminal_state.Save (read_fd, false);
4581 Terminal terminal(read_fd);
4582 terminal.SetCanonical(false);
4583 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004584// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004585#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004586 while (!GetIsDone())
4587 {
4588 fd_set read_fdset;
4589 FD_ZERO (&read_fdset);
4590 FD_SET (read_fd, &read_fdset);
4591 FD_SET (pipe_read_fd, &read_fdset);
4592 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4593 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4594 if (num_set_fds < 0)
4595 {
4596 const int select_errno = errno;
4597
4598 if (select_errno != EINTR)
4599 SetIsDone(true);
4600 }
4601 else if (num_set_fds > 0)
4602 {
4603 char ch = 0;
4604 size_t n;
4605 if (FD_ISSET (read_fd, &read_fdset))
4606 {
4607 n = 1;
4608 if (m_read_file.Read(&ch, n).Success() && n == 1)
4609 {
4610 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4611 SetIsDone(true);
4612 }
4613 else
4614 SetIsDone(true);
4615 }
4616 if (FD_ISSET (pipe_read_fd, &read_fdset))
4617 {
4618 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004619 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004620 {
Greg Clayton100eb932014-07-02 21:10:39 +00004621 switch (ch)
4622 {
4623 case 'q':
4624 SetIsDone(true);
4625 break;
4626 case 'i':
4627 if (StateIsRunningState(m_process->GetState()))
4628 m_process->Halt();
4629 break;
4630 }
Greg Clayton19e11352014-02-26 22:47:33 +00004631 }
Greg Clayton44d93782014-01-27 23:43:24 +00004632 }
4633 }
4634 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004635#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004636 terminal_state.Restore();
4637
4638 }
4639 else
4640 SetIsDone(true);
4641 }
4642 else
4643 SetIsDone(true);
4644 }
4645
4646 // Hide any characters that have been displayed so far so async
4647 // output can be displayed. Refresh() will be called after the
4648 // output has been displayed.
4649 virtual void
4650 Hide ()
4651 {
4652
4653 }
4654 // Called when the async output has been received in order to update
4655 // the input reader (refresh the prompt and redisplay any current
4656 // line(s) that are being edited
4657 virtual void
4658 Refresh ()
4659 {
4660
4661 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004662
Greg Clayton44d93782014-01-27 23:43:24 +00004663 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004664 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004665 {
Greg Clayton19e11352014-02-26 22:47:33 +00004666 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004667 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004668 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004669
Greg Claytonf0066ad2014-05-02 00:45:31 +00004670 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004671 Interrupt ()
4672 {
Greg Clayton19e11352014-02-26 22:47:33 +00004673 // Do only things that are safe to do in an interrupt context (like in
4674 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4675 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4676 // that was written to the pipe and then call m_process->Halt() from a
4677 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004678 if (m_active)
4679 {
4680 char ch = 'i'; // Send 'i' for interrupt
4681 return m_pipe.Write (&ch, 1) == 1;
4682 }
4683 else
4684 {
4685 // This IOHandler might be pushed on the stack, but not being run currently
4686 // so do the right thing if we aren't actively watching for STDIN by sending
4687 // the interrupt to the process. Otherwise the write to the pipe above would
4688 // do nothing. This can happen when the command interpreter is running and
4689 // gets a "expression ...". It will be on the IOHandler thread and sending
4690 // the input is complete to the delegate which will cause the expression to
4691 // run, which will push the process IO handler, but not run it.
4692
4693 if (StateIsRunningState(m_process->GetState()))
4694 {
4695 m_process->SendAsyncInterrupt();
4696 return true;
4697 }
4698 }
4699 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004700 }
Greg Clayton44d93782014-01-27 23:43:24 +00004701
4702 virtual void
4703 GotEOF()
4704 {
4705
4706 }
4707
4708protected:
4709 Process *m_process;
4710 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4711 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004712 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004713};
4714
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004715void
Greg Clayton44d93782014-01-27 23:43:24 +00004716Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004717{
4718 // First set up the Read Thread for reading/handling process I/O
4719
Greg Clayton44d93782014-01-27 23:43:24 +00004720 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004721
4722 if (conn_ap.get())
4723 {
4724 m_stdio_communication.SetConnection (conn_ap.release());
4725 if (m_stdio_communication.IsConnected())
4726 {
4727 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4728 m_stdio_communication.StartReadThread();
4729
4730 // Now read thread is set up, set up input reader.
4731
4732 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004733 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004734 }
4735 }
4736}
4737
Greg Claytonb4874f12014-02-28 18:22:24 +00004738bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004739Process::ProcessIOHandlerIsActive ()
4740{
4741 IOHandlerSP io_handler_sp (m_process_input_reader);
4742 if (io_handler_sp)
4743 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4744 return false;
4745}
4746bool
Greg Clayton44d93782014-01-27 23:43:24 +00004747Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004748{
Greg Clayton44d93782014-01-27 23:43:24 +00004749 IOHandlerSP io_handler_sp (m_process_input_reader);
4750 if (io_handler_sp)
4751 {
4752 io_handler_sp->SetIsDone(false);
4753 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004754 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004755 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004756 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004757}
4758
Greg Claytonb4874f12014-02-28 18:22:24 +00004759bool
Greg Clayton44d93782014-01-27 23:43:24 +00004760Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004761{
Greg Clayton44d93782014-01-27 23:43:24 +00004762 IOHandlerSP io_handler_sp (m_process_input_reader);
4763 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004764 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4765 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004766}
4767
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004768// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004769void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004770Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004771{
Greg Clayton6920b522012-08-22 18:39:03 +00004772 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004773}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004774
Greg Clayton99d0faf2010-11-18 23:32:35 +00004775void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004776Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004777{
Greg Clayton6920b522012-08-22 18:39:03 +00004778 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004779}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004780
Jim Ingham1624a2d2014-05-05 02:26:40 +00004781ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004782Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004783 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004784 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004785 Stream &errors)
4786{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004787 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004788
Jim Ingham77787032011-01-20 02:03:18 +00004789 if (thread_plan_sp.get() == NULL)
4790 {
4791 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004792 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004793 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004794
Jim Ingham7d7931d2013-03-28 00:05:34 +00004795 if (!thread_plan_sp->ValidatePlan(NULL))
4796 {
4797 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004798 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004799 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004800
Greg Claytonc14ee322011-09-22 04:58:26 +00004801 if (exe_ctx.GetProcessPtr() != this)
4802 {
4803 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004804 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004805 }
4806
4807 Thread *thread = exe_ctx.GetThreadPtr();
4808 if (thread == NULL)
4809 {
4810 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004811 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004812 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004813
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004814 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4815 // For that to be true the plan can't be private - since private plans suppress themselves in the
4816 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004817
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004818 bool orig_plan_private = thread_plan_sp->GetPrivate();
4819 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004820
Jim Ingham444586b2011-01-24 06:34:17 +00004821 if (m_private_state.GetValue() != eStateStopped)
4822 {
4823 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004824 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004825 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004826
Jim Ingham66243842011-08-13 00:56:10 +00004827 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004828 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004829 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004830 if (!selected_frame_sp)
4831 {
4832 thread->SetSelectedFrame(0);
4833 selected_frame_sp = thread->GetSelectedFrame();
4834 if (!selected_frame_sp)
4835 {
4836 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004837 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004838 }
4839 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004840
Jim Ingham11b0e052013-02-19 23:22:45 +00004841 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004842
4843 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4844 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004845
Greg Claytonc14ee322011-09-22 04:58:26 +00004846 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004847
Jim Ingham66243842011-08-13 00:56:10 +00004848 uint32_t selected_tid;
4849 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004850 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004851 {
4852 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004853 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004854 }
4855 else
4856 {
4857 selected_tid = LLDB_INVALID_THREAD_ID;
4858 }
4859
Jim Ingham372787f2012-04-07 00:00:41 +00004860 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004861 lldb::StateType old_state;
4862 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004863
Greg Clayton5160ce52013-03-27 23:08:40 +00004864 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004865 if (Host::GetCurrentThread() == m_private_state_thread)
4866 {
Jim Ingham076b3042012-04-10 01:21:57 +00004867 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4868 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004869 // 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 +00004870 // we are fielding public events here.
4871 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004872 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 +00004873
Jim Ingham372787f2012-04-07 00:00:41 +00004874 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004875
4876 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4877 // returning control here.
4878 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4879 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4880 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4881 // do just what we want.
4882 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4883 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4884 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4885 old_state = m_public_state.GetValue();
4886 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004887
Jim Ingham076b3042012-04-10 01:21:57 +00004888 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004889 StartPrivateStateThread(true);
4890 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004891
Jim Ingham372787f2012-04-07 00:00:41 +00004892 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004893
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004894 if (options.GetDebug())
4895 {
4896 // In this case, we aren't actually going to run, we just want to stop right away.
4897 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4898 // FIXME: To make this prettier we should invent some stop reason for this, but that
4899 // is only cosmetic, and this functionality is only of use to lldb developers who can
4900 // live with not pretty...
4901 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00004902 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004903 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004904
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004905 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004906
Sean Callanana46ec452012-07-11 21:31:24 +00004907 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004908
Jim Ingham77787032011-01-20 02:03:18 +00004909 {
Sean Callanana46ec452012-07-11 21:31:24 +00004910 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4911 // restored on exit to the function.
4912 //
4913 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4914 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004915
Sean Callanana46ec452012-07-11 21:31:24 +00004916 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004917
Jim Inghamf48169b2010-11-30 02:22:11 +00004918 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004919 {
4920 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004921 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004922 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004923 thread->GetIndexID(),
4924 thread->GetID(),
4925 s.GetData());
4926 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004927
Sean Callanana46ec452012-07-11 21:31:24 +00004928 bool got_event;
4929 lldb::EventSP event_sp;
4930 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004931
Sean Callanana46ec452012-07-11 21:31:24 +00004932 TimeValue* timeout_ptr = NULL;
4933 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004934
Jim Ingham0161b492013-02-09 01:29:05 +00004935 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 +00004936 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004937 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004938 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004939
Jim Ingham0161b492013-02-09 01:29:05 +00004940 // This is just for accounting:
4941 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004942
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004943 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00004944 uint32_t one_thread_timeout_usec;
4945 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00004946
4947 // If we are going to run all threads the whole time, or if we are only going to run one thread,
4948 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
4949 // first timeout already.
4950
4951 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00004952 {
4953 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00004954 one_thread_timeout_usec = 0;
4955 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00004956 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004957 else
Jim Ingham0161b492013-02-09 01:29:05 +00004958 {
Jim Inghamfd95f892014-04-22 01:41:52 +00004959 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004960
Jim Ingham914f4e72014-03-28 21:58:28 +00004961 // If the overall wait is forever, then we only need to set the one thread timeout:
4962 if (timeout_usec == 0)
4963 {
Ed Maste801335c2014-03-31 19:28:14 +00004964 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00004965 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00004966 else
Jim Inghamfd95f892014-04-22 01:41:52 +00004967 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00004968 }
Jim Ingham0161b492013-02-09 01:29:05 +00004969 else
4970 {
Jim Ingham914f4e72014-03-28 21:58:28 +00004971 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
4972 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
4973 uint64_t computed_one_thread_timeout;
4974 if (option_one_thread_timeout != 0)
4975 {
4976 if (timeout_usec < option_one_thread_timeout)
4977 {
4978 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004979 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00004980 }
4981 computed_one_thread_timeout = option_one_thread_timeout;
4982 }
4983 else
4984 {
4985 computed_one_thread_timeout = timeout_usec / 2;
4986 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
4987 computed_one_thread_timeout = default_one_thread_timeout_usec;
4988 }
Jim Inghamfd95f892014-04-22 01:41:52 +00004989 one_thread_timeout_usec = computed_one_thread_timeout;
4990 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
4991
Jim Ingham0161b492013-02-09 01:29:05 +00004992 }
Jim Ingham0161b492013-02-09 01:29:05 +00004993 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00004994
4995 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00004996 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 +00004997 options.GetStopOthers(),
4998 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00004999 before_first_timeout,
5000 one_thread_timeout_usec,
5001 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005002
Jim Ingham1460e4b2014-01-10 23:46:59 +00005003 // This isn't going to work if there are unfetched events on the queue.
5004 // Are there cases where we might want to run the remaining events here, and then try to
5005 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005006
Jim Ingham1460e4b2014-01-10 23:46:59 +00005007 Event *other_events = listener.PeekAtNextEvent();
5008 if (other_events != NULL)
5009 {
5010 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005011 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005012 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005013
Jim Ingham1460e4b2014-01-10 23:46:59 +00005014 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5015 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5016 // event coalescing to cause us to lose OUR running event...
5017 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005018
Jim Ingham8559a352012-11-26 23:52:18 +00005019 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5020 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005021
5022#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5023 // It's pretty much impossible to write test cases for things like:
5024 // One thread timeout expires, I go to halt, but the process already stopped
5025 // on the function call stop breakpoint. Turning on this define will make us not
5026 // fetch the first event till after the halt. So if you run a quick function, it will have
5027 // completed, and the completion event will be waiting, when you interrupt for halt.
5028 // The expression evaluation should still succeed.
5029 bool miss_first_event = true;
5030#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005031 TimeValue one_thread_timeout;
5032 TimeValue final_timeout;
5033
Jim Ingham35878c42014-04-08 21:33:21 +00005034
Sean Callanana46ec452012-07-11 21:31:24 +00005035 while (1)
5036 {
5037 // We usually want to resume the process if we get to the top of the loop.
5038 // The only exception is if we get two running events with no intervening
5039 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005040 if (log)
5041 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5042 do_resume,
5043 handle_running_event,
5044 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005045
Jim Ingham184e9812013-01-15 02:47:48 +00005046 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005047 {
5048 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005049
Jim Ingham184e9812013-01-15 02:47:48 +00005050 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005051 {
Jim Ingham0161b492013-02-09 01:29:05 +00005052 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005053 Error resume_error = PrivateResume ();
5054 if (!resume_error.Success())
5055 {
Jim Ingham0161b492013-02-09 01:29:05 +00005056 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5057 num_resumes,
5058 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005059 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005060 break;
5061 }
Sean Callanana46ec452012-07-11 21:31:24 +00005062 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005063
Jim Ingham0161b492013-02-09 01:29:05 +00005064 TimeValue resume_timeout = TimeValue::Now();
5065 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005066
Jim Ingham0161b492013-02-09 01:29:05 +00005067 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005068 if (!got_event)
5069 {
5070 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005071 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5072 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005073
Jim Ingham0161b492013-02-09 01:29:05 +00005074 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005075 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005076 break;
5077 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005078
Sean Callanana46ec452012-07-11 21:31:24 +00005079 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005080
Sean Callanana46ec452012-07-11 21:31:24 +00005081 if (stop_state != eStateRunning)
5082 {
Jim Ingham0161b492013-02-09 01:29:05 +00005083 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005084
Jim Ingham0161b492013-02-09 01:29:05 +00005085 if (stop_state == eStateStopped)
5086 {
5087 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5088 if (log)
5089 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5090 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5091 num_resumes,
5092 StateAsCString(stop_state),
5093 restarted,
5094 do_resume,
5095 handle_running_event);
5096 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005097
Jim Ingham0161b492013-02-09 01:29:05 +00005098 if (restarted)
5099 {
5100 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5101 // event here. But if I do, the best thing is to Halt and then get out of here.
5102 Halt();
5103 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005104
Jim Ingham35e1bda2012-10-16 21:41:58 +00005105 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5106 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005107 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005108 break;
5109 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005110
Sean Callanana46ec452012-07-11 21:31:24 +00005111 if (log)
5112 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5113 // We need to call the function synchronously, so spin waiting for it to return.
5114 // If we get interrupted while executing, we're going to lose our context, and
5115 // won't be able to gather the result at this point.
5116 // We set the timeout AFTER the resume, since the resume takes some time and we
5117 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005118 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005119 else
5120 {
Sean Callanana46ec452012-07-11 21:31:24 +00005121 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005122 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005123 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005124
Jim Ingham0161b492013-02-09 01:29:05 +00005125 if (before_first_timeout)
5126 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005127 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005128 {
5129 one_thread_timeout = TimeValue::Now();
5130 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005131 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005132 }
Jim Ingham0161b492013-02-09 01:29:05 +00005133 else
5134 {
5135 if (timeout_usec == 0)
5136 timeout_ptr = NULL;
5137 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005138 {
5139 final_timeout = TimeValue::Now();
5140 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005141 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005142 }
Jim Ingham0161b492013-02-09 01:29:05 +00005143 }
5144 }
5145 else
5146 {
5147 if (timeout_usec == 0)
5148 timeout_ptr = NULL;
5149 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005150 {
5151 final_timeout = TimeValue::Now();
5152 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005153 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005154 }
Jim Ingham0161b492013-02-09 01:29:05 +00005155 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005156
Jim Ingham0161b492013-02-09 01:29:05 +00005157 do_resume = true;
5158 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005159
Sean Callanana46ec452012-07-11 21:31:24 +00005160 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005161 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005162
Jim Ingham0f16e732011-02-08 05:20:59 +00005163 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005164 {
Sean Callanana46ec452012-07-11 21:31:24 +00005165 if (timeout_ptr)
5166 {
Matt Kopec676a4872013-02-21 23:55:31 +00005167 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005168 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5169 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005170 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005171 else
Sean Callanana46ec452012-07-11 21:31:24 +00005172 {
5173 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5174 }
5175 }
Jim Ingham35878c42014-04-08 21:33:21 +00005176
5177#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5178 // See comment above...
5179 if (miss_first_event)
5180 {
5181 usleep(1000);
5182 miss_first_event = false;
5183 got_event = false;
5184 }
5185 else
5186#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005187 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005188
Sean Callanana46ec452012-07-11 21:31:24 +00005189 if (got_event)
5190 {
5191 if (event_sp.get())
5192 {
5193 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005194 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005195 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005196 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005197 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005198 errors.Printf ("Execution halted by user interrupt.");
5199 if (log)
5200 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005201 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005202 }
5203 else
5204 {
5205 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5206 if (log)
5207 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005208
Jim Inghamcfc09352012-07-27 23:57:19 +00005209 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005210 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005211 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005212 {
Jim Ingham0161b492013-02-09 01:29:05 +00005213 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005214 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5215 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005216 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005217 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005218 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005219 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005220 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005221 }
5222 else
5223 {
Jim Ingham0161b492013-02-09 01:29:05 +00005224 // If we were restarted, we just need to go back up to fetch another event.
5225 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005226 {
5227 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005228 {
5229 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5230 }
5231 keep_going = true;
5232 do_resume = false;
5233 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005234
Jim Inghamcfc09352012-07-27 23:57:19 +00005235 }
5236 else
5237 {
Jim Ingham0161b492013-02-09 01:29:05 +00005238 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5239 StopReason stop_reason = eStopReasonInvalid;
5240 if (stop_info_sp)
5241 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005242
Jim Ingham0161b492013-02-09 01:29:05 +00005243 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5244 // it is OUR plan that is complete?
5245 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005246 {
5247 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005248 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5249 // Now mark this plan as private so it doesn't get reported as the stop reason
5250 // after this point.
5251 if (thread_plan_sp)
5252 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005253 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005254 }
5255 else
5256 {
Jim Ingham0161b492013-02-09 01:29:05 +00005257 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005258 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005259 {
5260 if (log)
5261 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005262 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005263 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005264 {
5265 event_to_broadcast_sp = event_sp;
5266 }
Jim Ingham0161b492013-02-09 01:29:05 +00005267 }
Jim Ingham184e9812013-01-15 02:47:48 +00005268 else
Jim Ingham0161b492013-02-09 01:29:05 +00005269 {
5270 if (log)
5271 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005272 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005273 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005274 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005275 }
Jim Ingham184e9812013-01-15 02:47:48 +00005276 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005277 }
Sean Callanana46ec452012-07-11 21:31:24 +00005278 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005279 }
5280 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005281
Jim Inghamcfc09352012-07-27 23:57:19 +00005282 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005283 // This shouldn't really happen, but sometimes we do get two running events without an
5284 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005285 do_resume = false;
5286 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005287 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005288 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005289
Jim Inghamcfc09352012-07-27 23:57:19 +00005290 default:
5291 if (log)
5292 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005293
Jim Inghamcfc09352012-07-27 23:57:19 +00005294 if (stop_state == eStateExited)
5295 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005296
Sean Callananbf154da2012-08-08 17:35:10 +00005297 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005298 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005299 break;
5300 }
Sean Callanana46ec452012-07-11 21:31:24 +00005301 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005302
Sean Callanana46ec452012-07-11 21:31:24 +00005303 if (keep_going)
5304 continue;
5305 else
5306 break;
5307 }
5308 else
5309 {
5310 if (log)
5311 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005312 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005313 break;
5314 }
5315 }
5316 else
5317 {
5318 // If we didn't get an event that means we've timed out...
5319 // We will interrupt the process here. Depending on what we were asked to do we will
5320 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005321
Sean Callanana46ec452012-07-11 21:31:24 +00005322 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005323 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005324 {
Jim Ingham0161b492013-02-09 01:29:05 +00005325 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005326 {
5327 if (timeout_usec != 0)
5328 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005329 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005330 "running for %" PRIu32 " usec with all threads enabled.",
5331 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005332 }
5333 else
5334 {
5335 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005336 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005337 }
5338 }
Sean Callanana46ec452012-07-11 21:31:24 +00005339 else
5340 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005341 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005342 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005343 }
5344 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005345 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005346 "abandoning execution.",
5347 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005348 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005349
Jim Ingham0161b492013-02-09 01:29:05 +00005350 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5351 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5352 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5353 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5354 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005355
Jim Ingham0161b492013-02-09 01:29:05 +00005356 bool back_to_top = true;
5357 uint32_t try_halt_again = 0;
5358 bool do_halt = true;
5359 const uint32_t num_retries = 5;
5360 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005361 {
Jim Ingham0161b492013-02-09 01:29:05 +00005362 Error halt_error;
5363 if (do_halt)
5364 {
5365 if (log)
5366 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5367 halt_error = Halt();
5368 }
5369 if (halt_error.Success())
5370 {
5371 if (log)
5372 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005373
Jim Ingham0161b492013-02-09 01:29:05 +00005374 real_timeout = TimeValue::Now();
5375 real_timeout.OffsetWithMicroSeconds(500000);
5376
5377 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005378
Jim Ingham0161b492013-02-09 01:29:05 +00005379 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005380 {
Jim Ingham0161b492013-02-09 01:29:05 +00005381 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5382 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005383 {
Jim Ingham0161b492013-02-09 01:29:05 +00005384 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5385 if (stop_state == lldb::eStateStopped
5386 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5387 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005388 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005389
Jim Ingham0161b492013-02-09 01:29:05 +00005390 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005391 {
Jim Ingham0161b492013-02-09 01:29:05 +00005392 // Between the time we initiated the Halt and the time we delivered it, the process could have
5393 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005394
Jim Ingham0161b492013-02-09 01:29:05 +00005395 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5396 {
5397 if (log)
5398 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5399 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005400 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005401 back_to_top = false;
5402 break;
5403 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005404
Jim Ingham0161b492013-02-09 01:29:05 +00005405 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5406 {
5407 if (log)
5408 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5409 "Exiting wait loop.");
5410 try_halt_again++;
5411 do_halt = false;
5412 continue;
5413 }
Sean Callanana46ec452012-07-11 21:31:24 +00005414
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005415 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005416 {
5417 if (log)
5418 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005419 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005420 back_to_top = false;
5421 break;
5422 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005423
Jim Ingham0161b492013-02-09 01:29:05 +00005424 if (before_first_timeout)
5425 {
5426 // Set all the other threads to run, and return to the top of the loop, which will continue;
5427 before_first_timeout = false;
5428 thread_plan_sp->SetStopOthers (false);
5429 if (log)
5430 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005431
Jim Ingham0161b492013-02-09 01:29:05 +00005432 back_to_top = true;
5433 break;
5434 }
5435 else
5436 {
5437 // Running all threads failed, so return Interrupted.
5438 if (log)
5439 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005440 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005441 back_to_top = false;
5442 break;
5443 }
Sean Callanana46ec452012-07-11 21:31:24 +00005444 }
5445 }
5446 else
Jim Ingham0161b492013-02-09 01:29:05 +00005447 { if (log)
5448 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5449 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005450 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005451 back_to_top = false;
5452 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005453 }
5454 }
Jim Ingham0161b492013-02-09 01:29:05 +00005455 else
5456 {
5457 try_halt_again++;
5458 continue;
5459 }
Sean Callanana46ec452012-07-11 21:31:24 +00005460 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005461
Jim Ingham0161b492013-02-09 01:29:05 +00005462 if (!back_to_top || try_halt_again > num_retries)
5463 break;
5464 else
5465 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005466 }
Sean Callanana46ec452012-07-11 21:31:24 +00005467 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005468
Sean Callanana46ec452012-07-11 21:31:24 +00005469 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5470 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5471 {
5472 StopPrivateStateThread();
5473 Error error;
5474 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005475 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005476 {
5477 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5478 }
5479 m_public_state.SetValueNoLock(old_state);
5480
5481 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005482
Jim Ingham184e9812013-01-15 02:47:48 +00005483 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5484 // could happen:
5485 // 1) The execution successfully completed
5486 // 2) We hit a breakpoint, and ignore_breakpoints was true
5487 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005488 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5489 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005490
Jim Ingham8646d3c2014-05-05 02:47:44 +00005491 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005492 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005493 {
5494 thread_plan_sp->RestoreThreadState();
5495 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005496
Sean Callanana46ec452012-07-11 21:31:24 +00005497 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005498 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005499 {
5500 if (log)
5501 {
5502 StreamString s;
5503 if (event_sp)
5504 event_sp->Dump (&s);
5505 else
5506 {
5507 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5508 }
5509
5510 StreamString ts;
5511
5512 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005513
Sean Callanana46ec452012-07-11 21:31:24 +00005514 do
5515 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005516 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005517 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005518 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005519 break;
5520 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005521 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005522 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005523 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005524 break;
5525 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005526 else
Sean Callanana46ec452012-07-11 21:31:24 +00005527 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005528 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5529
5530 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005531 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005532 event_explanation = "<no event data>";
5533 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005534 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005535
Jim Inghamcfc09352012-07-27 23:57:19 +00005536 Process *process = event_data->GetProcessSP().get();
5537
5538 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005539 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005540 event_explanation = "<no process>";
5541 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005542 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005543
Jim Inghamcfc09352012-07-27 23:57:19 +00005544 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005545
Jim Inghamcfc09352012-07-27 23:57:19 +00005546 uint32_t num_threads = thread_list.GetSize();
5547 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005548
Jim Inghamcfc09352012-07-27 23:57:19 +00005549 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005550
Jim Inghamcfc09352012-07-27 23:57:19 +00005551 for (thread_index = 0;
5552 thread_index < num_threads;
5553 ++thread_index)
5554 {
5555 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005556
Jim Inghamcfc09352012-07-27 23:57:19 +00005557 if (!thread)
5558 {
5559 ts.Printf("<?> ");
5560 continue;
5561 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005562
Daniel Malead01b2952012-11-29 21:49:15 +00005563 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005564 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005565
Jim Inghamcfc09352012-07-27 23:57:19 +00005566 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005567 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005568 else
5569 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005570
Jim Inghamcfc09352012-07-27 23:57:19 +00005571 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5572 if (stop_info_sp)
5573 {
5574 const char *stop_desc = stop_info_sp->GetDescription();
5575 if (stop_desc)
5576 ts.PutCString (stop_desc);
5577 }
5578 ts.Printf(">");
5579 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005580
Jim Inghamcfc09352012-07-27 23:57:19 +00005581 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005582 }
Sean Callanana46ec452012-07-11 21:31:24 +00005583 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005584
Jim Inghamcfc09352012-07-27 23:57:19 +00005585 if (event_explanation)
5586 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005587 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005588 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5589 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005590
Jim Inghame4483cf2013-09-27 01:13:01 +00005591 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005592 {
5593 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005594 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5595 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005596 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5597 thread_plan_sp->SetPrivate (orig_plan_private);
5598 }
5599 else
5600 {
5601 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005602 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5603 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005604 }
5605 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005606 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005607 {
5608 if (log)
5609 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005610
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005611 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005612 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005613 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005614 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005615 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005616 }
5617 else
5618 {
Sean Callanana46ec452012-07-11 21:31:24 +00005619 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005620 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005621 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005622 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005623 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005624 }
5625 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5626 {
5627 if (log)
5628 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005629 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005630 }
5631 else
5632 {
5633 if (log)
5634 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005635 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005636 {
5637 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005638 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005639 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5640 thread_plan_sp->SetPrivate (orig_plan_private);
5641 }
5642 }
5643 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005644
Sean Callanana46ec452012-07-11 21:31:24 +00005645 // Thread we ran the function in may have gone away because we ran the target
5646 // Check that it's still there, and if it is put it back in the context. Also restore the
5647 // frame in the context if it is still present.
5648 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5649 if (thread)
5650 {
5651 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5652 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005653
Sean Callanana46ec452012-07-11 21:31:24 +00005654 // Also restore the current process'es selected frame & thread, since this function calling may
5655 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005656
Sean Callanana46ec452012-07-11 21:31:24 +00005657 if (selected_tid != LLDB_INVALID_THREAD_ID)
5658 {
5659 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5660 {
5661 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005662 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005663 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005664 if (old_frame_sp)
5665 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005666 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005667 }
5668 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005669
Sean Callanana46ec452012-07-11 21:31:24 +00005670 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005671
Sean Callanana46ec452012-07-11 21:31:24 +00005672 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005673 {
Sean Callanana46ec452012-07-11 21:31:24 +00005674 if (log)
5675 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5676 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005677 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005678
Jim Inghamf48169b2010-11-30 02:22:11 +00005679 return return_value;
5680}
5681
5682const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005683Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005684{
5685 const char *result_name;
5686
5687 switch (result)
5688 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005689 case eExpressionCompleted:
5690 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005691 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005692 case eExpressionDiscarded:
5693 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005694 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005695 case eExpressionInterrupted:
5696 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005697 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005698 case eExpressionHitBreakpoint:
5699 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005700 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005701 case eExpressionSetupError:
5702 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005703 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005704 case eExpressionParseError:
5705 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005706 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005707 case eExpressionResultUnavailable:
5708 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005709 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005710 case eExpressionTimedOut:
5711 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005712 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005713 case eExpressionStoppedForDebug:
5714 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005715 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005716 }
5717 return result_name;
5718}
5719
Greg Clayton7260f622011-04-18 08:33:37 +00005720void
5721Process::GetStatus (Stream &strm)
5722{
5723 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005724 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005725 {
5726 if (state == eStateExited)
5727 {
5728 int exit_status = GetExitStatus();
5729 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005730 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005731 GetID(),
5732 exit_status,
5733 exit_status,
5734 exit_description ? exit_description : "");
5735 }
5736 else
5737 {
5738 if (state == eStateConnected)
5739 strm.Printf ("Connected to remote target.\n");
5740 else
Daniel Malead01b2952012-11-29 21:49:15 +00005741 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005742 }
5743 }
5744 else
5745 {
Daniel Malead01b2952012-11-29 21:49:15 +00005746 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005747 }
5748}
5749
5750size_t
5751Process::GetThreadStatus (Stream &strm,
5752 bool only_threads_with_stop_reason,
5753 uint32_t start_frame,
5754 uint32_t num_frames,
5755 uint32_t num_frames_with_source)
5756{
5757 size_t num_thread_infos_dumped = 0;
5758
Jim Ingham4a65fb12014-03-07 11:20:03 +00005759 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5760 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5761 // ID's, and look them up one by one:
5762
5763 uint32_t num_threads;
5764 std::vector<uint32_t> thread_index_array;
5765 //Scope for thread list locker;
5766 {
5767 Mutex::Locker locker (GetThreadList().GetMutex());
5768 ThreadList &curr_thread_list = GetThreadList();
5769 num_threads = curr_thread_list.GetSize();
5770 uint32_t idx;
5771 thread_index_array.resize(num_threads);
5772 for (idx = 0; idx < num_threads; ++idx)
5773 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5774 }
5775
Greg Clayton7260f622011-04-18 08:33:37 +00005776 for (uint32_t i = 0; i < num_threads; i++)
5777 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005778 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5779 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005780 {
5781 if (only_threads_with_stop_reason)
5782 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005783 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005784 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005785 continue;
5786 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005787 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005788 start_frame,
5789 num_frames,
5790 num_frames_with_source);
5791 ++num_thread_infos_dumped;
5792 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005793 else
5794 {
5795 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5796 if (log)
5797 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5798
5799 }
Greg Clayton7260f622011-04-18 08:33:37 +00005800 }
5801 return num_thread_infos_dumped;
5802}
5803
Greg Claytona9f40ad2012-02-22 04:37:26 +00005804void
5805Process::AddInvalidMemoryRegion (const LoadRange &region)
5806{
5807 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5808}
5809
5810bool
5811Process::RemoveInvalidMemoryRange (const LoadRange &region)
5812{
5813 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5814}
5815
Jim Ingham372787f2012-04-07 00:00:41 +00005816void
5817Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5818{
5819 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5820}
5821
5822bool
5823Process::RunPreResumeActions ()
5824{
5825 bool result = true;
5826 while (!m_pre_resume_actions.empty())
5827 {
5828 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5829 m_pre_resume_actions.pop_back();
5830 bool this_result = action.callback (action.baton);
5831 if (result == true) result = this_result;
5832 }
5833 return result;
5834}
5835
5836void
5837Process::ClearPreResumeActions ()
5838{
5839 m_pre_resume_actions.clear();
5840}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005841
Greg Claytonfa559e52012-05-18 02:38:05 +00005842void
5843Process::Flush ()
5844{
5845 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005846 m_extended_thread_list.Flush();
5847 m_extended_thread_stop_id = 0;
5848 m_queue_list.Clear();
5849 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005850}
Greg Clayton90ba8112012-12-05 00:16:59 +00005851
5852void
5853Process::DidExec ()
5854{
5855 Target &target = GetTarget();
5856 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005857 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005858 m_dynamic_checkers_ap.reset();
5859 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005860 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005861 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005862 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005863 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005864 m_image_tokens.clear();
5865 m_allocated_memory_cache.Clear();
5866 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005867 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005868 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005869 DoDidExec();
5870 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005871 // Flush the process (threads and all stack frames) after running CompleteAttach()
5872 // in case the dynamic loader loaded things in new locations.
5873 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005874
5875 // After we figure out what was loaded/unloaded in CompleteAttach,
5876 // we need to let the target know so it can do any cleanup it needs to.
5877 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005878}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005879
Jim Ingham1460e4b2014-01-10 23:46:59 +00005880addr_t
5881Process::ResolveIndirectFunction(const Address *address, Error &error)
5882{
5883 if (address == nullptr)
5884 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005885 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005886 return LLDB_INVALID_ADDRESS;
5887 }
5888
5889 addr_t function_addr = LLDB_INVALID_ADDRESS;
5890
5891 addr_t addr = address->GetLoadAddress(&GetTarget());
5892 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5893 if (iter != m_resolved_indirect_addresses.end())
5894 {
5895 function_addr = (*iter).second;
5896 }
5897 else
5898 {
5899 if (!InferiorCall(this, address, function_addr))
5900 {
5901 Symbol *symbol = address->CalculateSymbolContextSymbol();
5902 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5903 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5904 function_addr = LLDB_INVALID_ADDRESS;
5905 }
5906 else
5907 {
5908 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5909 }
5910 }
5911 return function_addr;
5912}
5913
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005914void
5915Process::ModulesDidLoad (ModuleList &module_list)
5916{
5917 SystemRuntime *sys_runtime = GetSystemRuntime();
5918 if (sys_runtime)
5919 {
5920 sys_runtime->ModulesDidLoad (module_list);
5921 }
5922
5923 GetJITLoaders().ModulesDidLoad (module_list);
5924}