blob: 41dcbf45042414134fdddd0eb08f7235f26a0ab5 [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"
Zachary Turner39de3112014-09-09 20:54:56 +000030#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000031#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000032#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000033#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000035#include "lldb/Target/DynamicLoader.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000036#include "lldb/Target/JITLoader.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000037#include "lldb/Target/MemoryHistory.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000038#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000039#include "lldb/Target/LanguageRuntime.h"
40#include "lldb/Target/CPPLanguageRuntime.h"
41#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000042#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000044#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000045#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/Target.h"
47#include "lldb/Target/TargetList.h"
48#include "lldb/Target/Thread.h"
49#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000050#include "lldb/Target/ThreadPlanBase.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000051#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052
53using namespace lldb;
54using namespace lldb_private;
55
Greg Clayton67cc0632012-08-22 17:17:09 +000056
57// Comment out line below to disable memory caching, overriding the process setting
58// target.process.disable-memory-cache
59#define ENABLE_MEMORY_CACHING
60
61#ifdef ENABLE_MEMORY_CACHING
62#define DISABLE_MEM_CACHE_DEFAULT false
63#else
64#define DISABLE_MEM_CACHE_DEFAULT true
65#endif
66
67class ProcessOptionValueProperties : public OptionValueProperties
68{
69public:
70 ProcessOptionValueProperties (const ConstString &name) :
71 OptionValueProperties (name)
72 {
73 }
74
75 // This constructor is used when creating ProcessOptionValueProperties when it
76 // is part of a new lldb_private::Process instance. It will copy all current
77 // global property values as needed
78 ProcessOptionValueProperties (ProcessProperties *global_properties) :
79 OptionValueProperties(*global_properties->GetValueProperties())
80 {
81 }
82
83 virtual const Property *
84 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
85 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000086 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000087 // try and grab the setting from the current process if there is one. Else we just
88 // use the one from this instance.
89 if (exe_ctx)
90 {
91 Process *process = exe_ctx->GetProcessPtr();
92 if (process)
93 {
94 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
95 if (this != instance_properties)
96 return instance_properties->ProtectedGetPropertyAtIndex (idx);
97 }
98 }
99 return ProtectedGetPropertyAtIndex (idx);
100 }
101};
102
103static PropertyDefinition
104g_properties[] =
105{
106 { "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 +0000107 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
108 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000109 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
110 { "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 +0000111 { "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 +0000112 { "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 +0000113 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Jason Molendaf0340c92014-09-03 22:30:54 +0000114 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Greg Clayton67cc0632012-08-22 17:17:09 +0000115 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
116};
117
118enum {
119 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000120 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000121 ePropertyIgnoreBreakpointsInExpressions,
122 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000123 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000124 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000125 ePropertyDetachKeepsStopped,
126 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09 +0000127};
128
129ProcessProperties::ProcessProperties (bool is_global) :
130 Properties ()
131{
132 if (is_global)
133 {
134 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
135 m_collection_sp->Initialize(g_properties);
136 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000137 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000138 true,
139 Thread::GetGlobalProperties()->GetValueProperties());
140 }
141 else
142 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
143}
144
145ProcessProperties::~ProcessProperties()
146{
147}
148
149bool
150ProcessProperties::GetDisableMemoryCache() const
151{
152 const uint32_t idx = ePropertyDisableMemCache;
153 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
154}
155
Jason Molendaf0340c92014-09-03 22:30:54 +0000156uint64_t
157ProcessProperties::GetMemoryCacheLineSize() const
158{
159 const uint32_t idx = ePropertyMemCacheLineSize;
160 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
161}
162
Greg Clayton67cc0632012-08-22 17:17:09 +0000163Args
164ProcessProperties::GetExtraStartupCommands () const
165{
166 Args args;
167 const uint32_t idx = ePropertyExtraStartCommand;
168 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
169 return args;
170}
171
172void
173ProcessProperties::SetExtraStartupCommands (const Args &args)
174{
175 const uint32_t idx = ePropertyExtraStartCommand;
176 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
177}
178
Greg Claytonc9d645d2012-10-18 22:40:37 +0000179FileSpec
180ProcessProperties::GetPythonOSPluginPath () const
181{
182 const uint32_t idx = ePropertyPythonOSPluginPath;
183 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
184}
185
186void
187ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
188{
189 const uint32_t idx = ePropertyPythonOSPluginPath;
190 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
191}
192
Jim Ingham184e9812013-01-15 02:47:48 +0000193
194bool
195ProcessProperties::GetIgnoreBreakpointsInExpressions () const
196{
197 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
198 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
199}
200
201void
202ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
203{
204 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
205 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
206}
207
208bool
209ProcessProperties::GetUnwindOnErrorInExpressions () const
210{
211 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
212 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
213}
214
215void
216ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
217{
218 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
219 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
220}
221
Jim Ingham29950772013-01-26 02:19:28 +0000222bool
223ProcessProperties::GetStopOnSharedLibraryEvents () const
224{
225 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
226 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
227}
228
229void
230ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
231{
232 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
233 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
234}
235
Jim Inghamacff8952013-05-02 00:27:30 +0000236bool
237ProcessProperties::GetDetachKeepsStopped () const
238{
239 const uint32_t idx = ePropertyDetachKeepsStopped;
240 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
241}
242
243void
244ProcessProperties::SetDetachKeepsStopped (bool stop)
245{
246 const uint32_t idx = ePropertyDetachKeepsStopped;
247 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
248}
249
Greg Clayton32e0a752011-03-30 18:16:51 +0000250void
Greg Clayton8b82f082011-04-12 05:54:46 +0000251ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000252{
253 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000254 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000255 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000256
257 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000258 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000259
260 if (m_executable)
261 {
262 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
263 s.PutCString (" file = ");
264 m_executable.Dump(&s);
265 s.EOL();
266 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000267 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000268 if (argc > 0)
269 {
270 for (uint32_t i=0; i<argc; i++)
271 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000272 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000273 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000274 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000275 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000276 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000277 }
278 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000279
280 const uint32_t envc = m_environment.GetArgumentCount();
281 if (envc > 0)
282 {
283 for (uint32_t i=0; i<envc; i++)
284 {
285 const char *env = m_environment.GetArgumentAtIndex(i);
286 if (i < 10)
287 s.Printf (" env[%u] = %s\n", i, env);
288 else
289 s.Printf ("env[%u] = %s\n", i, env);
290 }
291 }
292
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 if (m_arch.IsValid())
294 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
295
Greg Clayton8b82f082011-04-12 05:54:46 +0000296 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000297 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 cstr = platform->GetUserName (m_uid);
299 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000300 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000301 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000302 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000303 cstr = platform->GetGroupName (m_gid);
304 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000305 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000306 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000307 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000308 cstr = platform->GetUserName (m_euid);
309 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000310 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000311 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000312 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000313 cstr = platform->GetGroupName (m_egid);
314 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000315 }
316}
317
318void
Greg Clayton8b82f082011-04-12 05:54:46 +0000319ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000320{
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 const char *label;
322 if (show_args || verbose)
323 label = "ARGUMENTS";
324 else
325 label = "NAME";
326
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000327 if (verbose)
328 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000329 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000330 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
331 }
332 else
333 {
Jim Ingham368ac222014-08-15 17:05:27 +0000334 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
335 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000336 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000337}
338
339void
Greg Clayton8b82f082011-04-12 05:54:46 +0000340ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000341{
342 if (m_pid != LLDB_INVALID_PROCESS_ID)
343 {
344 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000345 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000346
Greg Clayton32e0a752011-03-30 18:16:51 +0000347
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000348 if (verbose)
349 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000350 cstr = platform->GetUserName (m_uid);
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_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000355
Greg Clayton8b82f082011-04-12 05:54:46 +0000356 cstr = platform->GetGroupName (m_gid);
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_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000361
Greg Clayton8b82f082011-04-12 05:54:46 +0000362 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000363 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
364 s.Printf ("%-10s ", cstr);
365 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000366 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000367
Greg Clayton8b82f082011-04-12 05:54:46 +0000368 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000369 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
370 s.Printf ("%-10s ", cstr);
371 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
374 }
375 else
376 {
Jim Ingham368ac222014-08-15 17:05:27 +0000377 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000378 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000379 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000380 }
381
Greg Clayton8b82f082011-04-12 05:54:46 +0000382 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000384 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000385 if (argc > 0)
386 {
387 for (uint32_t i=0; i<argc; i++)
388 {
389 if (i > 0)
390 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000391 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000392 }
393 }
394 }
395 else
396 {
397 s.PutCString (GetName());
398 }
399
400 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000401 }
402}
403
Greg Clayton8b82f082011-04-12 05:54:46 +0000404Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000405ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000406{
407 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000408 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000409
410 switch (short_option)
411 {
412 case 's': // Stop at program entry point
413 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
414 break;
415
Greg Clayton8b82f082011-04-12 05:54:46 +0000416 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000417 {
418 FileAction action;
419 if (action.Open (STDIN_FILENO, option_arg, true, false))
420 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000421 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000422 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000423
424 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000425 {
426 FileAction action;
427 if (action.Open (STDOUT_FILENO, option_arg, false, true))
428 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000429 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000430 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000431
432 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000433 {
434 FileAction action;
435 if (action.Open (STDERR_FILENO, option_arg, false, true))
436 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000437 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000438 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000439
Greg Clayton8b82f082011-04-12 05:54:46 +0000440 case 'p': // Process plug-in name
441 launch_info.SetProcessPluginName (option_arg);
442 break;
443
444 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000445 {
446 FileAction action;
447 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
448 launch_info.AppendFileAction (action);
449 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
450 launch_info.AppendFileAction (action);
451 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
452 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000453 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000454 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000455
456 case 'w':
457 launch_info.SetWorkingDirectory (option_arg);
458 break;
459
460 case 't': // Open process in new terminal window
461 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
462 break;
463
464 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000465 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
466 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000467 break;
468
Todd Fiala51637922014-08-19 17:40:43 +0000469 case 'A': // Disable ASLR.
470 {
471 bool success;
472 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
473 if (success)
474 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
475 else
476 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000477 break;
Todd Fiala51637922014-08-19 17:40:43 +0000478 }
479
480 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000481 if (option_arg && option_arg[0])
482 launch_info.SetShell (option_arg);
483 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000484 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000485 break;
486
Greg Clayton8b82f082011-04-12 05:54:46 +0000487 case 'v':
488 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
489 break;
490
491 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000492 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000493 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 }
495 return error;
496}
497
498OptionDefinition
499ProcessLaunchCommandOptions::g_option_table[] =
500{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000501{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
Todd Fiala51637922014-08-19 17:40:43 +0000502{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000503{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
504{ 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."},
505{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
506{ 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."},
507{ 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 +0000508
Zachary Turnerd37221d2014-07-09 16:31:49 +0000509{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
510{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
511{ 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 +0000512
Zachary Turnerd37221d2014-07-09 16:31:49 +0000513{ 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 +0000514
Zachary Turnerd37221d2014-07-09 16:31:49 +0000515{ 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 +0000516
Zachary Turnerd37221d2014-07-09 16:31:49 +0000517{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000518};
519
520
521
522bool
523ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000524{
525 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
526 return true;
527 const char *match_name = m_match_info.GetName();
528 if (!match_name)
529 return true;
530
531 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
532}
533
534bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000535ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000536{
537 if (!NameMatches (proc_info.GetName()))
538 return false;
539
540 if (m_match_info.ProcessIDIsValid() &&
541 m_match_info.GetProcessID() != proc_info.GetProcessID())
542 return false;
543
544 if (m_match_info.ParentProcessIDIsValid() &&
545 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
546 return false;
547
Greg Clayton8b82f082011-04-12 05:54:46 +0000548 if (m_match_info.UserIDIsValid () &&
549 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000550 return false;
551
Greg Clayton8b82f082011-04-12 05:54:46 +0000552 if (m_match_info.GroupIDIsValid () &&
553 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000554 return false;
555
556 if (m_match_info.EffectiveUserIDIsValid () &&
557 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
558 return false;
559
560 if (m_match_info.EffectiveGroupIDIsValid () &&
561 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
562 return false;
563
564 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000565 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000566 return false;
567 return true;
568}
569
570bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000571ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000572{
573 if (m_name_match_type != eNameMatchIgnore)
574 return false;
575
576 if (m_match_info.ProcessIDIsValid())
577 return false;
578
579 if (m_match_info.ParentProcessIDIsValid())
580 return false;
581
Greg Clayton8b82f082011-04-12 05:54:46 +0000582 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000583 return false;
584
Greg Clayton8b82f082011-04-12 05:54:46 +0000585 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000586 return false;
587
588 if (m_match_info.EffectiveUserIDIsValid ())
589 return false;
590
591 if (m_match_info.EffectiveGroupIDIsValid ())
592 return false;
593
594 if (m_match_info.GetArchitecture().IsValid())
595 return false;
596
597 if (m_match_all_users)
598 return false;
599
600 return true;
601
602}
603
604void
Greg Clayton8b82f082011-04-12 05:54:46 +0000605ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000606{
607 m_match_info.Clear();
608 m_name_match_type = eNameMatchIgnore;
609 m_match_all_users = false;
610}
Greg Clayton58be07b2011-01-07 06:08:19 +0000611
Greg Claytonc3776bf2012-02-09 06:16:32 +0000612ProcessSP
613Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000614{
Greg Clayton949e8222013-01-16 17:29:04 +0000615 static uint32_t g_process_unique_id = 0;
616
Greg Claytonc3776bf2012-02-09 06:16:32 +0000617 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 ProcessCreateInstance create_callback = NULL;
619 if (plugin_name)
620 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000621 ConstString const_plugin_name(plugin_name);
622 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623 if (create_callback)
624 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000625 process_sp = create_callback(target, listener, crash_file_path);
626 if (process_sp)
627 {
Greg Clayton949e8222013-01-16 17:29:04 +0000628 if (process_sp->CanDebug(target, true))
629 {
630 process_sp->m_process_unique_id = ++g_process_unique_id;
631 }
632 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000633 process_sp.reset();
634 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000635 }
636 }
637 else
638 {
Greg Claytonc982c762010-07-09 20:39:50 +0000639 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000641 process_sp = create_callback(target, listener, crash_file_path);
642 if (process_sp)
643 {
Greg Clayton949e8222013-01-16 17:29:04 +0000644 if (process_sp->CanDebug(target, false))
645 {
646 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000647 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000648 }
649 else
650 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000651 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 }
653 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000654 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655}
656
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000657ConstString &
658Process::GetStaticBroadcasterClass ()
659{
660 static ConstString class_name ("lldb.process");
661 return class_name;
662}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663
664//----------------------------------------------------------------------
665// Process constructor
666//----------------------------------------------------------------------
667Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000668 Process(target, listener, Host::GetUnixSignals ())
669{
670 // This constructor just delegates to the full Process constructor,
671 // defaulting to using the Host's UnixSignals.
672}
673
674Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000675 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000676 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000677 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679 m_public_state (eStateUnloaded),
680 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000681 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
682 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 m_private_state_listener ("lldb.process.internal_state_listener"),
684 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000685 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000686 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000688 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 m_exit_status (-1),
690 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000691 m_thread_mutex (Mutex::eMutexTypeRecursive),
692 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000693 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000694 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000695 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000696 m_queue_list (this),
697 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000698 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000699 m_image_tokens (),
700 m_listener (listener),
701 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000702 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000703 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000704 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000705 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000706 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000707 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000708 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000709 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000710 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
711 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000712 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000713 m_memory_cache (*this),
714 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000715 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000716 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000717 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000718 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000719 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000720 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000721 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000722 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000723 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000724 m_destroy_in_process (false),
725 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000727 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000728
Greg Clayton5160ce52013-03-27 23:08:40 +0000729 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000731 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732
Todd Fiala4ceced32014-08-29 17:35:57 +0000733 if (!m_unix_signals_sp)
734 m_unix_signals_sp.reset (new UnixSignals ());
735
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000736 SetEventName (eBroadcastBitStateChanged, "state-changed");
737 SetEventName (eBroadcastBitInterrupt, "interrupt");
738 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
739 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000740 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000741
Greg Clayton35a4cc52012-10-29 20:52:08 +0000742 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
743 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
744 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
745
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 listener.StartListeningForEvents (this,
747 eBroadcastBitStateChanged |
748 eBroadcastBitInterrupt |
749 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000750 eBroadcastBitSTDERR |
751 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000752
753 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000754 eBroadcastBitStateChanged |
755 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756
757 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
758 eBroadcastInternalStateControlStop |
759 eBroadcastInternalStateControlPause |
760 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000761 // We need something valid here, even if just the default UnixSignalsSP.
762 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763}
764
765//----------------------------------------------------------------------
766// Destructor
767//----------------------------------------------------------------------
768Process::~Process()
769{
Greg Clayton5160ce52013-03-27 23:08:40 +0000770 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000772 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000773 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000774
775 // ThreadList::Clear() will try to acquire this process's mutex, so
776 // explicitly clear the thread list here to ensure that the mutex
777 // is not destroyed before the thread list.
778 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779}
780
Greg Clayton67cc0632012-08-22 17:17:09 +0000781const ProcessPropertiesSP &
782Process::GetGlobalProperties()
783{
784 static ProcessPropertiesSP g_settings_sp;
785 if (!g_settings_sp)
786 g_settings_sp.reset (new ProcessProperties (true));
787 return g_settings_sp;
788}
789
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790void
791Process::Finalize()
792{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000793 switch (GetPrivateState())
794 {
795 case eStateConnected:
796 case eStateAttaching:
797 case eStateLaunching:
798 case eStateStopped:
799 case eStateRunning:
800 case eStateStepping:
801 case eStateCrashed:
802 case eStateSuspended:
803 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000804 {
805 // FIXME: This will have to be a process setting:
806 bool keep_stopped = false;
807 Detach(keep_stopped);
808 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000809 else
810 Destroy();
811 break;
812
813 case eStateInvalid:
814 case eStateUnloaded:
815 case eStateDetached:
816 case eStateExited:
817 break;
818 }
819
Greg Clayton1ed54f52011-10-01 00:45:15 +0000820 // Clear our broadcaster before we proceed with destroying
821 Broadcaster::Clear();
822
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 // Do any cleanup needed prior to being destructed... Subclasses
824 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000825
826 // We need to destroy the loader before the derived Process class gets destroyed
827 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000828 m_dynamic_checkers_ap.reset();
829 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000830 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000831 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000832 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000833 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000834 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000835 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000836 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000837 m_queue_list.Clear();
838 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000839 std::vector<Notifications> empty_notifications;
840 m_notifications.swap(empty_notifications);
841 m_image_tokens.clear();
842 m_memory_cache.Clear();
843 m_allocated_memory_cache.Clear();
844 m_language_runtimes.clear();
845 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000846//#ifdef LLDB_CONFIGURATION_DEBUG
847// StreamFile s(stdout, false);
848// EventSP event_sp;
849// while (m_private_state_listener.GetNextEvent(event_sp))
850// {
851// event_sp->Dump (&s);
852// s.EOL();
853// }
854//#endif
855 // We have to be very careful here as the m_private_state_listener might
856 // contain events that have ProcessSP values in them which can keep this
857 // process around forever. These events need to be cleared out.
858 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000859 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
860 m_public_run_lock.SetStopped();
861 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
862 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000863 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864}
865
866void
867Process::RegisterNotificationCallbacks (const Notifications& callbacks)
868{
869 m_notifications.push_back(callbacks);
870 if (callbacks.initialize != NULL)
871 callbacks.initialize (callbacks.baton, this);
872}
873
874bool
875Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
876{
877 std::vector<Notifications>::iterator pos, end = m_notifications.end();
878 for (pos = m_notifications.begin(); pos != end; ++pos)
879 {
880 if (pos->baton == callbacks.baton &&
881 pos->initialize == callbacks.initialize &&
882 pos->process_state_changed == callbacks.process_state_changed)
883 {
884 m_notifications.erase(pos);
885 return true;
886 }
887 }
888 return false;
889}
890
891void
892Process::SynchronouslyNotifyStateChanged (StateType state)
893{
894 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
895 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
896 {
897 if (notification_pos->process_state_changed)
898 notification_pos->process_state_changed (notification_pos->baton, this, state);
899 }
900}
901
902// FIXME: We need to do some work on events before the general Listener sees them.
903// For instance if we are continuing from a breakpoint, we need to ensure that we do
904// the little "insert real insn, step & stop" trick. But we can't do that when the
905// event is delivered by the broadcaster - since that is done on the thread that is
906// waiting for new events, so if we needed more than one event for our handling, we would
907// stall. So instead we do it when we fetch the event off of the queue.
908//
909
910StateType
911Process::GetNextEvent (EventSP &event_sp)
912{
913 StateType state = eStateInvalid;
914
915 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
916 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
917
918 return state;
919}
920
Todd Fialaa3b89e22014-08-12 14:33:19 +0000921bool
922Process::SyncIOHandler (uint64_t timeout_msec)
923{
924 bool timed_out = false;
925
926 // don't sync (potentially context switch) in case where there is no process IO
927 if (m_process_input_reader)
928 {
929 TimeValue timeout = TimeValue::Now();
930 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
931
932 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
933
934 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
935 if(log)
936 {
937 if(timed_out)
938 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
939 else
940 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
941 }
942
943 // reset sync one-shot so it will be ready for next time
944 m_iohandler_sync.SetValue(false, eBroadcastNever);
945 }
946
947 return !timed_out;
948}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000949
950StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000951Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952{
Jim Ingham4b536182011-08-09 02:12:22 +0000953 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
954 // We have to actually check each event, and in the case of a stopped event check the restarted flag
955 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000956 if (event_sp_ptr)
957 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000958 StateType state = GetState();
959 // If we are exited or detached, we won't ever get back to any
960 // other valid state...
961 if (state == eStateDetached || state == eStateExited)
962 return state;
963
Daniel Malea9e9919f2013-10-09 16:56:28 +0000964 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
965 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000966 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
967 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000968
969 if (!wait_always &&
970 StateIsStoppedState(state, true) &&
971 StateIsStoppedState(GetPrivateState(), true)) {
972 if (log)
973 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
974 __FUNCTION__);
975 return state;
976 }
977
Jim Ingham4b536182011-08-09 02:12:22 +0000978 while (state != eStateInvalid)
979 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000980 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000981 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000982 if (event_sp_ptr && event_sp)
983 *event_sp_ptr = event_sp;
984
Jim Ingham4b536182011-08-09 02:12:22 +0000985 switch (state)
986 {
987 case eStateCrashed:
988 case eStateDetached:
989 case eStateExited:
990 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000991 // We need to toggle the run lock as this won't get done in
992 // SetPublicState() if the process is hijacked.
993 if (hijack_listener)
994 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000995 return state;
996 case eStateStopped:
997 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
998 continue;
999 else
Greg Clayton44d93782014-01-27 23:43:24 +00001000 {
1001 // We need to toggle the run lock as this won't get done in
1002 // SetPublicState() if the process is hijacked.
1003 if (hijack_listener)
1004 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001005 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001006 }
Jim Ingham4b536182011-08-09 02:12:22 +00001007 default:
1008 continue;
1009 }
1010 }
1011 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012}
1013
1014
1015StateType
1016Process::WaitForState
1017(
1018 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001019 const StateType *match_states,
1020 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021)
1022{
1023 EventSP event_sp;
1024 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001025 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001026 while (state != eStateInvalid)
1027 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001028 // If we are exited or detached, we won't ever get back to any
1029 // other valid state...
1030 if (state == eStateDetached || state == eStateExited)
1031 return state;
1032
Greg Clayton44d93782014-01-27 23:43:24 +00001033 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034
1035 for (i=0; i<num_match_states; ++i)
1036 {
1037 if (match_states[i] == state)
1038 return state;
1039 }
1040 }
1041 return state;
1042}
1043
Jim Ingham30f9b212010-10-11 23:53:14 +00001044bool
1045Process::HijackProcessEvents (Listener *listener)
1046{
1047 if (listener != NULL)
1048 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001049 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001050 }
1051 else
1052 return false;
1053}
1054
1055void
1056Process::RestoreProcessEvents ()
1057{
1058 RestoreBroadcaster();
1059}
1060
Jim Ingham0f16e732011-02-08 05:20:59 +00001061bool
1062Process::HijackPrivateProcessEvents (Listener *listener)
1063{
1064 if (listener != NULL)
1065 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001066 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001067 }
1068 else
1069 return false;
1070}
1071
1072void
1073Process::RestorePrivateProcessEvents ()
1074{
1075 m_private_state_broadcaster.RestoreBroadcaster();
1076}
1077
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001079Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080{
Greg Clayton5160ce52013-03-27 23:08:40 +00001081 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082
1083 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001084 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1085 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086
Greg Clayton44d93782014-01-27 23:43:24 +00001087 Listener *listener = hijack_listener;
1088 if (listener == NULL)
1089 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001090
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001092 if (listener->WaitForEventForBroadcasterWithType (timeout,
1093 this,
1094 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1095 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001096 {
1097 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1098 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1099 else if (log)
1100 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1101 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102
1103 if (log)
1104 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001105 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 StateAsCString(state));
1107 return state;
1108}
1109
1110Event *
1111Process::PeekAtStateChangedEvents ()
1112{
Greg Clayton5160ce52013-03-27 23:08:40 +00001113 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114
1115 if (log)
1116 log->Printf ("Process::%s...", __FUNCTION__);
1117
1118 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001119 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1120 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001121 if (log)
1122 {
1123 if (event_ptr)
1124 {
1125 log->Printf ("Process::%s (event_ptr) => %s",
1126 __FUNCTION__,
1127 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1128 }
1129 else
1130 {
1131 log->Printf ("Process::%s no events found",
1132 __FUNCTION__);
1133 }
1134 }
1135 return event_ptr;
1136}
1137
1138StateType
1139Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1140{
Greg Clayton5160ce52013-03-27 23:08:40 +00001141 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142
1143 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001144 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1145 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146
1147 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001148 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1149 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001150 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001151 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001152 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1153 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001154
1155 // This is a bit of a hack, but when we wait here we could very well return
1156 // to the command-line, and that could disable the log, which would render the
1157 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001159 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1160 __FUNCTION__, static_cast<const void *>(timeout),
1161 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162 return state;
1163}
1164
1165bool
1166Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1167{
Greg Clayton5160ce52013-03-27 23:08:40 +00001168 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001169
1170 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001171 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1172 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173
1174 if (control_only)
1175 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1176 else
1177 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1178}
1179
1180bool
1181Process::IsRunning () const
1182{
1183 return StateIsRunningState (m_public_state.GetValue());
1184}
1185
1186int
1187Process::GetExitStatus ()
1188{
1189 if (m_public_state.GetValue() == eStateExited)
1190 return m_exit_status;
1191 return -1;
1192}
1193
Greg Clayton85851dd2010-12-04 00:10:17 +00001194
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001195const char *
1196Process::GetExitDescription ()
1197{
1198 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1199 return m_exit_string.c_str();
1200 return NULL;
1201}
1202
Greg Clayton6779606a2011-01-22 23:43:18 +00001203bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204Process::SetExitStatus (int status, const char *cstr)
1205{
Greg Clayton5160ce52013-03-27 23:08:40 +00001206 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001207 if (log)
1208 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1209 status, status,
1210 cstr ? "\"" : "",
1211 cstr ? cstr : "NULL",
1212 cstr ? "\"" : "");
1213
Greg Clayton6779606a2011-01-22 23:43:18 +00001214 // We were already in the exited state
1215 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001216 {
Greg Clayton385d6032011-01-26 23:47:29 +00001217 if (log)
1218 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001219 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001220 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001221
1222 m_exit_status = status;
1223 if (cstr)
1224 m_exit_string = cstr;
1225 else
1226 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227
Greg Clayton6779606a2011-01-22 23:43:18 +00001228 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001229
Greg Clayton6779606a2011-01-22 23:43:18 +00001230 SetPrivateState (eStateExited);
1231 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001232}
1233
1234// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001235// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001236// found in the global target list (we want to be completely sure that the
1237// lldb_private::Process doesn't go away before we can deliver the signal.
1238bool
Greg Claytone4e45922011-11-16 05:37:56 +00001239Process::SetProcessExitStatus (void *callback_baton,
1240 lldb::pid_t pid,
1241 bool exited,
1242 int signo, // Zero for no signal
1243 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001244)
1245{
Greg Clayton5160ce52013-03-27 23:08:40 +00001246 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001247 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001248 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001249 callback_baton,
1250 pid,
1251 exited,
1252 signo,
1253 exit_status);
1254
1255 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256 {
Greg Clayton66111032010-06-23 01:19:29 +00001257 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001258 if (target_sp)
1259 {
1260 ProcessSP process_sp (target_sp->GetProcessSP());
1261 if (process_sp)
1262 {
1263 const char *signal_cstr = NULL;
1264 if (signo)
1265 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1266
1267 process_sp->SetExitStatus (exit_status, signal_cstr);
1268 }
1269 }
1270 return true;
1271 }
1272 return false;
1273}
1274
1275
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001276void
1277Process::UpdateThreadListIfNeeded ()
1278{
1279 const uint32_t stop_id = GetStopID();
1280 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1281 {
Greg Clayton2637f822011-11-17 01:23:07 +00001282 const StateType state = GetPrivateState();
1283 if (StateIsStoppedState (state, true))
1284 {
1285 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001286 // m_thread_list does have its own mutex, but we need to
1287 // hold onto the mutex between the call to UpdateThreadList(...)
1288 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001289 ThreadList &old_thread_list = m_thread_list;
1290 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001291 ThreadList new_thread_list(this);
1292 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001293 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001294 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001295 {
Jim Ingham09437922013-03-01 20:04:25 +00001296 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1297 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1298 // shutting us down, causing a deadlock.
1299 if (!m_destroy_in_process)
1300 {
1301 OperatingSystem *os = GetOperatingSystem ();
1302 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001303 {
1304 // Clear any old backing threads where memory threads might have been
1305 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001306 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001307 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001308 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001309
1310 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001311 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1312 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1313 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 +00001314 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001315 else
1316 {
1317 // No OS plug-in, the new thread list is the same as the real thread list
1318 new_thread_list = real_thread_list;
1319 }
Jim Ingham09437922013-03-01 20:04:25 +00001320 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001321
1322 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001323 m_thread_list.Update (new_thread_list);
1324 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001325
Jason Molenda4ff13262013-11-20 00:31:38 +00001326 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1327 {
1328 // Clear any extended threads that we may have accumulated previously
1329 m_extended_thread_list.Clear();
1330 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001331
1332 m_queue_list.Clear();
1333 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001334 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001335 }
Greg Clayton2637f822011-11-17 01:23:07 +00001336 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001337 }
1338}
1339
Jason Molenda5e8dce42013-12-13 00:29:16 +00001340void
1341Process::UpdateQueueListIfNeeded ()
1342{
1343 if (m_system_runtime_ap.get())
1344 {
1345 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1346 {
1347 const StateType state = GetPrivateState();
1348 if (StateIsStoppedState (state, true))
1349 {
1350 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1351 m_queue_list_stop_id = GetLastNaturalStopID();
1352 }
1353 }
1354 }
1355}
1356
Greg Claytona4d87472013-01-18 23:41:08 +00001357ThreadSP
1358Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1359{
1360 OperatingSystem *os = GetOperatingSystem ();
1361 if (os)
1362 return os->CreateThread(tid, context);
1363 return ThreadSP();
1364}
1365
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001366uint32_t
1367Process::GetNextThreadIndexID (uint64_t thread_id)
1368{
1369 return AssignIndexIDToThread(thread_id);
1370}
1371
1372bool
1373Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1374{
1375 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1376 if (iterator == m_thread_id_to_index_id_map.end())
1377 {
1378 return false;
1379 }
1380 else
1381 {
1382 return true;
1383 }
1384}
1385
1386uint32_t
1387Process::AssignIndexIDToThread(uint64_t thread_id)
1388{
1389 uint32_t result = 0;
1390 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1391 if (iterator == m_thread_id_to_index_id_map.end())
1392 {
1393 result = ++m_thread_index_id;
1394 m_thread_id_to_index_id_map[thread_id] = result;
1395 }
1396 else
1397 {
1398 result = iterator->second;
1399 }
1400
1401 return result;
1402}
1403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404StateType
1405Process::GetState()
1406{
1407 // If any other threads access this we will need a mutex for it
1408 return m_public_state.GetValue ();
1409}
1410
1411void
Jim Ingham221d51c2013-05-08 00:35:16 +00001412Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413{
Greg Clayton5160ce52013-03-27 23:08:40 +00001414 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001416 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001417 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001419
1420 // On the transition from Run to Stopped, we unlock the writer end of the
1421 // run lock. The lock gets locked in Resume, which is the public API
1422 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001423 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1424 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001425 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001426 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001427 if (log)
1428 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001429 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001430 }
1431 else
1432 {
1433 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1434 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001435 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001436 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001437 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001438 {
1439 if (log)
1440 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001441 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001442 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001443 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001444 }
1445 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001446}
1447
Jim Ingham3b8285d2012-04-19 01:40:33 +00001448Error
1449Process::Resume ()
1450{
Greg Clayton5160ce52013-03-27 23:08:40 +00001451 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001452 if (log)
1453 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001454 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001455 {
1456 Error error("Resume request failed - process still running.");
1457 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001458 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001459 return error;
1460 }
1461 return PrivateResume();
1462}
1463
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464StateType
1465Process::GetPrivateState ()
1466{
1467 return m_private_state.GetValue();
1468}
1469
1470void
1471Process::SetPrivateState (StateType new_state)
1472{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001473 if (m_finalize_called)
1474 return;
1475
Greg Clayton5160ce52013-03-27 23:08:40 +00001476 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477 bool state_changed = false;
1478
1479 if (log)
1480 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1481
Andrew Kaylor29d65742013-05-10 17:19:04 +00001482 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001483 Mutex::Locker locker(m_private_state.GetMutex());
1484
1485 const StateType old_state = m_private_state.GetValueNoLock ();
1486 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001487
Greg Claytonaa49c832013-05-03 22:25:56 +00001488 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1489 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1490 if (old_state_is_stopped != new_state_is_stopped)
1491 {
1492 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001493 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001494 else
Ed Maste64fad602013-07-29 20:58:06 +00001495 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001496 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001497
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 if (state_changed)
1499 {
1500 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001501 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001503 // Note, this currently assumes that all threads in the list
1504 // stop when the process stops. In the future we will want to
1505 // support a debugging model where some threads continue to run
1506 // while others are stopped. When that happens we will either need
1507 // a way for the thread list to identify which threads are stopping
1508 // or create a special thread list containing only threads which
1509 // actually stopped.
1510 //
1511 // The process plugin is responsible for managing the actual
1512 // behavior of the threads and should have stopped any threads
1513 // that are going to stop before we get here.
1514 m_thread_list.DidStop();
1515
Jim Ingham4b536182011-08-09 02:12:22 +00001516 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001517 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001518 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001519 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001520 }
1521 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001522 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1523 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1524 else
1525 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526 }
1527 else
1528 {
1529 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001530 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001531 }
1532}
1533
Jim Ingham0faa43f2011-11-08 03:00:11 +00001534void
1535Process::SetRunningUserExpression (bool on)
1536{
1537 m_mod_id.SetRunningUserExpression (on);
1538}
1539
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540addr_t
1541Process::GetImageInfoAddress()
1542{
1543 return LLDB_INVALID_ADDRESS;
1544}
1545
Greg Clayton8f343b02010-11-04 01:54:29 +00001546//----------------------------------------------------------------------
1547// LoadImage
1548//
1549// This function provides a default implementation that works for most
1550// unix variants. Any Process subclasses that need to do shared library
1551// loading differently should override LoadImage and UnloadImage and
1552// do what is needed.
1553//----------------------------------------------------------------------
1554uint32_t
1555Process::LoadImage (const FileSpec &image_spec, Error &error)
1556{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001557 char path[PATH_MAX];
1558 image_spec.GetPath(path, sizeof(path));
1559
Greg Clayton8f343b02010-11-04 01:54:29 +00001560 DynamicLoader *loader = GetDynamicLoader();
1561 if (loader)
1562 {
1563 error = loader->CanLoadImage();
1564 if (error.Fail())
1565 return LLDB_INVALID_IMAGE_TOKEN;
1566 }
1567
1568 if (error.Success())
1569 {
1570 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001571
1572 if (thread_sp)
1573 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001574 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001575
1576 if (frame_sp)
1577 {
1578 ExecutionContext exe_ctx;
1579 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001580 EvaluateExpressionOptions expr_options;
1581 expr_options.SetUnwindOnError(true);
1582 expr_options.SetIgnoreBreakpoints(true);
1583 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001584 expr_options.SetResultIsInternal(true);
1585
Greg Clayton8f343b02010-11-04 01:54:29 +00001586 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001587 expr.Printf(R"(
1588 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1589 the_result.image_ptr = dlopen ("%s", 2);
1590 if (the_result.image_ptr == (void *) 0x0)
1591 {
1592 the_result.error_str = dlerror();
1593 }
1594 else
1595 {
1596 the_result.error_str = (const char *) 0x0;
1597 }
1598 the_result;
1599 )",
1600 path);
1601 const char *prefix = R"(
1602 extern "C" void* dlopen (const char *path, int mode);
1603 extern "C" const char *dlerror (void);
1604 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001605 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001606 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001607 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001608 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001609 expr.GetData(),
1610 prefix,
1611 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001612 expr_error);
1613 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001614 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001615 error = result_valobj_sp->GetError();
1616 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001617 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001618 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001619 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1620 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001621 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001622 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1623 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1624 {
1625 uint32_t image_token = m_image_tokens.size();
1626 m_image_tokens.push_back (image_ptr);
1627 return image_token;
1628 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001629 else if (image_ptr == 0)
1630 {
Jim Ingham6971b862014-07-19 00:37:06 +00001631 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1632 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001633 {
Jim Ingham6971b862014-07-19 00:37:06 +00001634 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001635 {
Jim Inghamcf973792014-07-17 21:53:48 +00001636 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001637 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001638 if (error.Success() && num_chars > 0)
1639 {
1640 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001641 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001642 }
1643 }
1644 }
1645 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001646 }
1647 }
1648 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001649 else
1650 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001651 }
1652 }
1653 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001654 if (!error.AsCString())
1655 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001656 return LLDB_INVALID_IMAGE_TOKEN;
1657}
1658
1659//----------------------------------------------------------------------
1660// UnloadImage
1661//
1662// This function provides a default implementation that works for most
1663// unix variants. Any Process subclasses that need to do shared library
1664// loading differently should override LoadImage and UnloadImage and
1665// do what is needed.
1666//----------------------------------------------------------------------
1667Error
1668Process::UnloadImage (uint32_t image_token)
1669{
1670 Error error;
1671 if (image_token < m_image_tokens.size())
1672 {
1673 const addr_t image_addr = m_image_tokens[image_token];
1674 if (image_addr == LLDB_INVALID_ADDRESS)
1675 {
1676 error.SetErrorString("image already unloaded");
1677 }
1678 else
1679 {
1680 DynamicLoader *loader = GetDynamicLoader();
1681 if (loader)
1682 error = loader->CanLoadImage();
1683
1684 if (error.Success())
1685 {
1686 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001687
1688 if (thread_sp)
1689 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001690 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001691
1692 if (frame_sp)
1693 {
1694 ExecutionContext exe_ctx;
1695 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001696 EvaluateExpressionOptions expr_options;
1697 expr_options.SetUnwindOnError(true);
1698 expr_options.SetIgnoreBreakpoints(true);
1699 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001700 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001701 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001702 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001703 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001704 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001705 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001706 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001707 expr.GetData(),
1708 prefix,
1709 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001710 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001711 if (result_valobj_sp->GetError().Success())
1712 {
1713 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001714 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001715 {
1716 if (scalar.UInt(1))
1717 {
1718 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1719 }
1720 else
1721 {
1722 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1723 }
1724 }
1725 }
1726 else
1727 {
1728 error = result_valobj_sp->GetError();
1729 }
1730 }
1731 }
1732 }
1733 }
1734 }
1735 else
1736 {
1737 error.SetErrorString("invalid image token");
1738 }
1739 return error;
1740}
1741
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001742const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001743Process::GetABI()
1744{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001745 if (!m_abi_sp)
1746 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1747 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001748}
1749
Jim Ingham22777012010-09-23 02:01:19 +00001750LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001751Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001752{
1753 LanguageRuntimeCollection::iterator pos;
1754 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001755 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001756 {
Jim Inghamab175242012-03-10 00:22:19 +00001757 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001758
Jim Inghamab175242012-03-10 00:22:19 +00001759 m_language_runtimes[language] = runtime_sp;
1760 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001761 }
1762 else
1763 return (*pos).second.get();
1764}
1765
1766CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001767Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001768{
Jim Inghamab175242012-03-10 00:22:19 +00001769 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001770 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1771 return static_cast<CPPLanguageRuntime *> (runtime);
1772 return NULL;
1773}
1774
1775ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001776Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001777{
Jim Inghamab175242012-03-10 00:22:19 +00001778 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001779 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1780 return static_cast<ObjCLanguageRuntime *> (runtime);
1781 return NULL;
1782}
1783
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001784bool
1785Process::IsPossibleDynamicValue (ValueObject& in_value)
1786{
1787 if (in_value.IsDynamic())
1788 return false;
1789 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1790
1791 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1792 {
1793 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1794 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1795 }
1796
1797 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1798 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1799 return true;
1800
1801 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1802 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1803}
1804
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805BreakpointSiteList &
1806Process::GetBreakpointSiteList()
1807{
1808 return m_breakpoint_site_list;
1809}
1810
1811const BreakpointSiteList &
1812Process::GetBreakpointSiteList() const
1813{
1814 return m_breakpoint_site_list;
1815}
1816
1817
1818void
1819Process::DisableAllBreakpointSites ()
1820{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001821 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1822// bp_site->SetEnabled(true);
1823 DisableBreakpointSite(bp_site);
1824 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825}
1826
1827Error
1828Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1829{
1830 Error error (DisableBreakpointSiteByID (break_id));
1831
1832 if (error.Success())
1833 m_breakpoint_site_list.Remove(break_id);
1834
1835 return error;
1836}
1837
1838Error
1839Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1840{
1841 Error error;
1842 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1843 if (bp_site_sp)
1844 {
1845 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001846 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001847 }
1848 else
1849 {
Daniel Malead01b2952012-11-29 21:49:15 +00001850 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001851 }
1852
1853 return error;
1854}
1855
1856Error
1857Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1858{
1859 Error error;
1860 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1861 if (bp_site_sp)
1862 {
1863 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001864 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 }
1866 else
1867 {
Daniel Malead01b2952012-11-29 21:49:15 +00001868 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869 }
1870 return error;
1871}
1872
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001873lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001874Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001875{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001876 addr_t load_addr = LLDB_INVALID_ADDRESS;
1877
1878 bool show_error = true;
1879 switch (GetState())
1880 {
1881 case eStateInvalid:
1882 case eStateUnloaded:
1883 case eStateConnected:
1884 case eStateAttaching:
1885 case eStateLaunching:
1886 case eStateDetached:
1887 case eStateExited:
1888 show_error = false;
1889 break;
1890
1891 case eStateStopped:
1892 case eStateRunning:
1893 case eStateStepping:
1894 case eStateCrashed:
1895 case eStateSuspended:
1896 show_error = IsAlive();
1897 break;
1898 }
1899
1900 // Reset the IsIndirect flag here, in case the location changes from
1901 // pointing to a indirect symbol to a regular symbol.
1902 owner->SetIsIndirect (false);
1903
1904 if (owner->ShouldResolveIndirectFunctions())
1905 {
1906 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1907 if (symbol && symbol->IsIndirect())
1908 {
1909 Error error;
1910 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1911 if (!error.Success() && show_error)
1912 {
Greg Clayton44d93782014-01-27 23:43:24 +00001913 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1914 symbol->GetAddress().GetLoadAddress(&m_target),
1915 owner->GetBreakpoint().GetID(),
1916 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001917 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001918 return LLDB_INVALID_BREAK_ID;
1919 }
1920 Address resolved_address(load_addr);
1921 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1922 owner->SetIsIndirect(true);
1923 }
1924 else
1925 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1926 }
1927 else
1928 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1929
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001930 if (load_addr != LLDB_INVALID_ADDRESS)
1931 {
1932 BreakpointSiteSP bp_site_sp;
1933
1934 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1935 // create a new breakpoint site and add it.
1936
1937 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1938
1939 if (bp_site_sp)
1940 {
1941 bp_site_sp->AddOwner (owner);
1942 owner->SetBreakpointSite (bp_site_sp);
1943 return bp_site_sp->GetID();
1944 }
1945 else
1946 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001947 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948 if (bp_site_sp)
1949 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001950 Error error = EnableBreakpointSite (bp_site_sp.get());
1951 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 {
1953 owner->SetBreakpointSite (bp_site_sp);
1954 return m_breakpoint_site_list.Add (bp_site_sp);
1955 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001956 else
1957 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001958 if (show_error)
1959 {
1960 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001961 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1962 load_addr,
1963 owner->GetBreakpoint().GetID(),
1964 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001965 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001966 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001967 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001968 }
1969 }
1970 }
1971 // We failed to enable the breakpoint
1972 return LLDB_INVALID_BREAK_ID;
1973
1974}
1975
1976void
1977Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1978{
1979 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1980 if (num_owners == 0)
1981 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001982 // Don't try to disable the site if we don't have a live process anymore.
1983 if (IsAlive())
1984 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001985 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1986 }
1987}
1988
1989
1990size_t
1991Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1992{
1993 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00001994 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001995
Jim Ingham20c77192011-06-29 19:42:28 +00001996 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00001998 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
1999 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002001 addr_t intersect_addr;
2002 size_t intersect_size;
2003 size_t opcode_offset;
2004 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002005 {
2006 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2007 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002008 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002009 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002010 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002011 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002013 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014 }
2015 return bytes_removed;
2016}
2017
2018
Greg Claytonded470d2011-03-19 01:12:21 +00002019
2020size_t
2021Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2022{
2023 PlatformSP platform_sp (m_target.GetPlatform());
2024 if (platform_sp)
2025 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2026 return 0;
2027}
2028
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029Error
2030Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2031{
2032 Error error;
2033 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002034 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002035 const addr_t bp_addr = bp_site->GetLoadAddress();
2036 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002037 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038 if (bp_site->IsEnabled())
2039 {
2040 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002041 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 +00002042 return error;
2043 }
2044
2045 if (bp_addr == LLDB_INVALID_ADDRESS)
2046 {
2047 error.SetErrorString("BreakpointSite contains an invalid load address.");
2048 return error;
2049 }
2050 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2051 // trap for the breakpoint site
2052 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2053
2054 if (bp_opcode_size == 0)
2055 {
Daniel Malead01b2952012-11-29 21:49:15 +00002056 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002057 }
2058 else
2059 {
2060 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2061
2062 if (bp_opcode_bytes == NULL)
2063 {
2064 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2065 return error;
2066 }
2067
2068 // Save the original opcode by reading it
2069 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2070 {
2071 // Write a software breakpoint in place of the original opcode
2072 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2073 {
2074 uint8_t verify_bp_opcode_bytes[64];
2075 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2076 {
2077 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2078 {
2079 bp_site->SetEnabled(true);
2080 bp_site->SetType (BreakpointSite::eSoftware);
2081 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002082 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002083 bp_site->GetID(),
2084 (uint64_t)bp_addr);
2085 }
2086 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002087 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088 }
2089 else
2090 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2091 }
2092 else
2093 error.SetErrorString("Unable to write breakpoint trap to memory.");
2094 }
2095 else
2096 error.SetErrorString("Unable to read memory at breakpoint address.");
2097 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002098 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002099 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002100 bp_site->GetID(),
2101 (uint64_t)bp_addr,
2102 error.AsCString());
2103 return error;
2104}
2105
2106Error
2107Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2108{
2109 Error error;
2110 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002111 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112 addr_t bp_addr = bp_site->GetLoadAddress();
2113 lldb::user_id_t breakID = bp_site->GetID();
2114 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002115 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116
2117 if (bp_site->IsHardware())
2118 {
2119 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2120 }
2121 else if (bp_site->IsEnabled())
2122 {
2123 const size_t break_op_size = bp_site->GetByteSize();
2124 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2125 if (break_op_size > 0)
2126 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002127 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002128 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002129 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002130 bool break_op_found = false;
2131
2132 // Read the breakpoint opcode
2133 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2134 {
2135 bool verify = false;
2136 // Make sure we have the a breakpoint opcode exists at this address
2137 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2138 {
2139 break_op_found = true;
2140 // We found a valid breakpoint opcode at this address, now restore
2141 // the saved opcode.
2142 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2143 {
2144 verify = true;
2145 }
2146 else
2147 error.SetErrorString("Memory write failed when restoring original opcode.");
2148 }
2149 else
2150 {
2151 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2152 // Set verify to true and so we can check if the original opcode has already been restored
2153 verify = true;
2154 }
2155
2156 if (verify)
2157 {
Greg Claytonc982c762010-07-09 20:39:50 +00002158 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002159 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002160 // Verify that our original opcode made it back to the inferior
2161 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2162 {
2163 // compare the memory we just read with the original opcode
2164 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2165 {
2166 // SUCCESS
2167 bp_site->SetEnabled(false);
2168 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002169 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 +00002170 return error;
2171 }
2172 else
2173 {
2174 if (break_op_found)
2175 error.SetErrorString("Failed to restore original opcode.");
2176 }
2177 }
2178 else
2179 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2180 }
2181 }
2182 else
2183 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2184 }
2185 }
2186 else
2187 {
2188 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002189 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 +00002190 return error;
2191 }
2192
2193 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002194 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002195 bp_site->GetID(),
2196 (uint64_t)bp_addr,
2197 error.AsCString());
2198 return error;
2199
2200}
2201
Greg Clayton58be07b2011-01-07 06:08:19 +00002202// Uncomment to verify memory caching works after making changes to caching code
2203//#define VERIFY_MEMORY_READS
2204
Sean Callanan64c0cf22012-06-07 22:26:42 +00002205size_t
2206Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2207{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002208 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002209 if (!GetDisableMemoryCache())
2210 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002211#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002212 // Memory caching is enabled, with debug verification
2213
2214 if (buf && size)
2215 {
2216 // Uncomment the line below to make sure memory caching is working.
2217 // I ran this through the test suite and got no assertions, so I am
2218 // pretty confident this is working well. If any changes are made to
2219 // memory caching, uncomment the line below and test your changes!
2220
2221 // Verify all memory reads by using the cache first, then redundantly
2222 // reading the same memory from the inferior and comparing to make sure
2223 // everything is exactly the same.
2224 std::string verify_buf (size, '\0');
2225 assert (verify_buf.size() == size);
2226 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2227 Error verify_error;
2228 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2229 assert (cache_bytes_read == verify_bytes_read);
2230 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2231 assert (verify_error.Success() == error.Success());
2232 return cache_bytes_read;
2233 }
2234 return 0;
2235#else // !defined(VERIFY_MEMORY_READS)
2236 // Memory caching is enabled, without debug verification
2237
2238 return m_memory_cache.Read (addr, buf, size, error);
2239#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002240 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002241 else
2242 {
2243 // Memory caching is disabled
2244
2245 return ReadMemoryFromInferior (addr, buf, size, error);
2246 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002247}
Greg Clayton58be07b2011-01-07 06:08:19 +00002248
Greg Clayton4c82d422012-05-18 23:20:01 +00002249size_t
2250Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2251{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002252 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002253 out_str.clear();
2254 addr_t curr_addr = addr;
2255 while (1)
2256 {
2257 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2258 if (length == 0)
2259 break;
2260 out_str.append(buf, length);
2261 // If we got "length - 1" bytes, we didn't get the whole C string, we
2262 // need to read some more characters
2263 if (length == sizeof(buf) - 1)
2264 curr_addr += length;
2265 else
2266 break;
2267 }
2268 return out_str.size();
2269}
2270
Greg Clayton58be07b2011-01-07 06:08:19 +00002271
2272size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002273Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2274 size_t type_width)
2275{
2276 size_t total_bytes_read = 0;
2277 if (dst && max_bytes && type_width && max_bytes >= type_width)
2278 {
2279 // Ensure a null terminator independent of the number of bytes that is read.
2280 memset (dst, 0, max_bytes);
2281 size_t bytes_left = max_bytes - type_width;
2282
2283 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2284 assert(sizeof(terminator) >= type_width &&
2285 "Attempting to validate a string with more than 4 bytes per character!");
2286
2287 addr_t curr_addr = addr;
2288 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2289 char *curr_dst = dst;
2290
2291 error.Clear();
2292 while (bytes_left > 0 && error.Success())
2293 {
2294 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2295 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2296 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2297
2298 if (bytes_read == 0)
2299 break;
2300
2301 // Search for a null terminator of correct size and alignment in bytes_read
2302 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2303 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2304 if (::strncmp(&dst[i], terminator, type_width) == 0)
2305 {
2306 error.Clear();
2307 return i;
2308 }
2309
2310 total_bytes_read += bytes_read;
2311 curr_dst += bytes_read;
2312 curr_addr += bytes_read;
2313 bytes_left -= bytes_read;
2314 }
2315 }
2316 else
2317 {
2318 if (max_bytes)
2319 error.SetErrorString("invalid arguments");
2320 }
2321 return total_bytes_read;
2322}
2323
2324// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2325// null terminators.
2326size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002327Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002328{
2329 size_t total_cstr_len = 0;
2330 if (dst && dst_max_len)
2331 {
Greg Claytone91b7952011-12-15 03:14:23 +00002332 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002333 // NULL out everything just to be safe
2334 memset (dst, 0, dst_max_len);
2335 Error error;
2336 addr_t curr_addr = addr;
2337 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2338 size_t bytes_left = dst_max_len - 1;
2339 char *curr_dst = dst;
2340
2341 while (bytes_left > 0)
2342 {
2343 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2344 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2345 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2346
2347 if (bytes_read == 0)
2348 {
Greg Claytone91b7952011-12-15 03:14:23 +00002349 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002350 dst[total_cstr_len] = '\0';
2351 break;
2352 }
2353 const size_t len = strlen(curr_dst);
2354
2355 total_cstr_len += len;
2356
2357 if (len < bytes_to_read)
2358 break;
2359
2360 curr_dst += bytes_read;
2361 curr_addr += bytes_read;
2362 bytes_left -= bytes_read;
2363 }
2364 }
Greg Claytone91b7952011-12-15 03:14:23 +00002365 else
2366 {
2367 if (dst == NULL)
2368 result_error.SetErrorString("invalid arguments");
2369 else
2370 result_error.Clear();
2371 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002372 return total_cstr_len;
2373}
2374
2375size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002376Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2377{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378 if (buf == NULL || size == 0)
2379 return 0;
2380
2381 size_t bytes_read = 0;
2382 uint8_t *bytes = (uint8_t *)buf;
2383
2384 while (bytes_read < size)
2385 {
2386 const size_t curr_size = size - bytes_read;
2387 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2388 bytes + bytes_read,
2389 curr_size,
2390 error);
2391 bytes_read += curr_bytes_read;
2392 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2393 break;
2394 }
2395
2396 // Replace any software breakpoint opcodes that fall into this range back
2397 // into "buf" before we return
2398 if (bytes_read > 0)
2399 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2400 return bytes_read;
2401}
2402
Greg Clayton58a4c462010-12-16 20:01:20 +00002403uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002404Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002405{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002406 Scalar scalar;
2407 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2408 return scalar.ULongLong(fail_value);
2409 return fail_value;
2410}
2411
2412addr_t
2413Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2414{
2415 Scalar scalar;
2416 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2417 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2418 return LLDB_INVALID_ADDRESS;
2419}
2420
2421
2422bool
2423Process::WritePointerToMemory (lldb::addr_t vm_addr,
2424 lldb::addr_t ptr_value,
2425 Error &error)
2426{
2427 Scalar scalar;
2428 const uint32_t addr_byte_size = GetAddressByteSize();
2429 if (addr_byte_size <= 4)
2430 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002431 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002432 scalar = ptr_value;
2433 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002434}
2435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436size_t
2437Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2438{
2439 size_t bytes_written = 0;
2440 const uint8_t *bytes = (const uint8_t *)buf;
2441
2442 while (bytes_written < size)
2443 {
2444 const size_t curr_size = size - bytes_written;
2445 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2446 bytes + bytes_written,
2447 curr_size,
2448 error);
2449 bytes_written += curr_bytes_written;
2450 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2451 break;
2452 }
2453 return bytes_written;
2454}
2455
2456size_t
2457Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2458{
Greg Clayton58be07b2011-01-07 06:08:19 +00002459#if defined (ENABLE_MEMORY_CACHING)
2460 m_memory_cache.Flush (addr, size);
2461#endif
2462
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463 if (buf == NULL || size == 0)
2464 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002465
Jim Ingham4b536182011-08-09 02:12:22 +00002466 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002467
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468 // We need to write any data that would go where any current software traps
2469 // (enabled software breakpoints) any software traps (breakpoints) that we
2470 // may have placed in our tasks memory.
2471
Greg Claytond8cf1a12013-06-12 00:46:38 +00002472 BreakpointSiteList bp_sites_in_range;
2473
2474 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002476 // No breakpoint sites overlap
2477 if (bp_sites_in_range.IsEmpty())
2478 return WriteMemoryPrivate (addr, buf, size, error);
2479 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002481 const uint8_t *ubuf = (const uint8_t *)buf;
2482 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483
Greg Claytond8cf1a12013-06-12 00:46:38 +00002484 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2485
2486 if (error.Success())
2487 {
2488 addr_t intersect_addr;
2489 size_t intersect_size;
2490 size_t opcode_offset;
2491 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2492 assert(intersects);
2493 assert(addr <= intersect_addr && intersect_addr < addr + size);
2494 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2495 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2496
2497 // Check for bytes before this breakpoint
2498 const addr_t curr_addr = addr + bytes_written;
2499 if (intersect_addr > curr_addr)
2500 {
2501 // There are some bytes before this breakpoint that we need to
2502 // just write to memory
2503 size_t curr_size = intersect_addr - curr_addr;
2504 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2505 ubuf + bytes_written,
2506 curr_size,
2507 error);
2508 bytes_written += curr_bytes_written;
2509 if (curr_bytes_written != curr_size)
2510 {
2511 // We weren't able to write all of the requested bytes, we
2512 // are done looping and will return the number of bytes that
2513 // we have written so far.
2514 if (error.Success())
2515 error.SetErrorToGenericError();
2516 }
2517 }
2518 // Now write any bytes that would cover up any software breakpoints
2519 // directly into the breakpoint opcode buffer
2520 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2521 bytes_written += intersect_size;
2522 }
2523 });
2524
2525 if (bytes_written < size)
2526 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2527 ubuf + bytes_written,
2528 size - bytes_written,
2529 error);
2530 }
2531 }
2532 else
2533 {
2534 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002535 }
2536
2537 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002538 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002539}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002540
2541size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002542Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002543{
2544 if (byte_size == UINT32_MAX)
2545 byte_size = scalar.GetByteSize();
2546 if (byte_size > 0)
2547 {
2548 uint8_t buf[32];
2549 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2550 if (mem_size > 0)
2551 return WriteMemory(addr, buf, mem_size, error);
2552 else
2553 error.SetErrorString ("failed to get scalar as memory data");
2554 }
2555 else
2556 {
2557 error.SetErrorString ("invalid scalar value");
2558 }
2559 return 0;
2560}
2561
2562size_t
2563Process::ReadScalarIntegerFromMemory (addr_t addr,
2564 uint32_t byte_size,
2565 bool is_signed,
2566 Scalar &scalar,
2567 Error &error)
2568{
Greg Clayton7060f892013-05-01 23:41:30 +00002569 uint64_t uval = 0;
2570 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002571 {
Greg Clayton7060f892013-05-01 23:41:30 +00002572 error.SetErrorString ("byte size is zero");
2573 }
2574 else if (byte_size & (byte_size - 1))
2575 {
2576 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2577 }
2578 else if (byte_size <= sizeof(uval))
2579 {
2580 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002581 if (bytes_read == byte_size)
2582 {
2583 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002584 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002585 if (byte_size <= 4)
2586 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002587 else
Greg Clayton7060f892013-05-01 23:41:30 +00002588 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002589 if (is_signed)
2590 scalar.SignExtend(byte_size * 8);
2591 return bytes_read;
2592 }
2593 }
2594 else
2595 {
2596 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2597 }
2598 return 0;
2599}
2600
Greg Claytond495c532011-05-17 03:37:42 +00002601#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602addr_t
2603Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2604{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002605 if (GetPrivateState() != eStateStopped)
2606 return LLDB_INVALID_ADDRESS;
2607
Greg Claytond495c532011-05-17 03:37:42 +00002608#if defined (USE_ALLOCATE_MEMORY_CACHE)
2609 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2610#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002611 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002612 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002613 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002614 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 +00002615 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002616 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002617 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002618 m_mod_id.GetStopID(),
2619 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002620 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002621#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622}
2623
Sean Callanan90539452011-09-20 23:01:51 +00002624bool
2625Process::CanJIT ()
2626{
Sean Callanana7b443a2012-02-14 22:50:38 +00002627 if (m_can_jit == eCanJITDontKnow)
2628 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002629 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002630 Error err;
2631
2632 uint64_t allocated_memory = AllocateMemory(8,
2633 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2634 err);
2635
2636 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002637 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002638 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002639 if (log)
2640 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2641 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002642 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002643 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002644 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002645 if (log)
2646 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2647 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002648
2649 DeallocateMemory (allocated_memory);
2650 }
2651
Sean Callanan90539452011-09-20 23:01:51 +00002652 return m_can_jit == eCanJITYes;
2653}
2654
2655void
2656Process::SetCanJIT (bool can_jit)
2657{
2658 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2659}
2660
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002661Error
2662Process::DeallocateMemory (addr_t ptr)
2663{
Greg Claytond495c532011-05-17 03:37:42 +00002664 Error error;
2665#if defined (USE_ALLOCATE_MEMORY_CACHE)
2666 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2667 {
Daniel Malead01b2952012-11-29 21:49:15 +00002668 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002669 }
2670#else
2671 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002672
Greg Clayton5160ce52013-03-27 23:08:40 +00002673 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002674 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002675 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 +00002676 ptr,
2677 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002678 m_mod_id.GetStopID(),
2679 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002680#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002681 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002682}
2683
Han Ming Ongc811d382012-11-17 00:33:14 +00002684
Greg Claytonc9660542012-02-05 02:38:54 +00002685ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002686Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002687 lldb::addr_t header_addr,
2688 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002689{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002690 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002691 if (module_sp)
2692 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002693 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002694 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002695 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002696 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002697 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002698 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002699}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002700
2701Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002702Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002703{
2704 Error error;
2705 error.SetErrorString("watchpoints are not supported");
2706 return error;
2707}
2708
2709Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002710Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711{
2712 Error error;
2713 error.SetErrorString("watchpoints are not supported");
2714 return error;
2715}
2716
2717StateType
2718Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2719{
2720 StateType state;
2721 // Now wait for the process to launch and return control to us, and then
2722 // call DidLaunch:
2723 while (1)
2724 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002725 event_sp.reset();
2726 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2727
Greg Clayton2637f822011-11-17 01:23:07 +00002728 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002730
2731 // If state is invalid, then we timed out
2732 if (state == eStateInvalid)
2733 break;
2734
2735 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736 HandlePrivateEvent (event_sp);
2737 }
2738 return state;
2739}
2740
2741Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002742Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743{
2744 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002746 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002747 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002748 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002749 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002750 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002751
Greg Claytonaa149cb2011-08-11 02:48:45 +00002752 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 if (exe_module)
2754 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002755 char local_exec_file_path[PATH_MAX];
2756 char platform_exec_file_path[PATH_MAX];
2757 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2758 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759 if (exe_module->GetFileSpec().Exists())
2760 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002761 // Install anything that might need to be installed prior to launching.
2762 // For host systems, this will do nothing, but if we are connected to a
2763 // remote platform it will install any needed binaries
2764 error = GetTarget().Install(&launch_info);
2765 if (error.Fail())
2766 return error;
2767
Greg Clayton71337622011-02-24 22:24:29 +00002768 if (PrivateStateThreadIsValid ())
2769 PausePrivateStateThread ();
2770
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002771 error = WillLaunch (exe_module);
2772 if (error.Success())
2773 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002774 const bool restarted = false;
2775 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002776 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777
Ed Maste64fad602013-07-29 20:58:06 +00002778 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002779 {
2780 // Now launch using these arguments.
2781 error = DoLaunch (exe_module, launch_info);
2782 }
2783 else
2784 {
2785 // This shouldn't happen
2786 error.SetErrorString("failed to acquire process run lock");
2787 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788
2789 if (error.Fail())
2790 {
2791 if (GetID() != LLDB_INVALID_PROCESS_ID)
2792 {
2793 SetID (LLDB_INVALID_PROCESS_ID);
2794 const char *error_string = error.AsCString();
2795 if (error_string == NULL)
2796 error_string = "launch failed";
2797 SetExitStatus (-1, error_string);
2798 }
2799 }
2800 else
2801 {
2802 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002803 TimeValue timeout_time;
2804 timeout_time = TimeValue::Now();
2805 timeout_time.OffsetWithSeconds(10);
2806 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807
Greg Clayton1a38ea72011-06-22 01:42:17 +00002808 if (state == eStateInvalid || event_sp.get() == NULL)
2809 {
2810 // We were able to launch the process, but we failed to
2811 // catch the initial stop.
2812 SetExitStatus (0, "failed to catch stop after launch");
2813 Destroy();
2814 }
2815 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002817
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818 DidLaunch ();
2819
Greg Claytonc859e2d2012-02-13 23:10:39 +00002820 DynamicLoader *dyld = GetDynamicLoader ();
2821 if (dyld)
2822 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002823
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002824 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002825
Jason Molendaeef51062013-11-05 03:57:19 +00002826 SystemRuntime *system_runtime = GetSystemRuntime ();
2827 if (system_runtime)
2828 system_runtime->DidLaunch();
2829
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002830 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002831 // This delays passing the stopped event to listeners till DidLaunch gets
2832 // a chance to complete...
2833 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002834
2835 if (PrivateStateThreadIsValid ())
2836 ResumePrivateStateThread ();
2837 else
2838 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 }
2840 else if (state == eStateExited)
2841 {
2842 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2843 // not likely to work, and return an invalid pid.
2844 HandlePrivateEvent (event_sp);
2845 }
2846 }
2847 }
2848 }
2849 else
2850 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002851 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 }
2853 }
2854 return error;
2855}
2856
Greg Claytonc3776bf2012-02-09 06:16:32 +00002857
2858Error
2859Process::LoadCore ()
2860{
2861 Error error = DoLoadCore();
2862 if (error.Success())
2863 {
2864 if (PrivateStateThreadIsValid ())
2865 ResumePrivateStateThread ();
2866 else
2867 StartPrivateStateThread ();
2868
Greg Claytonc859e2d2012-02-13 23:10:39 +00002869 DynamicLoader *dyld = GetDynamicLoader ();
2870 if (dyld)
2871 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002872
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002873 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002874
Jason Molendaeef51062013-11-05 03:57:19 +00002875 SystemRuntime *system_runtime = GetSystemRuntime ();
2876 if (system_runtime)
2877 system_runtime->DidAttach();
2878
Greg Claytonc859e2d2012-02-13 23:10:39 +00002879 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002880 // We successfully loaded a core file, now pretend we stopped so we can
2881 // show all of the threads in the core file and explore the crashed
2882 // state.
2883 SetPrivateState (eStateStopped);
2884
2885 }
2886 return error;
2887}
2888
Greg Claytonc859e2d2012-02-13 23:10:39 +00002889DynamicLoader *
2890Process::GetDynamicLoader ()
2891{
2892 if (m_dyld_ap.get() == NULL)
2893 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2894 return m_dyld_ap.get();
2895}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002896
Todd Fialaaf245d12014-06-30 21:05:18 +00002897const lldb::DataBufferSP
2898Process::GetAuxvData()
2899{
2900 return DataBufferSP ();
2901}
2902
Andrew MacPherson17220c12014-03-05 10:12:43 +00002903JITLoaderList &
2904Process::GetJITLoaders ()
2905{
2906 if (!m_jit_loaders_ap)
2907 {
2908 m_jit_loaders_ap.reset(new JITLoaderList());
2909 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2910 }
2911 return *m_jit_loaders_ap;
2912}
2913
Jason Molendaeef51062013-11-05 03:57:19 +00002914SystemRuntime *
2915Process::GetSystemRuntime ()
2916{
2917 if (m_system_runtime_ap.get() == NULL)
2918 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2919 return m_system_runtime_ap.get();
2920}
2921
Todd Fiala76e0fc92014-08-27 22:58:26 +00002922Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
2923 NextEventAction (process),
2924 m_exec_count (exec_count)
2925{
2926 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2927 if (log)
2928 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
2929}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002930
Jim Inghambb3a2832011-01-29 01:49:25 +00002931Process::NextEventAction::EventActionResult
2932Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002933{
Todd Fiala76e0fc92014-08-27 22:58:26 +00002934 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2935
Jim Inghambb3a2832011-01-29 01:49:25 +00002936 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00002937 if (log)
2938 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
2939
2940 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002941 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002942 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002943 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002944 return eEventActionRetry;
2945
2946 case eStateStopped:
2947 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002948 {
2949 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002950 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002951 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002952 // We don't want these events to be reported, so go set the ShouldReportStop here:
2953 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2954
Greg Claytonc9ed4782011-11-12 02:10:56 +00002955 if (m_exec_count > 0)
2956 {
2957 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00002958
2959 if (log)
2960 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
2961
Jim Ingham221d51c2013-05-08 00:35:16 +00002962 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002963 return eEventActionRetry;
2964 }
2965 else
2966 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00002967 if (log)
2968 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
2969
Greg Claytonc9ed4782011-11-12 02:10:56 +00002970 m_process->CompleteAttach ();
2971 return eEventActionSuccess;
2972 }
2973 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002974 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002975
Greg Clayton513c26c2011-01-29 07:10:55 +00002976 default:
2977 case eStateExited:
2978 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002979 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002980 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002981
2982 m_exit_string.assign ("No valid Process");
2983 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002984}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002985
Jim Inghambb3a2832011-01-29 01:49:25 +00002986Process::NextEventAction::EventActionResult
2987Process::AttachCompletionHandler::HandleBeingInterrupted()
2988{
2989 return eEventActionSuccess;
2990}
2991
2992const char *
2993Process::AttachCompletionHandler::GetExitString ()
2994{
2995 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002996}
2997
2998Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002999Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003000{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003002 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003003 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003004 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003005 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003006 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003007
Greg Clayton144f3a92011-11-15 03:53:30 +00003008 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003009 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003010 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003011 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003012 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003013
Greg Clayton144f3a92011-11-15 03:53:30 +00003014 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003015 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003016 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3017
3018 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003019 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003020 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3021 if (error.Success())
3022 {
Ed Maste64fad602013-07-29 20:58:06 +00003023 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003024 {
3025 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003026 const bool restarted = false;
3027 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003028 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003029 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003030 }
3031 else
3032 {
3033 // This shouldn't happen
3034 error.SetErrorString("failed to acquire process run lock");
3035 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003036
Greg Clayton144f3a92011-11-15 03:53:30 +00003037 if (error.Fail())
3038 {
3039 if (GetID() != LLDB_INVALID_PROCESS_ID)
3040 {
3041 SetID (LLDB_INVALID_PROCESS_ID);
3042 if (error.AsCString() == NULL)
3043 error.SetErrorString("attach failed");
3044
3045 SetExitStatus(-1, error.AsCString());
3046 }
3047 }
3048 else
3049 {
3050 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3051 StartPrivateStateThread();
3052 }
3053 return error;
3054 }
Greg Claytone996fd32011-03-08 22:40:15 +00003055 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003056 else
Greg Claytone996fd32011-03-08 22:40:15 +00003057 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003058 ProcessInstanceInfoList process_infos;
3059 PlatformSP platform_sp (m_target.GetPlatform ());
3060
3061 if (platform_sp)
3062 {
3063 ProcessInstanceInfoMatch match_info;
3064 match_info.GetProcessInfo() = attach_info;
3065 match_info.SetNameMatchType (eNameMatchEquals);
3066 platform_sp->FindProcesses (match_info, process_infos);
3067 const uint32_t num_matches = process_infos.GetSize();
3068 if (num_matches == 1)
3069 {
3070 attach_pid = process_infos.GetProcessIDAtIndex(0);
3071 // Fall through and attach using the above process ID
3072 }
3073 else
3074 {
3075 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3076 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003077 {
3078 StreamString s;
3079 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3080 for (size_t i = 0; i < num_matches; i++)
3081 {
3082 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3083 }
3084 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3085 process_name,
3086 s.GetData());
3087 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003088 else
3089 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3090 }
3091 }
3092 else
3093 {
3094 error.SetErrorString ("invalid platform, can't find processes by name");
3095 return error;
3096 }
Greg Claytone996fd32011-03-08 22:40:15 +00003097 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003098 }
3099 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003100 {
3101 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003102 }
3103 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003104
3105 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003106 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003107 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003108 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003109 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003110
Ed Maste64fad602013-07-29 20:58:06 +00003111 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003112 {
3113 // Now attach using these arguments.
3114 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003115 const bool restarted = false;
3116 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003117 error = DoAttachToProcessWithID (attach_pid, attach_info);
3118 }
3119 else
3120 {
3121 // This shouldn't happen
3122 error.SetErrorString("failed to acquire process run lock");
3123 }
3124
Greg Clayton144f3a92011-11-15 03:53:30 +00003125 if (error.Success())
3126 {
3127
3128 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3129 StartPrivateStateThread();
3130 }
3131 else
Greg Claytone996fd32011-03-08 22:40:15 +00003132 {
3133 if (GetID() != LLDB_INVALID_PROCESS_ID)
3134 {
3135 SetID (LLDB_INVALID_PROCESS_ID);
3136 const char *error_string = error.AsCString();
3137 if (error_string == NULL)
3138 error_string = "attach failed";
3139
3140 SetExitStatus(-1, error_string);
3141 }
3142 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003143 }
3144 }
3145 return error;
3146}
3147
Greg Clayton93d3c8332011-02-16 04:46:07 +00003148void
3149Process::CompleteAttach ()
3150{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003151 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3152 if (log)
3153 log->Printf ("Process::%s()", __FUNCTION__);
3154
Greg Clayton93d3c8332011-02-16 04:46:07 +00003155 // Let the process subclass figure out at much as it can about the process
3156 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003157 ArchSpec process_arch;
3158 DidAttach(process_arch);
3159
3160 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003161 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003162 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003163 if (log)
3164 {
3165 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3166 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3167 __FUNCTION__,
3168 triple_str ? triple_str : "<null>");
3169 }
3170 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003171
Jim Ingham4299fdb2011-09-15 01:10:17 +00003172 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3173 // the same as the one we've already set, switch architectures.
3174 PlatformSP platform_sp (m_target.GetPlatform ());
3175 assert (platform_sp.get());
3176 if (platform_sp)
3177 {
Greg Clayton70512312012-05-08 01:45:38 +00003178 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003179 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003180 {
3181 ArchSpec platform_arch;
3182 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3183 if (platform_sp)
3184 {
3185 m_target.SetPlatform (platform_sp);
3186 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003187 if (log)
3188 log->Printf ("Process::%s switching platform to %s and architecture to %s based on info from attach", __FUNCTION__, platform_sp->GetName().AsCString (""), platform_arch.GetTriple().getTriple().c_str ());
Greg Clayton70512312012-05-08 01:45:38 +00003189 }
3190 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003191 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003192 {
3193 ProcessInstanceInfo process_info;
3194 platform_sp->GetProcessInfo (GetID(), process_info);
3195 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003196 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003197 {
Greg Clayton70512312012-05-08 01:45:38 +00003198 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003199 if (log)
3200 log->Printf ("Process::%s switching architecture to %s based on info the platform retrieved for pid %" PRIu64, __FUNCTION__, process_arch.GetTriple().getTriple().c_str (), GetID ());
3201 }
Greg Clayton70512312012-05-08 01:45:38 +00003202 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003203 }
3204
3205 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003206 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003207 DynamicLoader *dyld = GetDynamicLoader ();
3208 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003209 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003210 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003211 if (log)
3212 {
3213 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3214 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3215 __FUNCTION__,
3216 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3217 dyld->GetPluginName().AsCString ("<unnamed>"));
3218 }
3219 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003220
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003221 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003222
Jason Molendaeef51062013-11-05 03:57:19 +00003223 SystemRuntime *system_runtime = GetSystemRuntime ();
3224 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003225 {
Jason Molendaeef51062013-11-05 03:57:19 +00003226 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003227 if (log)
3228 {
3229 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3230 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3231 __FUNCTION__,
3232 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3233 system_runtime->GetPluginName().AsCString("<unnamed>"));
3234 }
3235 }
Jason Molendaeef51062013-11-05 03:57:19 +00003236
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003237 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003238 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003239 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003240 Mutex::Locker modules_locker(target_modules.GetMutex());
3241 size_t num_modules = target_modules.GetSize();
3242 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003243
Andy Gibbsa297a972013-06-19 19:04:53 +00003244 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003245 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003246 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003247 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003248 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003249 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003250 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003251 break;
3252 }
3253 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003254 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003255 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003256 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003257 if (log)
3258 {
3259 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3260 log->Printf ("Process::%s after looping through modules, target executable is %s",
3261 __FUNCTION__,
3262 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3263 }
3264 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003265}
3266
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003268Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003269{
Greg Claytonb766a732011-02-04 01:58:07 +00003270 m_abi_sp.reset();
3271 m_process_input_reader.reset();
3272
3273 // Find the process and its architecture. Make sure it matches the architecture
3274 // of the current Target, and if not adjust it.
3275
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003276 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003277 if (error.Success())
3278 {
Greg Clayton71337622011-02-24 22:24:29 +00003279 if (GetID() != LLDB_INVALID_PROCESS_ID)
3280 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003281 EventSP event_sp;
3282 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3283
3284 if (state == eStateStopped || state == eStateCrashed)
3285 {
3286 // If we attached and actually have a process on the other end, then
3287 // this ended up being the equivalent of an attach.
3288 CompleteAttach ();
3289
3290 // This delays passing the stopped event to listeners till
3291 // CompleteAttach gets a chance to complete...
3292 HandlePrivateEvent (event_sp);
3293
3294 }
Greg Clayton71337622011-02-24 22:24:29 +00003295 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003296
3297 if (PrivateStateThreadIsValid ())
3298 ResumePrivateStateThread ();
3299 else
3300 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003301 }
3302 return error;
3303}
3304
3305
3306Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003307Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308{
Greg Clayton5160ce52013-03-27 23:08:40 +00003309 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003311 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003312 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003313 StateAsCString(m_public_state.GetValue()),
3314 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003315
3316 Error error (WillResume());
3317 // Tell the process it is about to resume before the thread list
3318 if (error.Success())
3319 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003320 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003321 // can let all of our threads know that they are about to be
3322 // resumed. Threads will each be called with
3323 // Thread::WillResume(StateType) where StateType contains the state
3324 // that they are supposed to have when the process is resumed
3325 // (suspended/running/stepping). Threads should also check
3326 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003327 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328 if (m_thread_list.WillResume())
3329 {
Jim Ingham372787f2012-04-07 00:00:41 +00003330 // Last thing, do the PreResumeActions.
3331 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003332 {
Jim Ingham0161b492013-02-09 01:29:05 +00003333 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003334 }
3335 else
3336 {
3337 m_mod_id.BumpResumeID();
3338 error = DoResume();
3339 if (error.Success())
3340 {
3341 DidResume();
3342 m_thread_list.DidResume();
3343 if (log)
3344 log->Printf ("Process thinks the process has resumed.");
3345 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003346 }
3347 }
3348 else
3349 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003350 // Somebody wanted to run without running. So generate a continue & a stopped event,
3351 // and let the world handle them.
3352 if (log)
3353 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3354
3355 SetPrivateState(eStateRunning);
3356 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357 }
3358 }
Jim Ingham444586b2011-01-24 06:34:17 +00003359 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003360 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003361 return error;
3362}
3363
3364Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003365Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003366{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003367 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3368 // in case it was already set and some thread plan logic calls halt on its
3369 // own.
3370 m_clear_thread_plans_on_stop |= clear_thread_plans;
3371
Jim Inghamaacc3182012-06-06 00:29:30 +00003372 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3373 // we could just straightaway get another event. It just narrows the window...
3374 m_currently_handling_event.WaitForValueEqualTo(false);
3375
3376
Jim Inghambb3a2832011-01-29 01:49:25 +00003377 // Pause our private state thread so we can ensure no one else eats
3378 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003379 Listener halt_listener ("lldb.process.halt_listener");
3380 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003381
Jim Inghambb3a2832011-01-29 01:49:25 +00003382 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003383 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003384
Greg Clayton06357c92014-07-30 17:38:47 +00003385 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003386 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003387 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003388
Greg Clayton513c26c2011-01-29 07:10:55 +00003389 bool caused_stop = false;
3390
3391 // Ask the process subclass to actually halt our process
3392 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003394 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003395 if (m_public_state.GetValue() == eStateAttaching)
3396 {
Greg Clayton06357c92014-07-30 17:38:47 +00003397 // Don't hijack and eat the eStateExited as the code that was doing
3398 // the attach will be waiting for this event...
3399 RestorePrivateProcessEvents();
3400 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003401 SetExitStatus(SIGKILL, "Cancelled async attach.");
3402 Destroy ();
3403 }
3404 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003405 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003406 // If "caused_stop" is true, then DoHalt stopped the process. If
3407 // "caused_stop" is false, the process was already stopped.
3408 // If the DoHalt caused the process to stop, then we want to catch
3409 // this event and set the interrupted bool to true before we pass
3410 // this along so clients know that the process was interrupted by
3411 // a halt command.
3412 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003413 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003414 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003415 TimeValue timeout_time;
3416 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003417 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003418 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3419 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003420
Jim Ingham0f16e732011-02-08 05:20:59 +00003421 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003422 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003423 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003424 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003425 }
3426 else
3427 {
Greg Clayton2637f822011-11-17 01:23:07 +00003428 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003429 {
3430 // We caused the process to interrupt itself, so mark this
3431 // as such in the stop event so clients can tell an interrupted
3432 // process from a natural stop
3433 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3434 }
3435 else
3436 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003437 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003438 if (log)
3439 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3440 error.SetErrorString ("Did not get stopped event after halt.");
3441 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003442 }
3443 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003444 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003445 }
3446 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003447 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003448 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003449 if (!restored_process_events)
3450 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003451
3452 // Post any event we might have consumed. If all goes well, we will have
3453 // stopped the process, intercepted the event and set the interrupted
3454 // bool in the event. Post it to the private event queue and that will end up
3455 // correctly setting the state.
3456 if (event_sp)
3457 m_private_state_broadcaster.BroadcastEvent(event_sp);
3458
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 return error;
3460}
3461
3462Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003463Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3464{
3465 Error error;
3466 if (m_public_state.GetValue() == eStateRunning)
3467 {
3468 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3469 if (log)
3470 log->Printf("Process::Destroy() About to halt.");
3471 error = Halt();
3472 if (error.Success())
3473 {
3474 // Consume the halt event.
3475 TimeValue timeout (TimeValue::Now());
3476 timeout.OffsetWithSeconds(1);
3477 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3478
3479 // If the process exited while we were waiting for it to stop, put the exited event into
3480 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3481 // they don't have a process anymore...
3482
3483 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3484 {
3485 if (log)
3486 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3487 return error;
3488 }
3489 else
3490 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3491
3492 if (state != eStateStopped)
3493 {
3494 if (log)
3495 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3496 // If we really couldn't stop the process then we should just error out here, but if the
3497 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3498 StateType private_state = m_private_state.GetValue();
3499 if (private_state != eStateStopped)
3500 {
3501 return error;
3502 }
3503 }
3504 }
3505 else
3506 {
3507 if (log)
3508 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3509 }
3510 }
3511 return error;
3512}
3513
3514Error
Jim Inghamacff8952013-05-02 00:27:30 +00003515Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003516{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003517 EventSP exit_event_sp;
3518 Error error;
3519 m_destroy_in_process = true;
3520
3521 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522
3523 if (error.Success())
3524 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003525 if (DetachRequiresHalt())
3526 {
3527 error = HaltForDestroyOrDetach (exit_event_sp);
3528 if (!error.Success())
3529 {
3530 m_destroy_in_process = false;
3531 return error;
3532 }
3533 else if (exit_event_sp)
3534 {
3535 // We shouldn't need to do anything else here. There's no process left to detach from...
3536 StopPrivateStateThread();
3537 m_destroy_in_process = false;
3538 return error;
3539 }
3540 }
3541
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003542 m_thread_list.DiscardThreadPlans();
3543 DisableAllBreakpointSites();
3544
Jim Inghamacff8952013-05-02 00:27:30 +00003545 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546 if (error.Success())
3547 {
3548 DidDetach();
3549 StopPrivateStateThread();
3550 }
Jim Inghamacff8952013-05-02 00:27:30 +00003551 else
3552 {
3553 return error;
3554 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003555 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003556 m_destroy_in_process = false;
3557
3558 // If we exited when we were waiting for a process to stop, then
3559 // forward the event here so we don't lose the event
3560 if (exit_event_sp)
3561 {
3562 // Directly broadcast our exited event because we shut down our
3563 // private state thread above
3564 BroadcastEvent(exit_event_sp);
3565 }
3566
3567 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3568 // the last events through the event system, in which case we might strand the write lock. Unlock
3569 // it here so when we do to tear down the process we don't get an error destroying the lock.
3570
Ed Maste64fad602013-07-29 20:58:06 +00003571 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572 return error;
3573}
3574
3575Error
3576Process::Destroy ()
3577{
Jim Ingham09437922013-03-01 20:04:25 +00003578
3579 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3580 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3581 // failed and the process stays around for some reason it won't be in a confused state.
3582
3583 m_destroy_in_process = true;
3584
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003585 Error error (WillDestroy());
3586 if (error.Success())
3587 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003588 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003589 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003590 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003591 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003592 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003593
Jim Inghamaacc3182012-06-06 00:29:30 +00003594 if (m_public_state.GetValue() != eStateRunning)
3595 {
3596 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3597 // kill it, we don't want it hitting a breakpoint...
3598 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3599 // we're not going to have much luck doing this now.
3600 m_thread_list.DiscardThreadPlans();
3601 DisableAllBreakpointSites();
3602 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003603
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003604 error = DoDestroy();
3605 if (error.Success())
3606 {
3607 DidDestroy();
3608 StopPrivateStateThread();
3609 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003610 m_stdio_communication.StopReadThread();
3611 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003612
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003613 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003614 {
3615 m_process_input_reader->SetIsDone(true);
3616 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003617 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003618 }
3619
Greg Clayton85fb1b92012-09-11 02:33:37 +00003620 // If we exited when we were waiting for a process to stop, then
3621 // forward the event here so we don't lose the event
3622 if (exit_event_sp)
3623 {
3624 // Directly broadcast our exited event because we shut down our
3625 // private state thread above
3626 BroadcastEvent(exit_event_sp);
3627 }
3628
Jim Inghamb1e2e842012-04-12 18:49:31 +00003629 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3630 // the last events through the event system, in which case we might strand the write lock. Unlock
3631 // 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 +00003632 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003633 }
Jim Ingham09437922013-03-01 20:04:25 +00003634
3635 m_destroy_in_process = false;
3636
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 return error;
3638}
3639
3640Error
3641Process::Signal (int signal)
3642{
3643 Error error (WillSignal());
3644 if (error.Success())
3645 {
3646 error = DoSignal(signal);
3647 if (error.Success())
3648 DidSignal();
3649 }
3650 return error;
3651}
3652
Greg Clayton514487e2011-02-15 21:59:32 +00003653lldb::ByteOrder
3654Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003655{
Greg Clayton514487e2011-02-15 21:59:32 +00003656 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003657}
3658
3659uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003660Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003661{
Greg Clayton514487e2011-02-15 21:59:32 +00003662 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003663}
3664
Greg Clayton514487e2011-02-15 21:59:32 +00003665
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666bool
3667Process::ShouldBroadcastEvent (Event *event_ptr)
3668{
3669 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3670 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003671 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003672
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003673 switch (state)
3674 {
Greg Claytonb766a732011-02-04 01:58:07 +00003675 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676 case eStateAttaching:
3677 case eStateLaunching:
3678 case eStateDetached:
3679 case eStateExited:
3680 case eStateUnloaded:
3681 // These events indicate changes in the state of the debugging session, always report them.
3682 return_value = true;
3683 break;
3684 case eStateInvalid:
3685 // We stopped for no apparent reason, don't report it.
3686 return_value = false;
3687 break;
3688 case eStateRunning:
3689 case eStateStepping:
3690 // If we've started the target running, we handle the cases where we
3691 // are already running and where there is a transition from stopped to
3692 // running differently.
3693 // running -> running: Automatically suppress extra running events
3694 // stopped -> running: Report except when there is one or more no votes
3695 // and no yes votes.
3696 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003697 if (m_force_next_event_delivery)
3698 return_value = true;
3699 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003700 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003701 switch (m_last_broadcast_state)
3702 {
3703 case eStateRunning:
3704 case eStateStepping:
3705 // We always suppress multiple runnings with no PUBLIC stop in between.
3706 return_value = false;
3707 break;
3708 default:
3709 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003710 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003711 // events. If I run the lldb/test/thread/a.out file and
3712 // break at main.cpp:58, run and hit the breakpoints on
3713 // multiple threads, then somehow during the stepping over
3714 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003715
Jim Ingham1460e4b2014-01-10 23:46:59 +00003716 // This is a transition from stop to run.
3717 switch (m_thread_list.ShouldReportRun (event_ptr))
3718 {
3719 case eVoteYes:
3720 case eVoteNoOpinion:
3721 return_value = true;
3722 break;
3723 case eVoteNo:
3724 return_value = false;
3725 break;
3726 }
3727 break;
3728 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729 }
3730 break;
3731 case eStateStopped:
3732 case eStateCrashed:
3733 case eStateSuspended:
3734 {
3735 // We've stopped. First see if we're going to restart the target.
3736 // If we are going to stop, then we always broadcast the event.
3737 // 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 +00003738 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003739
Jim Inghamcb4ca112012-05-16 01:32:14 +00003740 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003741 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003743 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003744 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003745 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003746 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003747 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3748 // so they can properly set their state.
3749 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003750 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003751 }
3752 else
3753 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003754 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3755 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003756
Jim Ingham0161b492013-02-09 01:29:05 +00003757 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3758 // Asking the thread list is also not likely to go well, since we are running again.
3759 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003760
Jim Ingham0161b492013-02-09 01:29:05 +00003761 if (!was_restarted)
3762 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003763
Jim Ingham221d51c2013-05-08 00:35:16 +00003764 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 {
Jim Ingham0161b492013-02-09 01:29:05 +00003766 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3767 if (log)
3768 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003769 should_resume, StateAsCString(state),
3770 was_restarted, stop_vote);
3771
Jim Ingham0161b492013-02-09 01:29:05 +00003772 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773 {
3774 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003775 return_value = true;
3776 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003778 case eVoteNo:
3779 return_value = false;
3780 break;
3781 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003782
Jim Inghamcb95f342012-09-05 21:13:56 +00003783 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003784 {
3785 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003786 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3787 static_cast<void*>(event_ptr),
3788 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003789 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003790 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003791 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003792
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003793 }
3794 else
3795 {
3796 return_value = true;
3797 SynchronouslyNotifyStateChanged (state);
3798 }
3799 }
3800 }
Jim Ingham0161b492013-02-09 01:29:05 +00003801 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003803
Jim Ingham1460e4b2014-01-10 23:46:59 +00003804 // Forcing the next event delivery is a one shot deal. So reset it here.
3805 m_force_next_event_delivery = false;
3806
Jim Ingham0161b492013-02-09 01:29:05 +00003807 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3808 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3809 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3810 // because the PublicState reflects the last event pulled off the queue, and there may be several
3811 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3812 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003813
Jim Ingham0161b492013-02-09 01:29:05 +00003814 if (return_value)
3815 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003816
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003818 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003819 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003820 StateAsCString(m_last_broadcast_state),
3821 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003822 return return_value;
3823}
3824
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825
3826bool
Jim Ingham372787f2012-04-07 00:00:41 +00003827Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003828{
Greg Clayton5160ce52013-03-27 23:08:40 +00003829 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003830
Greg Clayton8b82f082011-04-12 05:54:46 +00003831 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003833 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3834
Jim Ingham372787f2012-04-07 00:00:41 +00003835 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003836 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003837
3838 // Create a thread that watches our internal state and controls which
3839 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003840 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003841
Zachary Turner39de3112014-09-09 20:54:56 +00003842 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00003843 {
Zachary Turner39de3112014-09-09 20:54:56 +00003844 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3845 if (already_running)
3846 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3847 else
3848 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00003849 }
Jim Ingham372787f2012-04-07 00:00:41 +00003850 else
Todd Fiala17096d72014-07-16 19:03:16 +00003851 {
3852 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00003853 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003854 else
Zachary Turner39de3112014-09-09 20:54:56 +00003855 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003856 }
3857
Jim Ingham076b3042012-04-10 01:21:57 +00003858 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00003859 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
3860 if (m_private_state_thread.GetState() == eThreadStateRunning)
Jim Ingham076b3042012-04-10 01:21:57 +00003861 {
3862 ResumePrivateStateThread();
3863 return true;
3864 }
3865 else
3866 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867}
3868
3869void
3870Process::PausePrivateStateThread ()
3871{
3872 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3873}
3874
3875void
3876Process::ResumePrivateStateThread ()
3877{
3878 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3879}
3880
3881void
3882Process::StopPrivateStateThread ()
3883{
Greg Clayton8b82f082011-04-12 05:54:46 +00003884 if (PrivateStateThreadIsValid ())
3885 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003886 else
3887 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003888 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003889 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003890 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003891 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003892}
3893
3894void
3895Process::ControlPrivateStateThread (uint32_t signal)
3896{
Greg Clayton5160ce52013-03-27 23:08:40 +00003897 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003898
3899 assert (signal == eBroadcastInternalStateControlStop ||
3900 signal == eBroadcastInternalStateControlPause ||
3901 signal == eBroadcastInternalStateControlResume);
3902
3903 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003904 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003905
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003906 // Signal the private state thread. First we should copy this is case the
3907 // thread starts exiting since the private state thread will NULL this out
3908 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00003909 HostThread private_state_thread(m_private_state_thread);
3910 if (private_state_thread.GetState() == eThreadStateRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003911 {
3912 TimeValue timeout_time;
3913 bool timed_out;
3914
3915 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3916
3917 timeout_time = TimeValue::Now();
3918 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003919 if (log)
3920 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3922 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3923
3924 if (signal == eBroadcastInternalStateControlStop)
3925 {
3926 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003927 {
Zachary Turner39de3112014-09-09 20:54:56 +00003928 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003929 if (log)
3930 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3931 }
3932 else
3933 {
3934 if (log)
3935 log->Printf ("The control event killed the private state thread without having to cancel.");
3936 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937
3938 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00003939 private_state_thread.Join(&result);
3940 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003941 }
3942 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003943 else
3944 {
3945 if (log)
3946 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3947 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003948}
3949
3950void
Jim Inghamcfc09352012-07-27 23:57:19 +00003951Process::SendAsyncInterrupt ()
3952{
3953 if (PrivateStateThreadIsValid())
3954 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3955 else
3956 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3957}
3958
3959void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003960Process::HandlePrivateEvent (EventSP &event_sp)
3961{
Greg Clayton5160ce52013-03-27 23:08:40 +00003962 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003963 m_resume_requested = false;
3964
Jim Inghamaacc3182012-06-06 00:29:30 +00003965 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003966
Greg Clayton414f5d32011-01-25 02:58:48 +00003967 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003968
3969 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003970 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003971 {
Jim Ingham754ab982011-01-29 04:05:41 +00003972 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003973 if (log)
3974 log->Printf ("Ran next event action, result was %d.", action_result);
3975
Jim Inghambb3a2832011-01-29 01:49:25 +00003976 switch (action_result)
3977 {
3978 case NextEventAction::eEventActionSuccess:
3979 SetNextEventAction(NULL);
3980 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003981
Jim Inghambb3a2832011-01-29 01:49:25 +00003982 case NextEventAction::eEventActionRetry:
3983 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003984
Jim Inghambb3a2832011-01-29 01:49:25 +00003985 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003986 // Handle Exiting Here. If we already got an exited event,
3987 // we should just propagate it. Otherwise, swallow this event,
3988 // and set our state to exit so the next event will kill us.
3989 if (new_state != eStateExited)
3990 {
3991 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003992 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003993 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003994 SetNextEventAction(NULL);
3995 return;
3996 }
3997 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003998 break;
3999 }
4000 }
4001
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004002 // See if we should broadcast this state to external clients?
4003 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004004
4005 if (should_broadcast)
4006 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004007 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004008 if (log)
4009 {
Daniel Malead01b2952012-11-29 21:49:15 +00004010 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004011 __FUNCTION__,
4012 GetID(),
4013 StateAsCString(new_state),
4014 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004015 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016 }
Jim Ingham9575d842011-03-11 03:53:59 +00004017 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004018 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004019 {
4020 // Only push the input handler if we aren't fowarding events,
4021 // as this means the curses GUI is in use...
4022 if (!GetTarget().GetDebugger().IsForwardingEvents())
4023 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004024 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004025 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004026 else if (StateIsStoppedState(new_state, false))
4027 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004028 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004029 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4030 {
4031 // If the lldb_private::Debugger is handling the events, we don't
4032 // want to pop the process IOHandler here, we want to do it when
4033 // we receive the stopped event so we can carefully control when
4034 // the process IOHandler is popped because when we stop we want to
4035 // display some text stating how and why we stopped, then maybe some
4036 // process/thread/frame info, and then we want the "(lldb) " prompt
4037 // to show up. If we pop the process IOHandler here, then we will
4038 // cause the command interpreter to become the top IOHandler after
4039 // the process pops off and it will update its prompt right away...
4040 // See the Debugger.cpp file where it calls the function as
4041 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4042 // Otherwise we end up getting overlapping "(lldb) " prompts and
4043 // garbled output.
4044 //
4045 // If we aren't handling the events in the debugger (which is indicated
4046 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4047 // are hijacked, then we always pop the process IO handler manually.
4048 // Hijacking happens when the internal process state thread is running
4049 // thread plans, or when commands want to run in synchronous mode
4050 // and they call "process->WaitForProcessToStop()". An example of something
4051 // that will hijack the events is a simple expression:
4052 //
4053 // (lldb) expr (int)puts("hello")
4054 //
4055 // This will cause the internal process state thread to resume and halt
4056 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4057 // events) and we do need the IO handler to be pushed and popped
4058 // correctly.
4059
4060 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4061 PopProcessIOHandler ();
4062 }
4063 }
Jim Ingham9575d842011-03-11 03:53:59 +00004064
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004065 BroadcastEvent (event_sp);
4066 }
4067 else
4068 {
4069 if (log)
4070 {
Daniel Malead01b2952012-11-29 21:49:15 +00004071 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004072 __FUNCTION__,
4073 GetID(),
4074 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004075 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004076 }
4077 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004078 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004079}
4080
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004081thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004082Process::PrivateStateThread (void *arg)
4083{
4084 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004085 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086 return result;
4087}
4088
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004089thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004090Process::RunPrivateStateThread ()
4091{
Jim Ingham076b3042012-04-10 01:21:57 +00004092 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004093 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004094
Greg Clayton5160ce52013-03-27 23:08:40 +00004095 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004097 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4098 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004099
4100 bool exit_now = false;
4101 while (!exit_now)
4102 {
4103 EventSP event_sp;
4104 WaitForEventsPrivate (NULL, event_sp, control_only);
4105 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4106 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004107 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004108 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4109 __FUNCTION__, static_cast<void*>(this), GetID(),
4110 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004111
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004112 switch (event_sp->GetType())
4113 {
4114 case eBroadcastInternalStateControlStop:
4115 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004116 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117
4118 case eBroadcastInternalStateControlPause:
4119 control_only = true;
4120 break;
4121
4122 case eBroadcastInternalStateControlResume:
4123 control_only = false;
4124 break;
4125 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004126
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004127 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004128 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004129 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004130 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4131 {
4132 if (m_public_state.GetValue() == eStateAttaching)
4133 {
4134 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004135 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4136 __FUNCTION__, static_cast<void*>(this),
4137 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004138 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4139 }
4140 else
4141 {
4142 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004143 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4144 __FUNCTION__, static_cast<void*>(this),
4145 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004146 Halt();
4147 }
4148 continue;
4149 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004150
4151 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4152
4153 if (internal_state != eStateInvalid)
4154 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004155 if (m_clear_thread_plans_on_stop &&
4156 StateIsStoppedState(internal_state, true))
4157 {
4158 m_clear_thread_plans_on_stop = false;
4159 m_thread_list.DiscardThreadPlans();
4160 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004161 HandlePrivateEvent (event_sp);
4162 }
4163
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004164 if (internal_state == eStateInvalid ||
4165 internal_state == eStateExited ||
4166 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004167 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004168 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004169 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4170 __FUNCTION__, static_cast<void*>(this), GetID(),
4171 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004172
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004173 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004174 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004175 }
4176
Caroline Tice20ad3c42010-10-29 21:48:37 +00004177 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004178 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004179 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4180 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004181
Ed Maste64fad602013-07-29 20:58:06 +00004182 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004183 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004184 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185 return NULL;
4186}
4187
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004188//------------------------------------------------------------------
4189// Process Event Data
4190//------------------------------------------------------------------
4191
4192Process::ProcessEventData::ProcessEventData () :
4193 EventData (),
4194 m_process_sp (),
4195 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004196 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004197 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004198 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004199{
4200}
4201
4202Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4203 EventData (),
4204 m_process_sp (process_sp),
4205 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004206 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004207 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004208 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004209{
4210}
4211
4212Process::ProcessEventData::~ProcessEventData()
4213{
4214}
4215
4216const ConstString &
4217Process::ProcessEventData::GetFlavorString ()
4218{
4219 static ConstString g_flavor ("Process::ProcessEventData");
4220 return g_flavor;
4221}
4222
4223const ConstString &
4224Process::ProcessEventData::GetFlavor () const
4225{
4226 return ProcessEventData::GetFlavorString ();
4227}
4228
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004229void
4230Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4231{
4232 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004233 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4234 // the public event queue, then other times when we're pretending that this is where we stopped at the
4235 // end of expression evaluation. m_update_state is used to distinguish these
4236 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004237 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004238 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004240
Jim Ingham221d51c2013-05-08 00:35:16 +00004241 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004242
4243 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4244 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4245 // end up restarting the process.
4246 if (m_interrupted)
4247 return;
4248
4249 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004250 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004251 {
4252 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004253 uint32_t num_threads = curr_thread_list.GetSize();
4254 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004255
Jim Ingham4b536182011-08-09 02:12:22 +00004256 // The actions might change one of the thread's stop_info's opinions about whether we should
4257 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004258
4259 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4260 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4261 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4262 // 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
4263 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004264 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004265 for (idx = 0; idx < num_threads; ++idx)
4266 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4267
Jim Inghamc7078c22012-12-13 22:24:15 +00004268 // Use this to track whether we should continue from here. We will only continue the target running if
4269 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4270 // then it doesn't matter what the other threads say...
4271
4272 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004273
Jim Ingham0ad7e052013-04-25 02:04:59 +00004274 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4275 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4276 // thing to do is, and it's better to let the user decide than continue behind their backs.
4277
4278 bool does_anybody_have_an_opinion = false;
4279
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004280 for (idx = 0; idx < num_threads; ++idx)
4281 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004282 curr_thread_list = m_process_sp->GetThreadList();
4283 if (curr_thread_list.GetSize() != num_threads)
4284 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004285 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004286 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004287 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 +00004288 break;
4289 }
4290
4291 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4292
4293 if (thread_sp->GetIndexID() != thread_index_array[idx])
4294 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004295 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004296 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004297 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004298 idx,
4299 thread_index_array[idx],
4300 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004301 break;
4302 }
4303
Jim Inghamb15bfc72010-10-20 00:39:53 +00004304 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004305 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004306 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004307 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004308 bool this_thread_wants_to_stop;
4309 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004310 {
Jim Ingham0161b492013-02-09 01:29:05 +00004311 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4312 }
4313 else
4314 {
4315 stop_info_sp->PerformAction(event_ptr);
4316 // The stop action might restart the target. If it does, then we want to mark that in the
4317 // event so that whoever is receiving it will know to wait for the running event and reflect
4318 // that state appropriately.
4319 // We also need to stop processing actions, since they aren't expecting the target to be running.
4320
4321 // FIXME: we might have run.
4322 if (stop_info_sp->HasTargetRunSinceMe())
4323 {
4324 SetRestarted (true);
4325 break;
4326 }
4327
4328 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004329 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004330
Jim Inghamc7078c22012-12-13 22:24:15 +00004331 if (still_should_stop == false)
4332 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004333 }
4334 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004335
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004336
Jim Inghama8ca6e22013-05-03 23:04:37 +00004337 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004338 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004339 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004340 {
4341 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004342 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004343 // Use the public resume method here, since this is just
4344 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004345 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004346 }
4347 else
4348 {
4349 // If we didn't restart, run the Stop Hooks here:
4350 // They might also restart the target, so watch for that.
4351 m_process_sp->GetTarget().RunStopHooks();
4352 if (m_process_sp->GetPrivateState() == eStateRunning)
4353 SetRestarted(true);
4354 }
Jim Ingham9575d842011-03-11 03:53:59 +00004355 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004356 }
4357}
4358
4359void
4360Process::ProcessEventData::Dump (Stream *s) const
4361{
4362 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004363 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4364 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004365
Greg Clayton8b82f082011-04-12 05:54:46 +00004366 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004367}
4368
4369const Process::ProcessEventData *
4370Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4371{
4372 if (event_ptr)
4373 {
4374 const EventData *event_data = event_ptr->GetData();
4375 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4376 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4377 }
4378 return NULL;
4379}
4380
4381ProcessSP
4382Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4383{
4384 ProcessSP process_sp;
4385 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4386 if (data)
4387 process_sp = data->GetProcessSP();
4388 return process_sp;
4389}
4390
4391StateType
4392Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4393{
4394 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4395 if (data == NULL)
4396 return eStateInvalid;
4397 else
4398 return data->GetState();
4399}
4400
4401bool
4402Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4403{
4404 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4405 if (data == NULL)
4406 return false;
4407 else
4408 return data->GetRestarted();
4409}
4410
4411void
4412Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4413{
4414 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4415 if (data != NULL)
4416 data->SetRestarted(new_value);
4417}
4418
Jim Ingham0161b492013-02-09 01:29:05 +00004419size_t
4420Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4421{
4422 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4423 if (data != NULL)
4424 return data->GetNumRestartedReasons();
4425 else
4426 return 0;
4427}
4428
4429const char *
4430Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4431{
4432 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4433 if (data != NULL)
4434 return data->GetRestartedReasonAtIndex(idx);
4435 else
4436 return NULL;
4437}
4438
4439void
4440Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4441{
4442 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4443 if (data != NULL)
4444 data->AddRestartedReason(reason);
4445}
4446
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004447bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004448Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4449{
4450 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4451 if (data == NULL)
4452 return false;
4453 else
4454 return data->GetInterrupted ();
4455}
4456
4457void
4458Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4459{
4460 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4461 if (data != NULL)
4462 data->SetInterrupted(new_value);
4463}
4464
4465bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004466Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4467{
4468 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4469 if (data)
4470 {
4471 data->SetUpdateStateOnRemoval();
4472 return true;
4473 }
4474 return false;
4475}
4476
Greg Claytond9e416c2012-02-18 05:35:26 +00004477lldb::TargetSP
4478Process::CalculateTarget ()
4479{
4480 return m_target.shared_from_this();
4481}
4482
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004483void
Greg Clayton0603aa92010-10-04 01:05:56 +00004484Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004485{
Greg Claytonc14ee322011-09-22 04:58:26 +00004486 exe_ctx.SetTargetPtr (&m_target);
4487 exe_ctx.SetProcessPtr (this);
4488 exe_ctx.SetThreadPtr(NULL);
4489 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004490}
4491
Greg Claytone996fd32011-03-08 22:40:15 +00004492//uint32_t
4493//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4494//{
4495// return 0;
4496//}
4497//
4498//ArchSpec
4499//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4500//{
4501// return Host::GetArchSpecForExistingProcess (pid);
4502//}
4503//
4504//ArchSpec
4505//Process::GetArchSpecForExistingProcess (const char *process_name)
4506//{
4507// return Host::GetArchSpecForExistingProcess (process_name);
4508//}
4509//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004510void
4511Process::AppendSTDOUT (const char * s, size_t len)
4512{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004513 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004514 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004515 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004516}
4517
4518void
Greg Clayton93e86192011-11-13 04:45:22 +00004519Process::AppendSTDERR (const char * s, size_t len)
4520{
4521 Mutex::Locker locker (m_stdio_communication_mutex);
4522 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004523 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004524}
4525
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004526void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004527Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004528{
4529 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004530 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004531 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4532}
4533
4534size_t
4535Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4536{
4537 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004538 if (m_profile_data.empty())
4539 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004540
4541 std::string &one_profile_data = m_profile_data.front();
4542 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004543 if (bytes_available > 0)
4544 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004545 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004546 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004547 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4548 static_cast<void*>(buf),
4549 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004550 if (bytes_available > buf_size)
4551 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004552 memcpy(buf, one_profile_data.c_str(), buf_size);
4553 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004554 bytes_available = buf_size;
4555 }
4556 else
4557 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004558 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004559 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004560 }
4561 }
4562 return bytes_available;
4563}
4564
4565
Greg Clayton93e86192011-11-13 04:45:22 +00004566//------------------------------------------------------------------
4567// Process STDIO
4568//------------------------------------------------------------------
4569
4570size_t
4571Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4572{
4573 Mutex::Locker locker(m_stdio_communication_mutex);
4574 size_t bytes_available = m_stdout_data.size();
4575 if (bytes_available > 0)
4576 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004577 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004578 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004579 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4580 static_cast<void*>(buf),
4581 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004582 if (bytes_available > buf_size)
4583 {
4584 memcpy(buf, m_stdout_data.c_str(), buf_size);
4585 m_stdout_data.erase(0, buf_size);
4586 bytes_available = buf_size;
4587 }
4588 else
4589 {
4590 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4591 m_stdout_data.clear();
4592 }
4593 }
4594 return bytes_available;
4595}
4596
4597
4598size_t
4599Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4600{
4601 Mutex::Locker locker(m_stdio_communication_mutex);
4602 size_t bytes_available = m_stderr_data.size();
4603 if (bytes_available > 0)
4604 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004605 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004606 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004607 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4608 static_cast<void*>(buf),
4609 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004610 if (bytes_available > buf_size)
4611 {
4612 memcpy(buf, m_stderr_data.c_str(), buf_size);
4613 m_stderr_data.erase(0, buf_size);
4614 bytes_available = buf_size;
4615 }
4616 else
4617 {
4618 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4619 m_stderr_data.clear();
4620 }
4621 }
4622 return bytes_available;
4623}
4624
4625void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004626Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4627{
4628 Process *process = (Process *) baton;
4629 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4630}
4631
Greg Clayton44d93782014-01-27 23:43:24 +00004632class IOHandlerProcessSTDIO :
4633 public IOHandler
4634{
4635public:
4636 IOHandlerProcessSTDIO (Process *process,
4637 int write_fd) :
4638 IOHandler(process->GetTarget().GetDebugger()),
4639 m_process (process),
4640 m_read_file (),
4641 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004642 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004643 {
4644 m_read_file.SetDescriptor(GetInputFD(), false);
4645 }
4646
4647 virtual
4648 ~IOHandlerProcessSTDIO ()
4649 {
4650
4651 }
4652
4653 bool
4654 OpenPipes ()
4655 {
Greg Clayton100eb932014-07-02 21:10:39 +00004656 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004657 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004658 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004659 }
4660
4661 void
4662 ClosePipes()
4663 {
Greg Clayton100eb932014-07-02 21:10:39 +00004664 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004665 }
4666
4667 // Each IOHandler gets to run until it is done. It should read data
4668 // from the "in" and place output into "out" and "err and return
4669 // when done.
4670 virtual void
4671 Run ()
4672 {
4673 if (m_read_file.IsValid() && m_write_file.IsValid())
4674 {
4675 SetIsDone(false);
4676 if (OpenPipes())
4677 {
4678 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004679 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004680 TerminalState terminal_state;
4681 terminal_state.Save (read_fd, false);
4682 Terminal terminal(read_fd);
4683 terminal.SetCanonical(false);
4684 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004685// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004686#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004687 while (!GetIsDone())
4688 {
4689 fd_set read_fdset;
4690 FD_ZERO (&read_fdset);
4691 FD_SET (read_fd, &read_fdset);
4692 FD_SET (pipe_read_fd, &read_fdset);
4693 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4694 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4695 if (num_set_fds < 0)
4696 {
4697 const int select_errno = errno;
4698
4699 if (select_errno != EINTR)
4700 SetIsDone(true);
4701 }
4702 else if (num_set_fds > 0)
4703 {
4704 char ch = 0;
4705 size_t n;
4706 if (FD_ISSET (read_fd, &read_fdset))
4707 {
4708 n = 1;
4709 if (m_read_file.Read(&ch, n).Success() && n == 1)
4710 {
4711 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4712 SetIsDone(true);
4713 }
4714 else
4715 SetIsDone(true);
4716 }
4717 if (FD_ISSET (pipe_read_fd, &read_fdset))
4718 {
4719 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004720 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004721 {
Greg Clayton100eb932014-07-02 21:10:39 +00004722 switch (ch)
4723 {
4724 case 'q':
4725 SetIsDone(true);
4726 break;
4727 case 'i':
4728 if (StateIsRunningState(m_process->GetState()))
4729 m_process->Halt();
4730 break;
4731 }
Greg Clayton19e11352014-02-26 22:47:33 +00004732 }
Greg Clayton44d93782014-01-27 23:43:24 +00004733 }
4734 }
4735 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004736#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004737 terminal_state.Restore();
4738
4739 }
4740 else
4741 SetIsDone(true);
4742 }
4743 else
4744 SetIsDone(true);
4745 }
4746
4747 // Hide any characters that have been displayed so far so async
4748 // output can be displayed. Refresh() will be called after the
4749 // output has been displayed.
4750 virtual void
4751 Hide ()
4752 {
4753
4754 }
4755 // Called when the async output has been received in order to update
4756 // the input reader (refresh the prompt and redisplay any current
4757 // line(s) that are being edited
4758 virtual void
4759 Refresh ()
4760 {
4761
4762 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004763
Greg Clayton44d93782014-01-27 23:43:24 +00004764 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004765 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004766 {
Greg Clayton19e11352014-02-26 22:47:33 +00004767 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004768 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004769 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004770
Greg Claytonf0066ad2014-05-02 00:45:31 +00004771 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004772 Interrupt ()
4773 {
Greg Clayton19e11352014-02-26 22:47:33 +00004774 // Do only things that are safe to do in an interrupt context (like in
4775 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4776 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4777 // that was written to the pipe and then call m_process->Halt() from a
4778 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004779 if (m_active)
4780 {
4781 char ch = 'i'; // Send 'i' for interrupt
4782 return m_pipe.Write (&ch, 1) == 1;
4783 }
4784 else
4785 {
4786 // This IOHandler might be pushed on the stack, but not being run currently
4787 // so do the right thing if we aren't actively watching for STDIN by sending
4788 // the interrupt to the process. Otherwise the write to the pipe above would
4789 // do nothing. This can happen when the command interpreter is running and
4790 // gets a "expression ...". It will be on the IOHandler thread and sending
4791 // the input is complete to the delegate which will cause the expression to
4792 // run, which will push the process IO handler, but not run it.
4793
4794 if (StateIsRunningState(m_process->GetState()))
4795 {
4796 m_process->SendAsyncInterrupt();
4797 return true;
4798 }
4799 }
4800 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004801 }
Greg Clayton44d93782014-01-27 23:43:24 +00004802
4803 virtual void
4804 GotEOF()
4805 {
4806
4807 }
4808
4809protected:
4810 Process *m_process;
4811 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4812 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004813 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004814};
4815
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004816void
Greg Clayton44d93782014-01-27 23:43:24 +00004817Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004818{
4819 // First set up the Read Thread for reading/handling process I/O
4820
Greg Clayton44d93782014-01-27 23:43:24 +00004821 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004822
4823 if (conn_ap.get())
4824 {
4825 m_stdio_communication.SetConnection (conn_ap.release());
4826 if (m_stdio_communication.IsConnected())
4827 {
4828 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4829 m_stdio_communication.StartReadThread();
4830
4831 // Now read thread is set up, set up input reader.
4832
4833 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004834 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004835 }
4836 }
4837}
4838
Greg Claytonb4874f12014-02-28 18:22:24 +00004839bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004840Process::ProcessIOHandlerIsActive ()
4841{
4842 IOHandlerSP io_handler_sp (m_process_input_reader);
4843 if (io_handler_sp)
4844 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4845 return false;
4846}
4847bool
Greg Clayton44d93782014-01-27 23:43:24 +00004848Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004849{
Greg Clayton44d93782014-01-27 23:43:24 +00004850 IOHandlerSP io_handler_sp (m_process_input_reader);
4851 if (io_handler_sp)
4852 {
4853 io_handler_sp->SetIsDone(false);
4854 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004855 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004856 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004857 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004858}
4859
Greg Claytonb4874f12014-02-28 18:22:24 +00004860bool
Greg Clayton44d93782014-01-27 23:43:24 +00004861Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004862{
Greg Clayton44d93782014-01-27 23:43:24 +00004863 IOHandlerSP io_handler_sp (m_process_input_reader);
4864 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004865 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4866 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004867}
4868
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004869// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004870void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004871Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004872{
Greg Clayton6920b522012-08-22 18:39:03 +00004873 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004874}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004875
Greg Clayton99d0faf2010-11-18 23:32:35 +00004876void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004877Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004878{
Greg Clayton6920b522012-08-22 18:39:03 +00004879 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004880}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004881
Jim Ingham1624a2d2014-05-05 02:26:40 +00004882ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004883Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004884 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004885 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004886 Stream &errors)
4887{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004888 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004889
Jim Ingham77787032011-01-20 02:03:18 +00004890 if (thread_plan_sp.get() == NULL)
4891 {
4892 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004893 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004894 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004895
Jim Ingham7d7931d2013-03-28 00:05:34 +00004896 if (!thread_plan_sp->ValidatePlan(NULL))
4897 {
4898 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004899 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004900 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004901
Greg Claytonc14ee322011-09-22 04:58:26 +00004902 if (exe_ctx.GetProcessPtr() != this)
4903 {
4904 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004905 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004906 }
4907
4908 Thread *thread = exe_ctx.GetThreadPtr();
4909 if (thread == NULL)
4910 {
4911 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004912 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004913 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004914
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004915 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4916 // For that to be true the plan can't be private - since private plans suppress themselves in the
4917 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004918
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004919 bool orig_plan_private = thread_plan_sp->GetPrivate();
4920 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004921
Jim Ingham444586b2011-01-24 06:34:17 +00004922 if (m_private_state.GetValue() != eStateStopped)
4923 {
4924 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004925 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004926 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004927
Jim Ingham66243842011-08-13 00:56:10 +00004928 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004929 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004930 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004931 if (!selected_frame_sp)
4932 {
4933 thread->SetSelectedFrame(0);
4934 selected_frame_sp = thread->GetSelectedFrame();
4935 if (!selected_frame_sp)
4936 {
4937 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004938 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004939 }
4940 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004941
Jim Ingham11b0e052013-02-19 23:22:45 +00004942 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004943
4944 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4945 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004946
Greg Claytonc14ee322011-09-22 04:58:26 +00004947 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004948
Jim Ingham66243842011-08-13 00:56:10 +00004949 uint32_t selected_tid;
4950 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004951 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004952 {
4953 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004954 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004955 }
4956 else
4957 {
4958 selected_tid = LLDB_INVALID_THREAD_ID;
4959 }
4960
Zachary Turner39de3112014-09-09 20:54:56 +00004961 HostThread backup_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004962 lldb::StateType old_state;
4963 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004964
Greg Clayton5160ce52013-03-27 23:08:40 +00004965 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00004966 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00004967 {
Jim Ingham076b3042012-04-10 01:21:57 +00004968 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4969 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004970 // 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 +00004971 // we are fielding public events here.
4972 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004973 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 +00004974
Jim Ingham372787f2012-04-07 00:00:41 +00004975 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004976
4977 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4978 // returning control here.
4979 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4980 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4981 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4982 // do just what we want.
4983 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4984 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4985 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4986 old_state = m_public_state.GetValue();
4987 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004988
Jim Ingham076b3042012-04-10 01:21:57 +00004989 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004990 StartPrivateStateThread(true);
4991 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004992
Jim Ingham372787f2012-04-07 00:00:41 +00004993 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004994
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004995 if (options.GetDebug())
4996 {
4997 // In this case, we aren't actually going to run, we just want to stop right away.
4998 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4999 // FIXME: To make this prettier we should invent some stop reason for this, but that
5000 // is only cosmetic, and this functionality is only of use to lldb developers who can
5001 // live with not pretty...
5002 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005003 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005004 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005005
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005006 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005007
Sean Callanana46ec452012-07-11 21:31:24 +00005008 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005009
Jim Ingham77787032011-01-20 02:03:18 +00005010 {
Sean Callanana46ec452012-07-11 21:31:24 +00005011 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5012 // restored on exit to the function.
5013 //
5014 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5015 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005016
Sean Callanana46ec452012-07-11 21:31:24 +00005017 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005018
Jim Inghamf48169b2010-11-30 02:22:11 +00005019 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005020 {
5021 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005022 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005023 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005024 thread->GetIndexID(),
5025 thread->GetID(),
5026 s.GetData());
5027 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005028
Sean Callanana46ec452012-07-11 21:31:24 +00005029 bool got_event;
5030 lldb::EventSP event_sp;
5031 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005032
Sean Callanana46ec452012-07-11 21:31:24 +00005033 TimeValue* timeout_ptr = NULL;
5034 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005035
Jim Ingham0161b492013-02-09 01:29:05 +00005036 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 +00005037 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005038 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005039 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005040
Jim Ingham0161b492013-02-09 01:29:05 +00005041 // This is just for accounting:
5042 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005043
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005044 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005045 uint32_t one_thread_timeout_usec;
5046 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005047
5048 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5049 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5050 // first timeout already.
5051
5052 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005053 {
5054 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005055 one_thread_timeout_usec = 0;
5056 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005057 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005058 else
Jim Ingham0161b492013-02-09 01:29:05 +00005059 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005060 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005061
Jim Ingham914f4e72014-03-28 21:58:28 +00005062 // If the overall wait is forever, then we only need to set the one thread timeout:
5063 if (timeout_usec == 0)
5064 {
Ed Maste801335c2014-03-31 19:28:14 +00005065 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005066 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005067 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005068 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005069 }
Jim Ingham0161b492013-02-09 01:29:05 +00005070 else
5071 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005072 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5073 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5074 uint64_t computed_one_thread_timeout;
5075 if (option_one_thread_timeout != 0)
5076 {
5077 if (timeout_usec < option_one_thread_timeout)
5078 {
5079 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005080 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005081 }
5082 computed_one_thread_timeout = option_one_thread_timeout;
5083 }
5084 else
5085 {
5086 computed_one_thread_timeout = timeout_usec / 2;
5087 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5088 computed_one_thread_timeout = default_one_thread_timeout_usec;
5089 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005090 one_thread_timeout_usec = computed_one_thread_timeout;
5091 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5092
Jim Ingham0161b492013-02-09 01:29:05 +00005093 }
Jim Ingham0161b492013-02-09 01:29:05 +00005094 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005095
5096 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005097 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 +00005098 options.GetStopOthers(),
5099 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005100 before_first_timeout,
5101 one_thread_timeout_usec,
5102 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005103
Jim Ingham1460e4b2014-01-10 23:46:59 +00005104 // This isn't going to work if there are unfetched events on the queue.
5105 // Are there cases where we might want to run the remaining events here, and then try to
5106 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005107
Jim Ingham1460e4b2014-01-10 23:46:59 +00005108 Event *other_events = listener.PeekAtNextEvent();
5109 if (other_events != NULL)
5110 {
5111 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005112 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005113 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005114
Jim Ingham1460e4b2014-01-10 23:46:59 +00005115 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5116 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5117 // event coalescing to cause us to lose OUR running event...
5118 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005119
Jim Ingham8559a352012-11-26 23:52:18 +00005120 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5121 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005122
5123#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5124 // It's pretty much impossible to write test cases for things like:
5125 // One thread timeout expires, I go to halt, but the process already stopped
5126 // on the function call stop breakpoint. Turning on this define will make us not
5127 // fetch the first event till after the halt. So if you run a quick function, it will have
5128 // completed, and the completion event will be waiting, when you interrupt for halt.
5129 // The expression evaluation should still succeed.
5130 bool miss_first_event = true;
5131#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005132 TimeValue one_thread_timeout;
5133 TimeValue final_timeout;
5134
Jim Ingham35878c42014-04-08 21:33:21 +00005135
Sean Callanana46ec452012-07-11 21:31:24 +00005136 while (1)
5137 {
5138 // We usually want to resume the process if we get to the top of the loop.
5139 // The only exception is if we get two running events with no intervening
5140 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005141 if (log)
5142 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5143 do_resume,
5144 handle_running_event,
5145 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005146
Jim Ingham184e9812013-01-15 02:47:48 +00005147 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005148 {
5149 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005150
Jim Ingham184e9812013-01-15 02:47:48 +00005151 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005152 {
Jim Ingham0161b492013-02-09 01:29:05 +00005153 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005154 Error resume_error = PrivateResume ();
5155 if (!resume_error.Success())
5156 {
Jim Ingham0161b492013-02-09 01:29:05 +00005157 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5158 num_resumes,
5159 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005160 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005161 break;
5162 }
Sean Callanana46ec452012-07-11 21:31:24 +00005163 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005164
Jim Ingham0161b492013-02-09 01:29:05 +00005165 TimeValue resume_timeout = TimeValue::Now();
5166 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005167
Jim Ingham0161b492013-02-09 01:29:05 +00005168 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005169 if (!got_event)
5170 {
5171 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005172 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5173 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005174
Jim Ingham0161b492013-02-09 01:29:05 +00005175 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005176 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005177 break;
5178 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005179
Sean Callanana46ec452012-07-11 21:31:24 +00005180 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005181
Sean Callanana46ec452012-07-11 21:31:24 +00005182 if (stop_state != eStateRunning)
5183 {
Jim Ingham0161b492013-02-09 01:29:05 +00005184 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005185
Jim Ingham0161b492013-02-09 01:29:05 +00005186 if (stop_state == eStateStopped)
5187 {
5188 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5189 if (log)
5190 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5191 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5192 num_resumes,
5193 StateAsCString(stop_state),
5194 restarted,
5195 do_resume,
5196 handle_running_event);
5197 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005198
Jim Ingham0161b492013-02-09 01:29:05 +00005199 if (restarted)
5200 {
5201 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5202 // event here. But if I do, the best thing is to Halt and then get out of here.
5203 Halt();
5204 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005205
Jim Ingham35e1bda2012-10-16 21:41:58 +00005206 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5207 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005208 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005209 break;
5210 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005211
Sean Callanana46ec452012-07-11 21:31:24 +00005212 if (log)
5213 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5214 // We need to call the function synchronously, so spin waiting for it to return.
5215 // If we get interrupted while executing, we're going to lose our context, and
5216 // won't be able to gather the result at this point.
5217 // We set the timeout AFTER the resume, since the resume takes some time and we
5218 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005219 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005220 else
5221 {
Sean Callanana46ec452012-07-11 21:31:24 +00005222 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005223 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005224 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005225
Jim Ingham0161b492013-02-09 01:29:05 +00005226 if (before_first_timeout)
5227 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005228 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005229 {
5230 one_thread_timeout = TimeValue::Now();
5231 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005232 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005233 }
Jim Ingham0161b492013-02-09 01:29:05 +00005234 else
5235 {
5236 if (timeout_usec == 0)
5237 timeout_ptr = NULL;
5238 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005239 {
5240 final_timeout = TimeValue::Now();
5241 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005242 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005243 }
Jim Ingham0161b492013-02-09 01:29:05 +00005244 }
5245 }
5246 else
5247 {
5248 if (timeout_usec == 0)
5249 timeout_ptr = NULL;
5250 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005251 {
5252 final_timeout = TimeValue::Now();
5253 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005254 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005255 }
Jim Ingham0161b492013-02-09 01:29:05 +00005256 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005257
Jim Ingham0161b492013-02-09 01:29:05 +00005258 do_resume = true;
5259 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005260
Sean Callanana46ec452012-07-11 21:31:24 +00005261 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005262 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005263
Jim Ingham0f16e732011-02-08 05:20:59 +00005264 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005265 {
Sean Callanana46ec452012-07-11 21:31:24 +00005266 if (timeout_ptr)
5267 {
Matt Kopec676a4872013-02-21 23:55:31 +00005268 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005269 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5270 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005271 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005272 else
Sean Callanana46ec452012-07-11 21:31:24 +00005273 {
5274 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5275 }
5276 }
Jim Ingham35878c42014-04-08 21:33:21 +00005277
5278#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5279 // See comment above...
5280 if (miss_first_event)
5281 {
5282 usleep(1000);
5283 miss_first_event = false;
5284 got_event = false;
5285 }
5286 else
5287#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005288 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005289
Sean Callanana46ec452012-07-11 21:31:24 +00005290 if (got_event)
5291 {
5292 if (event_sp.get())
5293 {
5294 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005295 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005296 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005297 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005298 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005299 errors.Printf ("Execution halted by user interrupt.");
5300 if (log)
5301 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005302 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005303 }
5304 else
5305 {
5306 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5307 if (log)
5308 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005309
Jim Inghamcfc09352012-07-27 23:57:19 +00005310 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005311 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005312 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005313 {
Jim Ingham0161b492013-02-09 01:29:05 +00005314 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005315 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5316 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005317 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005318 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005319 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005320 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005321 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005322 }
5323 else
5324 {
Jim Ingham0161b492013-02-09 01:29:05 +00005325 // If we were restarted, we just need to go back up to fetch another event.
5326 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005327 {
5328 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005329 {
5330 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5331 }
5332 keep_going = true;
5333 do_resume = false;
5334 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005335
Jim Inghamcfc09352012-07-27 23:57:19 +00005336 }
5337 else
5338 {
Jim Ingham0161b492013-02-09 01:29:05 +00005339 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5340 StopReason stop_reason = eStopReasonInvalid;
5341 if (stop_info_sp)
5342 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005343
Jim Ingham0161b492013-02-09 01:29:05 +00005344 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5345 // it is OUR plan that is complete?
5346 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005347 {
5348 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005349 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5350 // Now mark this plan as private so it doesn't get reported as the stop reason
5351 // after this point.
5352 if (thread_plan_sp)
5353 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005354 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005355 }
5356 else
5357 {
Jim Ingham0161b492013-02-09 01:29:05 +00005358 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005359 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005360 {
5361 if (log)
5362 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005363 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005364 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005365 {
5366 event_to_broadcast_sp = event_sp;
5367 }
Jim Ingham0161b492013-02-09 01:29:05 +00005368 }
Jim Ingham184e9812013-01-15 02:47:48 +00005369 else
Jim Ingham0161b492013-02-09 01:29:05 +00005370 {
5371 if (log)
5372 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005373 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005374 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005375 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005376 }
Jim Ingham184e9812013-01-15 02:47:48 +00005377 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005378 }
Sean Callanana46ec452012-07-11 21:31:24 +00005379 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005380 }
5381 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005382
Jim Inghamcfc09352012-07-27 23:57:19 +00005383 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005384 // This shouldn't really happen, but sometimes we do get two running events without an
5385 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005386 do_resume = false;
5387 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005388 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005389 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005390
Jim Inghamcfc09352012-07-27 23:57:19 +00005391 default:
5392 if (log)
5393 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005394
Jim Inghamcfc09352012-07-27 23:57:19 +00005395 if (stop_state == eStateExited)
5396 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005397
Sean Callananbf154da2012-08-08 17:35:10 +00005398 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005399 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005400 break;
5401 }
Sean Callanana46ec452012-07-11 21:31:24 +00005402 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005403
Sean Callanana46ec452012-07-11 21:31:24 +00005404 if (keep_going)
5405 continue;
5406 else
5407 break;
5408 }
5409 else
5410 {
5411 if (log)
5412 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005413 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005414 break;
5415 }
5416 }
5417 else
5418 {
5419 // If we didn't get an event that means we've timed out...
5420 // We will interrupt the process here. Depending on what we were asked to do we will
5421 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005422
Sean Callanana46ec452012-07-11 21:31:24 +00005423 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005424 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005425 {
Jim Ingham0161b492013-02-09 01:29:05 +00005426 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005427 {
5428 if (timeout_usec != 0)
5429 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005430 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005431 "running for %" PRIu32 " usec with all threads enabled.",
5432 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005433 }
5434 else
5435 {
5436 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005437 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005438 }
5439 }
Sean Callanana46ec452012-07-11 21:31:24 +00005440 else
5441 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005442 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005443 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005444 }
5445 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005446 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005447 "abandoning execution.",
5448 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005449 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005450
Jim Ingham0161b492013-02-09 01:29:05 +00005451 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5452 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5453 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5454 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5455 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005456
Jim Ingham0161b492013-02-09 01:29:05 +00005457 bool back_to_top = true;
5458 uint32_t try_halt_again = 0;
5459 bool do_halt = true;
5460 const uint32_t num_retries = 5;
5461 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005462 {
Jim Ingham0161b492013-02-09 01:29:05 +00005463 Error halt_error;
5464 if (do_halt)
5465 {
5466 if (log)
5467 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5468 halt_error = Halt();
5469 }
5470 if (halt_error.Success())
5471 {
5472 if (log)
5473 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005474
Jim Ingham0161b492013-02-09 01:29:05 +00005475 real_timeout = TimeValue::Now();
5476 real_timeout.OffsetWithMicroSeconds(500000);
5477
5478 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005479
Jim Ingham0161b492013-02-09 01:29:05 +00005480 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005481 {
Jim Ingham0161b492013-02-09 01:29:05 +00005482 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5483 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005484 {
Jim Ingham0161b492013-02-09 01:29:05 +00005485 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5486 if (stop_state == lldb::eStateStopped
5487 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5488 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005489 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005490
Jim Ingham0161b492013-02-09 01:29:05 +00005491 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005492 {
Jim Ingham0161b492013-02-09 01:29:05 +00005493 // Between the time we initiated the Halt and the time we delivered it, the process could have
5494 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005495
Jim Ingham0161b492013-02-09 01:29:05 +00005496 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5497 {
5498 if (log)
5499 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5500 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005501 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005502 back_to_top = false;
5503 break;
5504 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005505
Jim Ingham0161b492013-02-09 01:29:05 +00005506 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5507 {
5508 if (log)
5509 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5510 "Exiting wait loop.");
5511 try_halt_again++;
5512 do_halt = false;
5513 continue;
5514 }
Sean Callanana46ec452012-07-11 21:31:24 +00005515
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005516 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005517 {
5518 if (log)
5519 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005520 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005521 back_to_top = false;
5522 break;
5523 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005524
Jim Ingham0161b492013-02-09 01:29:05 +00005525 if (before_first_timeout)
5526 {
5527 // Set all the other threads to run, and return to the top of the loop, which will continue;
5528 before_first_timeout = false;
5529 thread_plan_sp->SetStopOthers (false);
5530 if (log)
5531 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005532
Jim Ingham0161b492013-02-09 01:29:05 +00005533 back_to_top = true;
5534 break;
5535 }
5536 else
5537 {
5538 // Running all threads failed, so return Interrupted.
5539 if (log)
5540 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005541 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005542 back_to_top = false;
5543 break;
5544 }
Sean Callanana46ec452012-07-11 21:31:24 +00005545 }
5546 }
5547 else
Jim Ingham0161b492013-02-09 01:29:05 +00005548 { if (log)
5549 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5550 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005551 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005552 back_to_top = false;
5553 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005554 }
5555 }
Jim Ingham0161b492013-02-09 01:29:05 +00005556 else
5557 {
5558 try_halt_again++;
5559 continue;
5560 }
Sean Callanana46ec452012-07-11 21:31:24 +00005561 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005562
Jim Ingham0161b492013-02-09 01:29:05 +00005563 if (!back_to_top || try_halt_again > num_retries)
5564 break;
5565 else
5566 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005567 }
Sean Callanana46ec452012-07-11 21:31:24 +00005568 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005569
Sean Callanana46ec452012-07-11 21:31:24 +00005570 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
Zachary Turner39de3112014-09-09 20:54:56 +00005571 if (backup_private_state_thread.GetState() != eThreadStateInvalid)
Sean Callanana46ec452012-07-11 21:31:24 +00005572 {
5573 StopPrivateStateThread();
5574 Error error;
5575 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005576 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005577 {
5578 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5579 }
5580 m_public_state.SetValueNoLock(old_state);
5581
5582 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005583
Jim Ingham184e9812013-01-15 02:47:48 +00005584 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5585 // could happen:
5586 // 1) The execution successfully completed
5587 // 2) We hit a breakpoint, and ignore_breakpoints was true
5588 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005589 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5590 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005591
Jim Ingham8646d3c2014-05-05 02:47:44 +00005592 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005593 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005594 {
5595 thread_plan_sp->RestoreThreadState();
5596 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005597
Sean Callanana46ec452012-07-11 21:31:24 +00005598 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005599 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005600 {
5601 if (log)
5602 {
5603 StreamString s;
5604 if (event_sp)
5605 event_sp->Dump (&s);
5606 else
5607 {
5608 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5609 }
5610
5611 StreamString ts;
5612
5613 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005614
Sean Callanana46ec452012-07-11 21:31:24 +00005615 do
5616 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005617 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005618 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005619 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005620 break;
5621 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005622 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005623 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005624 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005625 break;
5626 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005627 else
Sean Callanana46ec452012-07-11 21:31:24 +00005628 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005629 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5630
5631 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005632 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005633 event_explanation = "<no event data>";
5634 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005635 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005636
Jim Inghamcfc09352012-07-27 23:57:19 +00005637 Process *process = event_data->GetProcessSP().get();
5638
5639 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005640 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005641 event_explanation = "<no process>";
5642 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005643 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005644
Jim Inghamcfc09352012-07-27 23:57:19 +00005645 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005646
Jim Inghamcfc09352012-07-27 23:57:19 +00005647 uint32_t num_threads = thread_list.GetSize();
5648 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005649
Jim Inghamcfc09352012-07-27 23:57:19 +00005650 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005651
Jim Inghamcfc09352012-07-27 23:57:19 +00005652 for (thread_index = 0;
5653 thread_index < num_threads;
5654 ++thread_index)
5655 {
5656 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005657
Jim Inghamcfc09352012-07-27 23:57:19 +00005658 if (!thread)
5659 {
5660 ts.Printf("<?> ");
5661 continue;
5662 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005663
Daniel Malead01b2952012-11-29 21:49:15 +00005664 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005665 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005666
Jim Inghamcfc09352012-07-27 23:57:19 +00005667 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005668 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005669 else
5670 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005671
Jim Inghamcfc09352012-07-27 23:57:19 +00005672 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5673 if (stop_info_sp)
5674 {
5675 const char *stop_desc = stop_info_sp->GetDescription();
5676 if (stop_desc)
5677 ts.PutCString (stop_desc);
5678 }
5679 ts.Printf(">");
5680 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005681
Jim Inghamcfc09352012-07-27 23:57:19 +00005682 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005683 }
Sean Callanana46ec452012-07-11 21:31:24 +00005684 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005685
Jim Inghamcfc09352012-07-27 23:57:19 +00005686 if (event_explanation)
5687 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005688 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005689 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5690 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005691
Jim Inghame4483cf2013-09-27 01:13:01 +00005692 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005693 {
5694 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005695 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5696 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005697 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5698 thread_plan_sp->SetPrivate (orig_plan_private);
5699 }
5700 else
5701 {
5702 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005703 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5704 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005705 }
5706 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005707 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005708 {
5709 if (log)
5710 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005711
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005712 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005713 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005714 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005715 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005716 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005717 }
5718 else
5719 {
Sean Callanana46ec452012-07-11 21:31:24 +00005720 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005721 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005722 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005723 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005724 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005725 }
5726 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5727 {
5728 if (log)
5729 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005730 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005731 }
5732 else
5733 {
5734 if (log)
5735 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005736 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005737 {
5738 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005739 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005740 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5741 thread_plan_sp->SetPrivate (orig_plan_private);
5742 }
5743 }
5744 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005745
Sean Callanana46ec452012-07-11 21:31:24 +00005746 // Thread we ran the function in may have gone away because we ran the target
5747 // Check that it's still there, and if it is put it back in the context. Also restore the
5748 // frame in the context if it is still present.
5749 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5750 if (thread)
5751 {
5752 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5753 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005754
Sean Callanana46ec452012-07-11 21:31:24 +00005755 // Also restore the current process'es selected frame & thread, since this function calling may
5756 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005757
Sean Callanana46ec452012-07-11 21:31:24 +00005758 if (selected_tid != LLDB_INVALID_THREAD_ID)
5759 {
5760 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5761 {
5762 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005763 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005764 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005765 if (old_frame_sp)
5766 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005767 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005768 }
5769 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005770
Sean Callanana46ec452012-07-11 21:31:24 +00005771 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005772
Sean Callanana46ec452012-07-11 21:31:24 +00005773 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005774 {
Sean Callanana46ec452012-07-11 21:31:24 +00005775 if (log)
5776 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5777 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005778 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005779
Jim Inghamf48169b2010-11-30 02:22:11 +00005780 return return_value;
5781}
5782
5783const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005784Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005785{
5786 const char *result_name;
5787
5788 switch (result)
5789 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005790 case eExpressionCompleted:
5791 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005792 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005793 case eExpressionDiscarded:
5794 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005795 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005796 case eExpressionInterrupted:
5797 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005798 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005799 case eExpressionHitBreakpoint:
5800 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005801 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005802 case eExpressionSetupError:
5803 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005804 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005805 case eExpressionParseError:
5806 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005807 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005808 case eExpressionResultUnavailable:
5809 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005810 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005811 case eExpressionTimedOut:
5812 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005813 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005814 case eExpressionStoppedForDebug:
5815 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005816 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005817 }
5818 return result_name;
5819}
5820
Greg Clayton7260f622011-04-18 08:33:37 +00005821void
5822Process::GetStatus (Stream &strm)
5823{
5824 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005825 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005826 {
5827 if (state == eStateExited)
5828 {
5829 int exit_status = GetExitStatus();
5830 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005831 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005832 GetID(),
5833 exit_status,
5834 exit_status,
5835 exit_description ? exit_description : "");
5836 }
5837 else
5838 {
5839 if (state == eStateConnected)
5840 strm.Printf ("Connected to remote target.\n");
5841 else
Daniel Malead01b2952012-11-29 21:49:15 +00005842 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005843 }
5844 }
5845 else
5846 {
Daniel Malead01b2952012-11-29 21:49:15 +00005847 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005848 }
5849}
5850
5851size_t
5852Process::GetThreadStatus (Stream &strm,
5853 bool only_threads_with_stop_reason,
5854 uint32_t start_frame,
5855 uint32_t num_frames,
5856 uint32_t num_frames_with_source)
5857{
5858 size_t num_thread_infos_dumped = 0;
5859
Jim Ingham4a65fb12014-03-07 11:20:03 +00005860 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5861 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5862 // ID's, and look them up one by one:
5863
5864 uint32_t num_threads;
5865 std::vector<uint32_t> thread_index_array;
5866 //Scope for thread list locker;
5867 {
5868 Mutex::Locker locker (GetThreadList().GetMutex());
5869 ThreadList &curr_thread_list = GetThreadList();
5870 num_threads = curr_thread_list.GetSize();
5871 uint32_t idx;
5872 thread_index_array.resize(num_threads);
5873 for (idx = 0; idx < num_threads; ++idx)
5874 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5875 }
5876
Greg Clayton7260f622011-04-18 08:33:37 +00005877 for (uint32_t i = 0; i < num_threads; i++)
5878 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005879 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5880 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005881 {
5882 if (only_threads_with_stop_reason)
5883 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005884 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005885 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005886 continue;
5887 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005888 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005889 start_frame,
5890 num_frames,
5891 num_frames_with_source);
5892 ++num_thread_infos_dumped;
5893 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005894 else
5895 {
5896 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5897 if (log)
5898 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5899
5900 }
Greg Clayton7260f622011-04-18 08:33:37 +00005901 }
5902 return num_thread_infos_dumped;
5903}
5904
Greg Claytona9f40ad2012-02-22 04:37:26 +00005905void
5906Process::AddInvalidMemoryRegion (const LoadRange &region)
5907{
5908 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5909}
5910
5911bool
5912Process::RemoveInvalidMemoryRange (const LoadRange &region)
5913{
5914 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5915}
5916
Jim Ingham372787f2012-04-07 00:00:41 +00005917void
5918Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5919{
5920 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5921}
5922
5923bool
5924Process::RunPreResumeActions ()
5925{
5926 bool result = true;
5927 while (!m_pre_resume_actions.empty())
5928 {
5929 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5930 m_pre_resume_actions.pop_back();
5931 bool this_result = action.callback (action.baton);
5932 if (result == true) result = this_result;
5933 }
5934 return result;
5935}
5936
5937void
5938Process::ClearPreResumeActions ()
5939{
5940 m_pre_resume_actions.clear();
5941}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005942
Greg Claytonfa559e52012-05-18 02:38:05 +00005943void
5944Process::Flush ()
5945{
5946 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005947 m_extended_thread_list.Flush();
5948 m_extended_thread_stop_id = 0;
5949 m_queue_list.Clear();
5950 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005951}
Greg Clayton90ba8112012-12-05 00:16:59 +00005952
5953void
5954Process::DidExec ()
5955{
Todd Fiala76e0fc92014-08-27 22:58:26 +00005956 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5957 if (log)
5958 log->Printf ("Process::%s()", __FUNCTION__);
5959
Greg Clayton90ba8112012-12-05 00:16:59 +00005960 Target &target = GetTarget();
5961 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005962 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005963 m_dynamic_checkers_ap.reset();
5964 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005965 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005966 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005967 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005968 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005969 m_image_tokens.clear();
5970 m_allocated_memory_cache.Clear();
5971 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005972 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005973 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005974 DoDidExec();
5975 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005976 // Flush the process (threads and all stack frames) after running CompleteAttach()
5977 // in case the dynamic loader loaded things in new locations.
5978 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005979
5980 // After we figure out what was loaded/unloaded in CompleteAttach,
5981 // we need to let the target know so it can do any cleanup it needs to.
5982 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005983}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005984
Jim Ingham1460e4b2014-01-10 23:46:59 +00005985addr_t
5986Process::ResolveIndirectFunction(const Address *address, Error &error)
5987{
5988 if (address == nullptr)
5989 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00005990 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00005991 return LLDB_INVALID_ADDRESS;
5992 }
5993
5994 addr_t function_addr = LLDB_INVALID_ADDRESS;
5995
5996 addr_t addr = address->GetLoadAddress(&GetTarget());
5997 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5998 if (iter != m_resolved_indirect_addresses.end())
5999 {
6000 function_addr = (*iter).second;
6001 }
6002 else
6003 {
6004 if (!InferiorCall(this, address, function_addr))
6005 {
6006 Symbol *symbol = address->CalculateSymbolContextSymbol();
6007 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6008 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6009 function_addr = LLDB_INVALID_ADDRESS;
6010 }
6011 else
6012 {
6013 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6014 }
6015 }
6016 return function_addr;
6017}
6018
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006019void
6020Process::ModulesDidLoad (ModuleList &module_list)
6021{
6022 SystemRuntime *sys_runtime = GetSystemRuntime();
6023 if (sys_runtime)
6024 {
6025 sys_runtime->ModulesDidLoad (module_list);
6026 }
6027
6028 GetJITLoaders().ModulesDidLoad (module_list);
6029}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006030
6031ThreadCollectionSP
6032Process::GetHistoryThreads(lldb::addr_t addr)
6033{
6034 ThreadCollectionSP threads;
6035
6036 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6037
6038 if (! memory_history.get()) {
6039 return threads;
6040 }
6041
6042 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6043
6044 return threads;
6045}