blob: 55575f20846a72cf07622b1c84ab6c4588f3140b [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 (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000691 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000692 m_thread_mutex (Mutex::eMutexTypeRecursive),
693 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000695 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000696 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000697 m_queue_list (this),
698 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000700 m_image_tokens (),
701 m_listener (listener),
702 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000703 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000704 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000705 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000706 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000707 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000708 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000709 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000710 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000711 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
712 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000713 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000714 m_memory_cache (*this),
715 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000716 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000717 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000718 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000719 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000720 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000721 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000722 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000723 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000724 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000725 m_destroy_in_process (false),
726 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000728 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000729
Greg Clayton5160ce52013-03-27 23:08:40 +0000730 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000732 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733
Todd Fiala4ceced32014-08-29 17:35:57 +0000734 if (!m_unix_signals_sp)
735 m_unix_signals_sp.reset (new UnixSignals ());
736
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000737 SetEventName (eBroadcastBitStateChanged, "state-changed");
738 SetEventName (eBroadcastBitInterrupt, "interrupt");
739 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
740 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000741 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000742
Greg Clayton35a4cc52012-10-29 20:52:08 +0000743 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
744 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
745 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
746
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747 listener.StartListeningForEvents (this,
748 eBroadcastBitStateChanged |
749 eBroadcastBitInterrupt |
750 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000751 eBroadcastBitSTDERR |
752 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000753
754 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000755 eBroadcastBitStateChanged |
756 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757
758 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
759 eBroadcastInternalStateControlStop |
760 eBroadcastInternalStateControlPause |
761 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000762 // We need something valid here, even if just the default UnixSignalsSP.
763 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764}
765
766//----------------------------------------------------------------------
767// Destructor
768//----------------------------------------------------------------------
769Process::~Process()
770{
Greg Clayton5160ce52013-03-27 23:08:40 +0000771 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000773 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000775
776 // ThreadList::Clear() will try to acquire this process's mutex, so
777 // explicitly clear the thread list here to ensure that the mutex
778 // is not destroyed before the thread list.
779 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780}
781
Greg Clayton67cc0632012-08-22 17:17:09 +0000782const ProcessPropertiesSP &
783Process::GetGlobalProperties()
784{
785 static ProcessPropertiesSP g_settings_sp;
786 if (!g_settings_sp)
787 g_settings_sp.reset (new ProcessProperties (true));
788 return g_settings_sp;
789}
790
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791void
792Process::Finalize()
793{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000794 switch (GetPrivateState())
795 {
796 case eStateConnected:
797 case eStateAttaching:
798 case eStateLaunching:
799 case eStateStopped:
800 case eStateRunning:
801 case eStateStepping:
802 case eStateCrashed:
803 case eStateSuspended:
804 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000805 {
806 // FIXME: This will have to be a process setting:
807 bool keep_stopped = false;
808 Detach(keep_stopped);
809 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000810 else
811 Destroy();
812 break;
813
814 case eStateInvalid:
815 case eStateUnloaded:
816 case eStateDetached:
817 case eStateExited:
818 break;
819 }
820
Greg Clayton1ed54f52011-10-01 00:45:15 +0000821 // Clear our broadcaster before we proceed with destroying
822 Broadcaster::Clear();
823
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824 // Do any cleanup needed prior to being destructed... Subclasses
825 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000826
827 // We need to destroy the loader before the derived Process class gets destroyed
828 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000829 m_dynamic_checkers_ap.reset();
830 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000831 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000832 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000833 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000834 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000835 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000836 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000837 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000838 m_queue_list.Clear();
839 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000840 std::vector<Notifications> empty_notifications;
841 m_notifications.swap(empty_notifications);
842 m_image_tokens.clear();
843 m_memory_cache.Clear();
844 m_allocated_memory_cache.Clear();
845 m_language_runtimes.clear();
846 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +0000847//#ifdef LLDB_CONFIGURATION_DEBUG
848// StreamFile s(stdout, false);
849// EventSP event_sp;
850// while (m_private_state_listener.GetNextEvent(event_sp))
851// {
852// event_sp->Dump (&s);
853// s.EOL();
854// }
855//#endif
856 // We have to be very careful here as the m_private_state_listener might
857 // contain events that have ProcessSP values in them which can keep this
858 // process around forever. These events need to be cleared out.
859 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000860 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
861 m_public_run_lock.SetStopped();
862 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
863 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000864 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865}
866
867void
868Process::RegisterNotificationCallbacks (const Notifications& callbacks)
869{
870 m_notifications.push_back(callbacks);
871 if (callbacks.initialize != NULL)
872 callbacks.initialize (callbacks.baton, this);
873}
874
875bool
876Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
877{
878 std::vector<Notifications>::iterator pos, end = m_notifications.end();
879 for (pos = m_notifications.begin(); pos != end; ++pos)
880 {
881 if (pos->baton == callbacks.baton &&
882 pos->initialize == callbacks.initialize &&
883 pos->process_state_changed == callbacks.process_state_changed)
884 {
885 m_notifications.erase(pos);
886 return true;
887 }
888 }
889 return false;
890}
891
892void
893Process::SynchronouslyNotifyStateChanged (StateType state)
894{
895 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
896 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
897 {
898 if (notification_pos->process_state_changed)
899 notification_pos->process_state_changed (notification_pos->baton, this, state);
900 }
901}
902
903// FIXME: We need to do some work on events before the general Listener sees them.
904// For instance if we are continuing from a breakpoint, we need to ensure that we do
905// the little "insert real insn, step & stop" trick. But we can't do that when the
906// event is delivered by the broadcaster - since that is done on the thread that is
907// waiting for new events, so if we needed more than one event for our handling, we would
908// stall. So instead we do it when we fetch the event off of the queue.
909//
910
911StateType
912Process::GetNextEvent (EventSP &event_sp)
913{
914 StateType state = eStateInvalid;
915
916 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
917 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
918
919 return state;
920}
921
Todd Fialaa3b89e22014-08-12 14:33:19 +0000922bool
923Process::SyncIOHandler (uint64_t timeout_msec)
924{
925 bool timed_out = false;
926
927 // don't sync (potentially context switch) in case where there is no process IO
928 if (m_process_input_reader)
929 {
930 TimeValue timeout = TimeValue::Now();
931 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
932
933 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
934
935 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
936 if(log)
937 {
938 if(timed_out)
939 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
940 else
941 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
942 }
943
944 // reset sync one-shot so it will be ready for next time
945 m_iohandler_sync.SetValue(false, eBroadcastNever);
946 }
947
948 return !timed_out;
949}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000950
951StateType
Greg Clayton44d93782014-01-27 23:43:24 +0000952Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953{
Jim Ingham4b536182011-08-09 02:12:22 +0000954 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
955 // We have to actually check each event, and in the case of a stopped event check the restarted flag
956 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000957 if (event_sp_ptr)
958 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000959 StateType state = GetState();
960 // If we are exited or detached, we won't ever get back to any
961 // other valid state...
962 if (state == eStateDetached || state == eStateExited)
963 return state;
964
Daniel Malea9e9919f2013-10-09 16:56:28 +0000965 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
966 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000967 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
968 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000969
970 if (!wait_always &&
971 StateIsStoppedState(state, true) &&
972 StateIsStoppedState(GetPrivateState(), true)) {
973 if (log)
974 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
975 __FUNCTION__);
976 return state;
977 }
978
Jim Ingham4b536182011-08-09 02:12:22 +0000979 while (state != eStateInvalid)
980 {
Greg Clayton85fb1b92012-09-11 02:33:37 +0000981 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +0000982 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +0000983 if (event_sp_ptr && event_sp)
984 *event_sp_ptr = event_sp;
985
Jim Ingham4b536182011-08-09 02:12:22 +0000986 switch (state)
987 {
988 case eStateCrashed:
989 case eStateDetached:
990 case eStateExited:
991 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +0000992 // We need to toggle the run lock as this won't get done in
993 // SetPublicState() if the process is hijacked.
994 if (hijack_listener)
995 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +0000996 return state;
997 case eStateStopped:
998 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
999 continue;
1000 else
Greg Clayton44d93782014-01-27 23:43:24 +00001001 {
1002 // We need to toggle the run lock as this won't get done in
1003 // SetPublicState() if the process is hijacked.
1004 if (hijack_listener)
1005 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001006 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001007 }
Jim Ingham4b536182011-08-09 02:12:22 +00001008 default:
1009 continue;
1010 }
1011 }
1012 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013}
1014
1015
1016StateType
1017Process::WaitForState
1018(
1019 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001020 const StateType *match_states,
1021 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001022)
1023{
1024 EventSP event_sp;
1025 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001026 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027 while (state != eStateInvalid)
1028 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001029 // If we are exited or detached, we won't ever get back to any
1030 // other valid state...
1031 if (state == eStateDetached || state == eStateExited)
1032 return state;
1033
Greg Clayton44d93782014-01-27 23:43:24 +00001034 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035
1036 for (i=0; i<num_match_states; ++i)
1037 {
1038 if (match_states[i] == state)
1039 return state;
1040 }
1041 }
1042 return state;
1043}
1044
Jim Ingham30f9b212010-10-11 23:53:14 +00001045bool
1046Process::HijackProcessEvents (Listener *listener)
1047{
1048 if (listener != NULL)
1049 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001050 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001051 }
1052 else
1053 return false;
1054}
1055
1056void
1057Process::RestoreProcessEvents ()
1058{
1059 RestoreBroadcaster();
1060}
1061
Jim Ingham0f16e732011-02-08 05:20:59 +00001062bool
1063Process::HijackPrivateProcessEvents (Listener *listener)
1064{
1065 if (listener != NULL)
1066 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001067 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001068 }
1069 else
1070 return false;
1071}
1072
1073void
1074Process::RestorePrivateProcessEvents ()
1075{
1076 m_private_state_broadcaster.RestoreBroadcaster();
1077}
1078
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001079StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001080Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081{
Greg Clayton5160ce52013-03-27 23:08:40 +00001082 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083
1084 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001085 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1086 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001087
Greg Clayton44d93782014-01-27 23:43:24 +00001088 Listener *listener = hijack_listener;
1089 if (listener == NULL)
1090 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001091
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001093 if (listener->WaitForEventForBroadcasterWithType (timeout,
1094 this,
1095 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1096 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001097 {
1098 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1099 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1100 else if (log)
1101 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1102 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103
1104 if (log)
1105 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001106 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107 StateAsCString(state));
1108 return state;
1109}
1110
1111Event *
1112Process::PeekAtStateChangedEvents ()
1113{
Greg Clayton5160ce52013-03-27 23:08:40 +00001114 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115
1116 if (log)
1117 log->Printf ("Process::%s...", __FUNCTION__);
1118
1119 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001120 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1121 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 if (log)
1123 {
1124 if (event_ptr)
1125 {
1126 log->Printf ("Process::%s (event_ptr) => %s",
1127 __FUNCTION__,
1128 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1129 }
1130 else
1131 {
1132 log->Printf ("Process::%s no events found",
1133 __FUNCTION__);
1134 }
1135 }
1136 return event_ptr;
1137}
1138
1139StateType
1140Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1141{
Greg Clayton5160ce52013-03-27 23:08:40 +00001142 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143
1144 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001145 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1146 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147
1148 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001149 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1150 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001151 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001152 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001153 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1154 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155
1156 // This is a bit of a hack, but when we wait here we could very well return
1157 // to the command-line, and that could disable the log, which would render the
1158 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001159 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001160 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1161 __FUNCTION__, static_cast<const void *>(timeout),
1162 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163 return state;
1164}
1165
1166bool
1167Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1168{
Greg Clayton5160ce52013-03-27 23:08:40 +00001169 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001170
1171 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001172 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1173 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174
1175 if (control_only)
1176 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1177 else
1178 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1179}
1180
1181bool
1182Process::IsRunning () const
1183{
1184 return StateIsRunningState (m_public_state.GetValue());
1185}
1186
1187int
1188Process::GetExitStatus ()
1189{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001190 Mutex::Locker locker (m_exit_status_mutex);
1191
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 if (m_public_state.GetValue() == eStateExited)
1193 return m_exit_status;
1194 return -1;
1195}
1196
Greg Clayton85851dd2010-12-04 00:10:17 +00001197
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198const char *
1199Process::GetExitDescription ()
1200{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001201 Mutex::Locker locker (m_exit_status_mutex);
1202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1204 return m_exit_string.c_str();
1205 return NULL;
1206}
1207
Greg Clayton6779606a2011-01-22 23:43:18 +00001208bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209Process::SetExitStatus (int status, const char *cstr)
1210{
Greg Clayton5160ce52013-03-27 23:08:40 +00001211 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001212 if (log)
1213 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1214 status, status,
1215 cstr ? "\"" : "",
1216 cstr ? cstr : "NULL",
1217 cstr ? "\"" : "");
1218
Greg Clayton6779606a2011-01-22 23:43:18 +00001219 // We were already in the exited state
1220 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001221 {
Greg Clayton385d6032011-01-26 23:47:29 +00001222 if (log)
1223 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001224 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001225 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001226
Todd Fiala7b0917a2014-09-15 20:07:33 +00001227 // use a mutex to protect the status and string during updating
1228 {
1229 Mutex::Locker locker (m_exit_status_mutex);
1230
1231 m_exit_status = status;
1232 if (cstr)
1233 m_exit_string = cstr;
1234 else
1235 m_exit_string.clear();
1236 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001237
Greg Clayton6779606a2011-01-22 23:43:18 +00001238 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001239
Greg Clayton6779606a2011-01-22 23:43:18 +00001240 SetPrivateState (eStateExited);
1241 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001242}
1243
1244// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001245// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001246// found in the global target list (we want to be completely sure that the
1247// lldb_private::Process doesn't go away before we can deliver the signal.
1248bool
Greg Claytone4e45922011-11-16 05:37:56 +00001249Process::SetProcessExitStatus (void *callback_baton,
1250 lldb::pid_t pid,
1251 bool exited,
1252 int signo, // Zero for no signal
1253 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001254)
1255{
Greg Clayton5160ce52013-03-27 23:08:40 +00001256 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001257 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001258 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001259 callback_baton,
1260 pid,
1261 exited,
1262 signo,
1263 exit_status);
1264
1265 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266 {
Greg Clayton66111032010-06-23 01:19:29 +00001267 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268 if (target_sp)
1269 {
1270 ProcessSP process_sp (target_sp->GetProcessSP());
1271 if (process_sp)
1272 {
1273 const char *signal_cstr = NULL;
1274 if (signo)
1275 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1276
1277 process_sp->SetExitStatus (exit_status, signal_cstr);
1278 }
1279 }
1280 return true;
1281 }
1282 return false;
1283}
1284
1285
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001286void
1287Process::UpdateThreadListIfNeeded ()
1288{
1289 const uint32_t stop_id = GetStopID();
1290 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1291 {
Greg Clayton2637f822011-11-17 01:23:07 +00001292 const StateType state = GetPrivateState();
1293 if (StateIsStoppedState (state, true))
1294 {
1295 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001296 // m_thread_list does have its own mutex, but we need to
1297 // hold onto the mutex between the call to UpdateThreadList(...)
1298 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001299 ThreadList &old_thread_list = m_thread_list;
1300 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001301 ThreadList new_thread_list(this);
1302 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001303 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001304 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001305 {
Jim Ingham09437922013-03-01 20:04:25 +00001306 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1307 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1308 // shutting us down, causing a deadlock.
1309 if (!m_destroy_in_process)
1310 {
1311 OperatingSystem *os = GetOperatingSystem ();
1312 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001313 {
1314 // Clear any old backing threads where memory threads might have been
1315 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001316 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001317 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001318 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001319
1320 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001321 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1322 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1323 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 +00001324 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001325 else
1326 {
1327 // No OS plug-in, the new thread list is the same as the real thread list
1328 new_thread_list = real_thread_list;
1329 }
Jim Ingham09437922013-03-01 20:04:25 +00001330 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001331
1332 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001333 m_thread_list.Update (new_thread_list);
1334 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001335
Jason Molenda4ff13262013-11-20 00:31:38 +00001336 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1337 {
1338 // Clear any extended threads that we may have accumulated previously
1339 m_extended_thread_list.Clear();
1340 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001341
1342 m_queue_list.Clear();
1343 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001344 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001345 }
Greg Clayton2637f822011-11-17 01:23:07 +00001346 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001347 }
1348}
1349
Jason Molenda5e8dce42013-12-13 00:29:16 +00001350void
1351Process::UpdateQueueListIfNeeded ()
1352{
1353 if (m_system_runtime_ap.get())
1354 {
1355 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1356 {
1357 const StateType state = GetPrivateState();
1358 if (StateIsStoppedState (state, true))
1359 {
1360 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1361 m_queue_list_stop_id = GetLastNaturalStopID();
1362 }
1363 }
1364 }
1365}
1366
Greg Claytona4d87472013-01-18 23:41:08 +00001367ThreadSP
1368Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1369{
1370 OperatingSystem *os = GetOperatingSystem ();
1371 if (os)
1372 return os->CreateThread(tid, context);
1373 return ThreadSP();
1374}
1375
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001376uint32_t
1377Process::GetNextThreadIndexID (uint64_t thread_id)
1378{
1379 return AssignIndexIDToThread(thread_id);
1380}
1381
1382bool
1383Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1384{
1385 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1386 if (iterator == m_thread_id_to_index_id_map.end())
1387 {
1388 return false;
1389 }
1390 else
1391 {
1392 return true;
1393 }
1394}
1395
1396uint32_t
1397Process::AssignIndexIDToThread(uint64_t thread_id)
1398{
1399 uint32_t result = 0;
1400 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1401 if (iterator == m_thread_id_to_index_id_map.end())
1402 {
1403 result = ++m_thread_index_id;
1404 m_thread_id_to_index_id_map[thread_id] = result;
1405 }
1406 else
1407 {
1408 result = iterator->second;
1409 }
1410
1411 return result;
1412}
1413
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414StateType
1415Process::GetState()
1416{
1417 // If any other threads access this we will need a mutex for it
1418 return m_public_state.GetValue ();
1419}
1420
1421void
Jim Ingham221d51c2013-05-08 00:35:16 +00001422Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423{
Greg Clayton5160ce52013-03-27 23:08:40 +00001424 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001426 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001427 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001428 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001429
1430 // On the transition from Run to Stopped, we unlock the writer end of the
1431 // run lock. The lock gets locked in Resume, which is the public API
1432 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001433 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1434 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001435 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001436 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001437 if (log)
1438 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001439 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001440 }
1441 else
1442 {
1443 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1444 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001445 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001446 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001447 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001448 {
1449 if (log)
1450 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001451 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001452 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001453 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001454 }
1455 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456}
1457
Jim Ingham3b8285d2012-04-19 01:40:33 +00001458Error
1459Process::Resume ()
1460{
Greg Clayton5160ce52013-03-27 23:08:40 +00001461 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001462 if (log)
1463 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001464 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001465 {
1466 Error error("Resume request failed - process still running.");
1467 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001468 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001469 return error;
1470 }
1471 return PrivateResume();
1472}
1473
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474StateType
1475Process::GetPrivateState ()
1476{
1477 return m_private_state.GetValue();
1478}
1479
1480void
1481Process::SetPrivateState (StateType new_state)
1482{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001483 if (m_finalize_called)
1484 return;
1485
Greg Clayton5160ce52013-03-27 23:08:40 +00001486 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001487 bool state_changed = false;
1488
1489 if (log)
1490 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1491
Andrew Kaylor29d65742013-05-10 17:19:04 +00001492 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493 Mutex::Locker locker(m_private_state.GetMutex());
1494
1495 const StateType old_state = m_private_state.GetValueNoLock ();
1496 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001497
Greg Claytonaa49c832013-05-03 22:25:56 +00001498 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1499 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1500 if (old_state_is_stopped != new_state_is_stopped)
1501 {
1502 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001503 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001504 else
Ed Maste64fad602013-07-29 20:58:06 +00001505 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001506 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001507
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508 if (state_changed)
1509 {
1510 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001511 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001513 // Note, this currently assumes that all threads in the list
1514 // stop when the process stops. In the future we will want to
1515 // support a debugging model where some threads continue to run
1516 // while others are stopped. When that happens we will either need
1517 // a way for the thread list to identify which threads are stopping
1518 // or create a special thread list containing only threads which
1519 // actually stopped.
1520 //
1521 // The process plugin is responsible for managing the actual
1522 // behavior of the threads and should have stopped any threads
1523 // that are going to stop before we get here.
1524 m_thread_list.DidStop();
1525
Jim Ingham4b536182011-08-09 02:12:22 +00001526 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001527 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001528 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001529 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 }
1531 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001532 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1533 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1534 else
1535 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536 }
1537 else
1538 {
1539 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001540 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001541 }
1542}
1543
Jim Ingham0faa43f2011-11-08 03:00:11 +00001544void
1545Process::SetRunningUserExpression (bool on)
1546{
1547 m_mod_id.SetRunningUserExpression (on);
1548}
1549
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001550addr_t
1551Process::GetImageInfoAddress()
1552{
1553 return LLDB_INVALID_ADDRESS;
1554}
1555
Greg Clayton8f343b02010-11-04 01:54:29 +00001556//----------------------------------------------------------------------
1557// LoadImage
1558//
1559// This function provides a default implementation that works for most
1560// unix variants. Any Process subclasses that need to do shared library
1561// loading differently should override LoadImage and UnloadImage and
1562// do what is needed.
1563//----------------------------------------------------------------------
1564uint32_t
1565Process::LoadImage (const FileSpec &image_spec, Error &error)
1566{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001567 char path[PATH_MAX];
1568 image_spec.GetPath(path, sizeof(path));
1569
Greg Clayton8f343b02010-11-04 01:54:29 +00001570 DynamicLoader *loader = GetDynamicLoader();
1571 if (loader)
1572 {
1573 error = loader->CanLoadImage();
1574 if (error.Fail())
1575 return LLDB_INVALID_IMAGE_TOKEN;
1576 }
1577
1578 if (error.Success())
1579 {
1580 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001581
1582 if (thread_sp)
1583 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001584 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001585
1586 if (frame_sp)
1587 {
1588 ExecutionContext exe_ctx;
1589 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001590 EvaluateExpressionOptions expr_options;
1591 expr_options.SetUnwindOnError(true);
1592 expr_options.SetIgnoreBreakpoints(true);
1593 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001594 expr_options.SetResultIsInternal(true);
1595
Greg Clayton8f343b02010-11-04 01:54:29 +00001596 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001597 expr.Printf(R"(
1598 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1599 the_result.image_ptr = dlopen ("%s", 2);
1600 if (the_result.image_ptr == (void *) 0x0)
1601 {
1602 the_result.error_str = dlerror();
1603 }
1604 else
1605 {
1606 the_result.error_str = (const char *) 0x0;
1607 }
1608 the_result;
1609 )",
1610 path);
1611 const char *prefix = R"(
1612 extern "C" void* dlopen (const char *path, int mode);
1613 extern "C" const char *dlerror (void);
1614 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001615 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001616 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001617 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001618 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001619 expr.GetData(),
1620 prefix,
1621 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001622 expr_error);
1623 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001624 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001625 error = result_valobj_sp->GetError();
1626 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001627 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001628 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001629 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1630 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001631 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001632 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1633 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1634 {
1635 uint32_t image_token = m_image_tokens.size();
1636 m_image_tokens.push_back (image_ptr);
1637 return image_token;
1638 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001639 else if (image_ptr == 0)
1640 {
Jim Ingham6971b862014-07-19 00:37:06 +00001641 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1642 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001643 {
Jim Ingham6971b862014-07-19 00:37:06 +00001644 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001645 {
Jim Inghamcf973792014-07-17 21:53:48 +00001646 StreamString s;
Jim Ingham6971b862014-07-19 00:37:06 +00001647 size_t num_chars = error_str_sp->ReadPointedString (s, error);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001648 if (error.Success() && num_chars > 0)
1649 {
1650 error.Clear();
Jim Ingham6971b862014-07-19 00:37:06 +00001651 error.SetErrorStringWithFormat("dlopen error: %s", s.GetData());
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001652 }
1653 }
1654 }
1655 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001656 }
1657 }
1658 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001659 else
1660 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001661 }
1662 }
1663 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001664 if (!error.AsCString())
1665 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001666 return LLDB_INVALID_IMAGE_TOKEN;
1667}
1668
1669//----------------------------------------------------------------------
1670// UnloadImage
1671//
1672// This function provides a default implementation that works for most
1673// unix variants. Any Process subclasses that need to do shared library
1674// loading differently should override LoadImage and UnloadImage and
1675// do what is needed.
1676//----------------------------------------------------------------------
1677Error
1678Process::UnloadImage (uint32_t image_token)
1679{
1680 Error error;
1681 if (image_token < m_image_tokens.size())
1682 {
1683 const addr_t image_addr = m_image_tokens[image_token];
1684 if (image_addr == LLDB_INVALID_ADDRESS)
1685 {
1686 error.SetErrorString("image already unloaded");
1687 }
1688 else
1689 {
1690 DynamicLoader *loader = GetDynamicLoader();
1691 if (loader)
1692 error = loader->CanLoadImage();
1693
1694 if (error.Success())
1695 {
1696 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001697
1698 if (thread_sp)
1699 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001700 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001701
1702 if (frame_sp)
1703 {
1704 ExecutionContext exe_ctx;
1705 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001706 EvaluateExpressionOptions expr_options;
1707 expr_options.SetUnwindOnError(true);
1708 expr_options.SetIgnoreBreakpoints(true);
1709 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001710 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001711 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001712 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001713 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001714 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001715 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001716 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001717 expr.GetData(),
1718 prefix,
1719 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001720 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001721 if (result_valobj_sp->GetError().Success())
1722 {
1723 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001724 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001725 {
1726 if (scalar.UInt(1))
1727 {
1728 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1729 }
1730 else
1731 {
1732 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1733 }
1734 }
1735 }
1736 else
1737 {
1738 error = result_valobj_sp->GetError();
1739 }
1740 }
1741 }
1742 }
1743 }
1744 }
1745 else
1746 {
1747 error.SetErrorString("invalid image token");
1748 }
1749 return error;
1750}
1751
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001752const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001753Process::GetABI()
1754{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001755 if (!m_abi_sp)
1756 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1757 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001758}
1759
Jim Ingham22777012010-09-23 02:01:19 +00001760LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001761Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001762{
1763 LanguageRuntimeCollection::iterator pos;
1764 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001765 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001766 {
Jim Inghamab175242012-03-10 00:22:19 +00001767 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001768
Jim Inghamab175242012-03-10 00:22:19 +00001769 m_language_runtimes[language] = runtime_sp;
1770 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001771 }
1772 else
1773 return (*pos).second.get();
1774}
1775
1776CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001777Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001778{
Jim Inghamab175242012-03-10 00:22:19 +00001779 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001780 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1781 return static_cast<CPPLanguageRuntime *> (runtime);
1782 return NULL;
1783}
1784
1785ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001786Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001787{
Jim Inghamab175242012-03-10 00:22:19 +00001788 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001789 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1790 return static_cast<ObjCLanguageRuntime *> (runtime);
1791 return NULL;
1792}
1793
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001794bool
1795Process::IsPossibleDynamicValue (ValueObject& in_value)
1796{
1797 if (in_value.IsDynamic())
1798 return false;
1799 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1800
1801 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1802 {
1803 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1804 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1805 }
1806
1807 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1808 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1809 return true;
1810
1811 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1812 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1813}
1814
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001815BreakpointSiteList &
1816Process::GetBreakpointSiteList()
1817{
1818 return m_breakpoint_site_list;
1819}
1820
1821const BreakpointSiteList &
1822Process::GetBreakpointSiteList() const
1823{
1824 return m_breakpoint_site_list;
1825}
1826
1827
1828void
1829Process::DisableAllBreakpointSites ()
1830{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001831 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1832// bp_site->SetEnabled(true);
1833 DisableBreakpointSite(bp_site);
1834 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835}
1836
1837Error
1838Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1839{
1840 Error error (DisableBreakpointSiteByID (break_id));
1841
1842 if (error.Success())
1843 m_breakpoint_site_list.Remove(break_id);
1844
1845 return error;
1846}
1847
1848Error
1849Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1850{
1851 Error error;
1852 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1853 if (bp_site_sp)
1854 {
1855 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001856 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857 }
1858 else
1859 {
Daniel Malead01b2952012-11-29 21:49:15 +00001860 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001861 }
1862
1863 return error;
1864}
1865
1866Error
1867Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1868{
1869 Error error;
1870 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1871 if (bp_site_sp)
1872 {
1873 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001874 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001875 }
1876 else
1877 {
Daniel Malead01b2952012-11-29 21:49:15 +00001878 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001879 }
1880 return error;
1881}
1882
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001883lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001884Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001885{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001886 addr_t load_addr = LLDB_INVALID_ADDRESS;
1887
1888 bool show_error = true;
1889 switch (GetState())
1890 {
1891 case eStateInvalid:
1892 case eStateUnloaded:
1893 case eStateConnected:
1894 case eStateAttaching:
1895 case eStateLaunching:
1896 case eStateDetached:
1897 case eStateExited:
1898 show_error = false;
1899 break;
1900
1901 case eStateStopped:
1902 case eStateRunning:
1903 case eStateStepping:
1904 case eStateCrashed:
1905 case eStateSuspended:
1906 show_error = IsAlive();
1907 break;
1908 }
1909
1910 // Reset the IsIndirect flag here, in case the location changes from
1911 // pointing to a indirect symbol to a regular symbol.
1912 owner->SetIsIndirect (false);
1913
1914 if (owner->ShouldResolveIndirectFunctions())
1915 {
1916 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1917 if (symbol && symbol->IsIndirect())
1918 {
1919 Error error;
1920 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
1921 if (!error.Success() && show_error)
1922 {
Greg Clayton44d93782014-01-27 23:43:24 +00001923 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1924 symbol->GetAddress().GetLoadAddress(&m_target),
1925 owner->GetBreakpoint().GetID(),
1926 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001927 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00001928 return LLDB_INVALID_BREAK_ID;
1929 }
1930 Address resolved_address(load_addr);
1931 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
1932 owner->SetIsIndirect(true);
1933 }
1934 else
1935 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1936 }
1937 else
1938 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
1939
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940 if (load_addr != LLDB_INVALID_ADDRESS)
1941 {
1942 BreakpointSiteSP bp_site_sp;
1943
1944 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1945 // create a new breakpoint site and add it.
1946
1947 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1948
1949 if (bp_site_sp)
1950 {
1951 bp_site_sp->AddOwner (owner);
1952 owner->SetBreakpointSite (bp_site_sp);
1953 return bp_site_sp->GetID();
1954 }
1955 else
1956 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001957 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 if (bp_site_sp)
1959 {
Greg Claytoneb023e72013-10-11 19:48:25 +00001960 Error error = EnableBreakpointSite (bp_site_sp.get());
1961 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001962 {
1963 owner->SetBreakpointSite (bp_site_sp);
1964 return m_breakpoint_site_list.Add (bp_site_sp);
1965 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001966 else
1967 {
Greg Claytonfbb76342013-11-20 21:07:01 +00001968 if (show_error)
1969 {
1970 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00001971 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
1972 load_addr,
1973 owner->GetBreakpoint().GetID(),
1974 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00001975 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00001976 }
Greg Claytoneb023e72013-10-11 19:48:25 +00001977 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978 }
1979 }
1980 }
1981 // We failed to enable the breakpoint
1982 return LLDB_INVALID_BREAK_ID;
1983
1984}
1985
1986void
1987Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1988{
1989 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1990 if (num_owners == 0)
1991 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00001992 // Don't try to disable the site if we don't have a live process anymore.
1993 if (IsAlive())
1994 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001995 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1996 }
1997}
1998
1999
2000size_t
2001Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2002{
2003 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002004 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005
Jim Ingham20c77192011-06-29 19:42:28 +00002006 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002008 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2009 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002010 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002011 addr_t intersect_addr;
2012 size_t intersect_size;
2013 size_t opcode_offset;
2014 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002015 {
2016 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2017 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002018 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002019 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002020 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002021 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002022 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002023 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 }
2025 return bytes_removed;
2026}
2027
2028
Greg Claytonded470d2011-03-19 01:12:21 +00002029
2030size_t
2031Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2032{
2033 PlatformSP platform_sp (m_target.GetPlatform());
2034 if (platform_sp)
2035 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2036 return 0;
2037}
2038
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002039Error
2040Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2041{
2042 Error error;
2043 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002044 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002045 const addr_t bp_addr = bp_site->GetLoadAddress();
2046 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002047 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048 if (bp_site->IsEnabled())
2049 {
2050 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002051 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 +00002052 return error;
2053 }
2054
2055 if (bp_addr == LLDB_INVALID_ADDRESS)
2056 {
2057 error.SetErrorString("BreakpointSite contains an invalid load address.");
2058 return error;
2059 }
2060 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2061 // trap for the breakpoint site
2062 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2063
2064 if (bp_opcode_size == 0)
2065 {
Daniel Malead01b2952012-11-29 21:49:15 +00002066 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002067 }
2068 else
2069 {
2070 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2071
2072 if (bp_opcode_bytes == NULL)
2073 {
2074 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2075 return error;
2076 }
2077
2078 // Save the original opcode by reading it
2079 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2080 {
2081 // Write a software breakpoint in place of the original opcode
2082 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2083 {
2084 uint8_t verify_bp_opcode_bytes[64];
2085 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2086 {
2087 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2088 {
2089 bp_site->SetEnabled(true);
2090 bp_site->SetType (BreakpointSite::eSoftware);
2091 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002092 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002093 bp_site->GetID(),
2094 (uint64_t)bp_addr);
2095 }
2096 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002097 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098 }
2099 else
2100 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2101 }
2102 else
2103 error.SetErrorString("Unable to write breakpoint trap to memory.");
2104 }
2105 else
2106 error.SetErrorString("Unable to read memory at breakpoint address.");
2107 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002108 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002109 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002110 bp_site->GetID(),
2111 (uint64_t)bp_addr,
2112 error.AsCString());
2113 return error;
2114}
2115
2116Error
2117Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2118{
2119 Error error;
2120 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002121 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002122 addr_t bp_addr = bp_site->GetLoadAddress();
2123 lldb::user_id_t breakID = bp_site->GetID();
2124 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002125 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126
2127 if (bp_site->IsHardware())
2128 {
2129 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2130 }
2131 else if (bp_site->IsEnabled())
2132 {
2133 const size_t break_op_size = bp_site->GetByteSize();
2134 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2135 if (break_op_size > 0)
2136 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002137 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002138 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002139 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002140 bool break_op_found = false;
2141
2142 // Read the breakpoint opcode
2143 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2144 {
2145 bool verify = false;
2146 // Make sure we have the a breakpoint opcode exists at this address
2147 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2148 {
2149 break_op_found = true;
2150 // We found a valid breakpoint opcode at this address, now restore
2151 // the saved opcode.
2152 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2153 {
2154 verify = true;
2155 }
2156 else
2157 error.SetErrorString("Memory write failed when restoring original opcode.");
2158 }
2159 else
2160 {
2161 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2162 // Set verify to true and so we can check if the original opcode has already been restored
2163 verify = true;
2164 }
2165
2166 if (verify)
2167 {
Greg Claytonc982c762010-07-09 20:39:50 +00002168 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002169 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002170 // Verify that our original opcode made it back to the inferior
2171 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2172 {
2173 // compare the memory we just read with the original opcode
2174 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2175 {
2176 // SUCCESS
2177 bp_site->SetEnabled(false);
2178 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002179 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 +00002180 return error;
2181 }
2182 else
2183 {
2184 if (break_op_found)
2185 error.SetErrorString("Failed to restore original opcode.");
2186 }
2187 }
2188 else
2189 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2190 }
2191 }
2192 else
2193 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2194 }
2195 }
2196 else
2197 {
2198 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002199 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 +00002200 return error;
2201 }
2202
2203 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002204 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002205 bp_site->GetID(),
2206 (uint64_t)bp_addr,
2207 error.AsCString());
2208 return error;
2209
2210}
2211
Greg Clayton58be07b2011-01-07 06:08:19 +00002212// Uncomment to verify memory caching works after making changes to caching code
2213//#define VERIFY_MEMORY_READS
2214
Sean Callanan64c0cf22012-06-07 22:26:42 +00002215size_t
2216Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2217{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002218 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002219 if (!GetDisableMemoryCache())
2220 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002221#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002222 // Memory caching is enabled, with debug verification
2223
2224 if (buf && size)
2225 {
2226 // Uncomment the line below to make sure memory caching is working.
2227 // I ran this through the test suite and got no assertions, so I am
2228 // pretty confident this is working well. If any changes are made to
2229 // memory caching, uncomment the line below and test your changes!
2230
2231 // Verify all memory reads by using the cache first, then redundantly
2232 // reading the same memory from the inferior and comparing to make sure
2233 // everything is exactly the same.
2234 std::string verify_buf (size, '\0');
2235 assert (verify_buf.size() == size);
2236 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2237 Error verify_error;
2238 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2239 assert (cache_bytes_read == verify_bytes_read);
2240 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2241 assert (verify_error.Success() == error.Success());
2242 return cache_bytes_read;
2243 }
2244 return 0;
2245#else // !defined(VERIFY_MEMORY_READS)
2246 // Memory caching is enabled, without debug verification
2247
2248 return m_memory_cache.Read (addr, buf, size, error);
2249#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002250 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002251 else
2252 {
2253 // Memory caching is disabled
2254
2255 return ReadMemoryFromInferior (addr, buf, size, error);
2256 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002257}
Greg Clayton58be07b2011-01-07 06:08:19 +00002258
Greg Clayton4c82d422012-05-18 23:20:01 +00002259size_t
2260Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2261{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002262 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002263 out_str.clear();
2264 addr_t curr_addr = addr;
2265 while (1)
2266 {
2267 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2268 if (length == 0)
2269 break;
2270 out_str.append(buf, length);
2271 // If we got "length - 1" bytes, we didn't get the whole C string, we
2272 // need to read some more characters
2273 if (length == sizeof(buf) - 1)
2274 curr_addr += length;
2275 else
2276 break;
2277 }
2278 return out_str.size();
2279}
2280
Greg Clayton58be07b2011-01-07 06:08:19 +00002281
2282size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002283Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2284 size_t type_width)
2285{
2286 size_t total_bytes_read = 0;
2287 if (dst && max_bytes && type_width && max_bytes >= type_width)
2288 {
2289 // Ensure a null terminator independent of the number of bytes that is read.
2290 memset (dst, 0, max_bytes);
2291 size_t bytes_left = max_bytes - type_width;
2292
2293 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2294 assert(sizeof(terminator) >= type_width &&
2295 "Attempting to validate a string with more than 4 bytes per character!");
2296
2297 addr_t curr_addr = addr;
2298 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2299 char *curr_dst = dst;
2300
2301 error.Clear();
2302 while (bytes_left > 0 && error.Success())
2303 {
2304 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2305 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2306 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2307
2308 if (bytes_read == 0)
2309 break;
2310
2311 // Search for a null terminator of correct size and alignment in bytes_read
2312 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2313 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2314 if (::strncmp(&dst[i], terminator, type_width) == 0)
2315 {
2316 error.Clear();
2317 return i;
2318 }
2319
2320 total_bytes_read += bytes_read;
2321 curr_dst += bytes_read;
2322 curr_addr += bytes_read;
2323 bytes_left -= bytes_read;
2324 }
2325 }
2326 else
2327 {
2328 if (max_bytes)
2329 error.SetErrorString("invalid arguments");
2330 }
2331 return total_bytes_read;
2332}
2333
2334// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2335// null terminators.
2336size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002337Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002338{
2339 size_t total_cstr_len = 0;
2340 if (dst && dst_max_len)
2341 {
Greg Claytone91b7952011-12-15 03:14:23 +00002342 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002343 // NULL out everything just to be safe
2344 memset (dst, 0, dst_max_len);
2345 Error error;
2346 addr_t curr_addr = addr;
2347 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2348 size_t bytes_left = dst_max_len - 1;
2349 char *curr_dst = dst;
2350
2351 while (bytes_left > 0)
2352 {
2353 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2354 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2355 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2356
2357 if (bytes_read == 0)
2358 {
Greg Claytone91b7952011-12-15 03:14:23 +00002359 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002360 dst[total_cstr_len] = '\0';
2361 break;
2362 }
2363 const size_t len = strlen(curr_dst);
2364
2365 total_cstr_len += len;
2366
2367 if (len < bytes_to_read)
2368 break;
2369
2370 curr_dst += bytes_read;
2371 curr_addr += bytes_read;
2372 bytes_left -= bytes_read;
2373 }
2374 }
Greg Claytone91b7952011-12-15 03:14:23 +00002375 else
2376 {
2377 if (dst == NULL)
2378 result_error.SetErrorString("invalid arguments");
2379 else
2380 result_error.Clear();
2381 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002382 return total_cstr_len;
2383}
2384
2385size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002386Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2387{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388 if (buf == NULL || size == 0)
2389 return 0;
2390
2391 size_t bytes_read = 0;
2392 uint8_t *bytes = (uint8_t *)buf;
2393
2394 while (bytes_read < size)
2395 {
2396 const size_t curr_size = size - bytes_read;
2397 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2398 bytes + bytes_read,
2399 curr_size,
2400 error);
2401 bytes_read += curr_bytes_read;
2402 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2403 break;
2404 }
2405
2406 // Replace any software breakpoint opcodes that fall into this range back
2407 // into "buf" before we return
2408 if (bytes_read > 0)
2409 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2410 return bytes_read;
2411}
2412
Greg Clayton58a4c462010-12-16 20:01:20 +00002413uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002414Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002415{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002416 Scalar scalar;
2417 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2418 return scalar.ULongLong(fail_value);
2419 return fail_value;
2420}
2421
2422addr_t
2423Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2424{
2425 Scalar scalar;
2426 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2427 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2428 return LLDB_INVALID_ADDRESS;
2429}
2430
2431
2432bool
2433Process::WritePointerToMemory (lldb::addr_t vm_addr,
2434 lldb::addr_t ptr_value,
2435 Error &error)
2436{
2437 Scalar scalar;
2438 const uint32_t addr_byte_size = GetAddressByteSize();
2439 if (addr_byte_size <= 4)
2440 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002441 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002442 scalar = ptr_value;
2443 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002444}
2445
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446size_t
2447Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2448{
2449 size_t bytes_written = 0;
2450 const uint8_t *bytes = (const uint8_t *)buf;
2451
2452 while (bytes_written < size)
2453 {
2454 const size_t curr_size = size - bytes_written;
2455 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2456 bytes + bytes_written,
2457 curr_size,
2458 error);
2459 bytes_written += curr_bytes_written;
2460 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2461 break;
2462 }
2463 return bytes_written;
2464}
2465
2466size_t
2467Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2468{
Greg Clayton58be07b2011-01-07 06:08:19 +00002469#if defined (ENABLE_MEMORY_CACHING)
2470 m_memory_cache.Flush (addr, size);
2471#endif
2472
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002473 if (buf == NULL || size == 0)
2474 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002475
Jim Ingham4b536182011-08-09 02:12:22 +00002476 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002477
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002478 // We need to write any data that would go where any current software traps
2479 // (enabled software breakpoints) any software traps (breakpoints) that we
2480 // may have placed in our tasks memory.
2481
Greg Claytond8cf1a12013-06-12 00:46:38 +00002482 BreakpointSiteList bp_sites_in_range;
2483
2484 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002485 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002486 // No breakpoint sites overlap
2487 if (bp_sites_in_range.IsEmpty())
2488 return WriteMemoryPrivate (addr, buf, size, error);
2489 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002490 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002491 const uint8_t *ubuf = (const uint8_t *)buf;
2492 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493
Greg Claytond8cf1a12013-06-12 00:46:38 +00002494 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2495
2496 if (error.Success())
2497 {
2498 addr_t intersect_addr;
2499 size_t intersect_size;
2500 size_t opcode_offset;
2501 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2502 assert(intersects);
2503 assert(addr <= intersect_addr && intersect_addr < addr + size);
2504 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2505 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2506
2507 // Check for bytes before this breakpoint
2508 const addr_t curr_addr = addr + bytes_written;
2509 if (intersect_addr > curr_addr)
2510 {
2511 // There are some bytes before this breakpoint that we need to
2512 // just write to memory
2513 size_t curr_size = intersect_addr - curr_addr;
2514 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2515 ubuf + bytes_written,
2516 curr_size,
2517 error);
2518 bytes_written += curr_bytes_written;
2519 if (curr_bytes_written != curr_size)
2520 {
2521 // We weren't able to write all of the requested bytes, we
2522 // are done looping and will return the number of bytes that
2523 // we have written so far.
2524 if (error.Success())
2525 error.SetErrorToGenericError();
2526 }
2527 }
2528 // Now write any bytes that would cover up any software breakpoints
2529 // directly into the breakpoint opcode buffer
2530 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2531 bytes_written += intersect_size;
2532 }
2533 });
2534
2535 if (bytes_written < size)
2536 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2537 ubuf + bytes_written,
2538 size - bytes_written,
2539 error);
2540 }
2541 }
2542 else
2543 {
2544 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002545 }
2546
2547 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002548 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002550
2551size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002552Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002553{
2554 if (byte_size == UINT32_MAX)
2555 byte_size = scalar.GetByteSize();
2556 if (byte_size > 0)
2557 {
2558 uint8_t buf[32];
2559 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2560 if (mem_size > 0)
2561 return WriteMemory(addr, buf, mem_size, error);
2562 else
2563 error.SetErrorString ("failed to get scalar as memory data");
2564 }
2565 else
2566 {
2567 error.SetErrorString ("invalid scalar value");
2568 }
2569 return 0;
2570}
2571
2572size_t
2573Process::ReadScalarIntegerFromMemory (addr_t addr,
2574 uint32_t byte_size,
2575 bool is_signed,
2576 Scalar &scalar,
2577 Error &error)
2578{
Greg Clayton7060f892013-05-01 23:41:30 +00002579 uint64_t uval = 0;
2580 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002581 {
Greg Clayton7060f892013-05-01 23:41:30 +00002582 error.SetErrorString ("byte size is zero");
2583 }
2584 else if (byte_size & (byte_size - 1))
2585 {
2586 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2587 }
2588 else if (byte_size <= sizeof(uval))
2589 {
2590 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002591 if (bytes_read == byte_size)
2592 {
2593 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002594 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002595 if (byte_size <= 4)
2596 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002597 else
Greg Clayton7060f892013-05-01 23:41:30 +00002598 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002599 if (is_signed)
2600 scalar.SignExtend(byte_size * 8);
2601 return bytes_read;
2602 }
2603 }
2604 else
2605 {
2606 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2607 }
2608 return 0;
2609}
2610
Greg Claytond495c532011-05-17 03:37:42 +00002611#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002612addr_t
2613Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2614{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002615 if (GetPrivateState() != eStateStopped)
2616 return LLDB_INVALID_ADDRESS;
2617
Greg Claytond495c532011-05-17 03:37:42 +00002618#if defined (USE_ALLOCATE_MEMORY_CACHE)
2619 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2620#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002621 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002622 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002623 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002624 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 +00002625 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002626 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002627 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002628 m_mod_id.GetStopID(),
2629 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002630 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002631#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632}
2633
Sean Callanan90539452011-09-20 23:01:51 +00002634bool
2635Process::CanJIT ()
2636{
Sean Callanana7b443a2012-02-14 22:50:38 +00002637 if (m_can_jit == eCanJITDontKnow)
2638 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002639 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002640 Error err;
2641
2642 uint64_t allocated_memory = AllocateMemory(8,
2643 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2644 err);
2645
2646 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002647 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002648 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002649 if (log)
2650 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2651 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002652 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002653 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002654 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002655 if (log)
2656 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2657 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002658
2659 DeallocateMemory (allocated_memory);
2660 }
2661
Sean Callanan90539452011-09-20 23:01:51 +00002662 return m_can_jit == eCanJITYes;
2663}
2664
2665void
2666Process::SetCanJIT (bool can_jit)
2667{
2668 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2669}
2670
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002671Error
2672Process::DeallocateMemory (addr_t ptr)
2673{
Greg Claytond495c532011-05-17 03:37:42 +00002674 Error error;
2675#if defined (USE_ALLOCATE_MEMORY_CACHE)
2676 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2677 {
Daniel Malead01b2952012-11-29 21:49:15 +00002678 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002679 }
2680#else
2681 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002682
Greg Clayton5160ce52013-03-27 23:08:40 +00002683 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002684 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002685 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 +00002686 ptr,
2687 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002688 m_mod_id.GetStopID(),
2689 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002690#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002691 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002692}
2693
Han Ming Ongc811d382012-11-17 00:33:14 +00002694
Greg Claytonc9660542012-02-05 02:38:54 +00002695ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002696Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002697 lldb::addr_t header_addr,
2698 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002699{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002700 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002701 if (module_sp)
2702 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002703 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002704 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002705 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002706 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002707 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002708 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002709}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710
2711Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002712Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713{
2714 Error error;
2715 error.SetErrorString("watchpoints are not supported");
2716 return error;
2717}
2718
2719Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002720Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721{
2722 Error error;
2723 error.SetErrorString("watchpoints are not supported");
2724 return error;
2725}
2726
2727StateType
2728Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2729{
2730 StateType state;
2731 // Now wait for the process to launch and return control to us, and then
2732 // call DidLaunch:
2733 while (1)
2734 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002735 event_sp.reset();
2736 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2737
Greg Clayton2637f822011-11-17 01:23:07 +00002738 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002739 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002740
2741 // If state is invalid, then we timed out
2742 if (state == eStateInvalid)
2743 break;
2744
2745 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746 HandlePrivateEvent (event_sp);
2747 }
2748 return state;
2749}
2750
2751Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002752Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753{
2754 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002755 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002756 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002757 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002758 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002759 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002760 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002761
Greg Claytonaa149cb2011-08-11 02:48:45 +00002762 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002763 if (exe_module)
2764 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002765 char local_exec_file_path[PATH_MAX];
2766 char platform_exec_file_path[PATH_MAX];
2767 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2768 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769 if (exe_module->GetFileSpec().Exists())
2770 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002771 // Install anything that might need to be installed prior to launching.
2772 // For host systems, this will do nothing, but if we are connected to a
2773 // remote platform it will install any needed binaries
2774 error = GetTarget().Install(&launch_info);
2775 if (error.Fail())
2776 return error;
2777
Greg Clayton71337622011-02-24 22:24:29 +00002778 if (PrivateStateThreadIsValid ())
2779 PausePrivateStateThread ();
2780
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 error = WillLaunch (exe_module);
2782 if (error.Success())
2783 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002784 const bool restarted = false;
2785 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002786 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002787
Ed Maste64fad602013-07-29 20:58:06 +00002788 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002789 {
2790 // Now launch using these arguments.
2791 error = DoLaunch (exe_module, launch_info);
2792 }
2793 else
2794 {
2795 // This shouldn't happen
2796 error.SetErrorString("failed to acquire process run lock");
2797 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798
2799 if (error.Fail())
2800 {
2801 if (GetID() != LLDB_INVALID_PROCESS_ID)
2802 {
2803 SetID (LLDB_INVALID_PROCESS_ID);
2804 const char *error_string = error.AsCString();
2805 if (error_string == NULL)
2806 error_string = "launch failed";
2807 SetExitStatus (-1, error_string);
2808 }
2809 }
2810 else
2811 {
2812 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002813 TimeValue timeout_time;
2814 timeout_time = TimeValue::Now();
2815 timeout_time.OffsetWithSeconds(10);
2816 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002817
Greg Clayton1a38ea72011-06-22 01:42:17 +00002818 if (state == eStateInvalid || event_sp.get() == NULL)
2819 {
2820 // We were able to launch the process, but we failed to
2821 // catch the initial stop.
2822 SetExitStatus (0, "failed to catch stop after launch");
2823 Destroy();
2824 }
2825 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002827
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828 DidLaunch ();
2829
Greg Claytonc859e2d2012-02-13 23:10:39 +00002830 DynamicLoader *dyld = GetDynamicLoader ();
2831 if (dyld)
2832 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002833
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002834 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002835
Jason Molendaeef51062013-11-05 03:57:19 +00002836 SystemRuntime *system_runtime = GetSystemRuntime ();
2837 if (system_runtime)
2838 system_runtime->DidLaunch();
2839
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002840 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002841 // This delays passing the stopped event to listeners till DidLaunch gets
2842 // a chance to complete...
2843 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002844
2845 if (PrivateStateThreadIsValid ())
2846 ResumePrivateStateThread ();
2847 else
2848 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849 }
2850 else if (state == eStateExited)
2851 {
2852 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2853 // not likely to work, and return an invalid pid.
2854 HandlePrivateEvent (event_sp);
2855 }
2856 }
2857 }
2858 }
2859 else
2860 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002861 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002862 }
2863 }
2864 return error;
2865}
2866
Greg Claytonc3776bf2012-02-09 06:16:32 +00002867
2868Error
2869Process::LoadCore ()
2870{
2871 Error error = DoLoadCore();
2872 if (error.Success())
2873 {
2874 if (PrivateStateThreadIsValid ())
2875 ResumePrivateStateThread ();
2876 else
2877 StartPrivateStateThread ();
2878
Greg Claytonc859e2d2012-02-13 23:10:39 +00002879 DynamicLoader *dyld = GetDynamicLoader ();
2880 if (dyld)
2881 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002882
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002883 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002884
Jason Molendaeef51062013-11-05 03:57:19 +00002885 SystemRuntime *system_runtime = GetSystemRuntime ();
2886 if (system_runtime)
2887 system_runtime->DidAttach();
2888
Greg Claytonc859e2d2012-02-13 23:10:39 +00002889 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002890 // We successfully loaded a core file, now pretend we stopped so we can
2891 // show all of the threads in the core file and explore the crashed
2892 // state.
2893 SetPrivateState (eStateStopped);
2894
2895 }
2896 return error;
2897}
2898
Greg Claytonc859e2d2012-02-13 23:10:39 +00002899DynamicLoader *
2900Process::GetDynamicLoader ()
2901{
2902 if (m_dyld_ap.get() == NULL)
2903 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2904 return m_dyld_ap.get();
2905}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002906
Todd Fialaaf245d12014-06-30 21:05:18 +00002907const lldb::DataBufferSP
2908Process::GetAuxvData()
2909{
2910 return DataBufferSP ();
2911}
2912
Andrew MacPherson17220c12014-03-05 10:12:43 +00002913JITLoaderList &
2914Process::GetJITLoaders ()
2915{
2916 if (!m_jit_loaders_ap)
2917 {
2918 m_jit_loaders_ap.reset(new JITLoaderList());
2919 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2920 }
2921 return *m_jit_loaders_ap;
2922}
2923
Jason Molendaeef51062013-11-05 03:57:19 +00002924SystemRuntime *
2925Process::GetSystemRuntime ()
2926{
2927 if (m_system_runtime_ap.get() == NULL)
2928 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2929 return m_system_runtime_ap.get();
2930}
2931
Todd Fiala76e0fc92014-08-27 22:58:26 +00002932Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
2933 NextEventAction (process),
2934 m_exec_count (exec_count)
2935{
2936 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2937 if (log)
2938 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
2939}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002940
Jim Inghambb3a2832011-01-29 01:49:25 +00002941Process::NextEventAction::EventActionResult
2942Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943{
Todd Fiala76e0fc92014-08-27 22:58:26 +00002944 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2945
Jim Inghambb3a2832011-01-29 01:49:25 +00002946 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00002947 if (log)
2948 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
2949
2950 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002951 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002952 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002953 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002954 return eEventActionRetry;
2955
2956 case eStateStopped:
2957 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002958 {
2959 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002960 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002961 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002962 // We don't want these events to be reported, so go set the ShouldReportStop here:
2963 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2964
Greg Claytonc9ed4782011-11-12 02:10:56 +00002965 if (m_exec_count > 0)
2966 {
2967 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00002968
2969 if (log)
2970 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
2971
Jim Ingham221d51c2013-05-08 00:35:16 +00002972 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002973 return eEventActionRetry;
2974 }
2975 else
2976 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00002977 if (log)
2978 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
2979
Greg Claytonc9ed4782011-11-12 02:10:56 +00002980 m_process->CompleteAttach ();
2981 return eEventActionSuccess;
2982 }
2983 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002984 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002985
Greg Clayton513c26c2011-01-29 07:10:55 +00002986 default:
2987 case eStateExited:
2988 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002989 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002990 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002991
2992 m_exit_string.assign ("No valid Process");
2993 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002994}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995
Jim Inghambb3a2832011-01-29 01:49:25 +00002996Process::NextEventAction::EventActionResult
2997Process::AttachCompletionHandler::HandleBeingInterrupted()
2998{
2999 return eEventActionSuccess;
3000}
3001
3002const char *
3003Process::AttachCompletionHandler::GetExitString ()
3004{
3005 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006}
3007
3008Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003009Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003010{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003011 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003012 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003013 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003014 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003015 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003016 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003017
Greg Clayton144f3a92011-11-15 03:53:30 +00003018 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003019 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003020 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003021 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003022 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003023
Greg Clayton144f3a92011-11-15 03:53:30 +00003024 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003025 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003026 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3027
3028 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003030 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3031 if (error.Success())
3032 {
Ed Maste64fad602013-07-29 20:58:06 +00003033 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003034 {
3035 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003036 const bool restarted = false;
3037 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003038 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003039 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003040 }
3041 else
3042 {
3043 // This shouldn't happen
3044 error.SetErrorString("failed to acquire process run lock");
3045 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003046
Greg Clayton144f3a92011-11-15 03:53:30 +00003047 if (error.Fail())
3048 {
3049 if (GetID() != LLDB_INVALID_PROCESS_ID)
3050 {
3051 SetID (LLDB_INVALID_PROCESS_ID);
3052 if (error.AsCString() == NULL)
3053 error.SetErrorString("attach failed");
3054
3055 SetExitStatus(-1, error.AsCString());
3056 }
3057 }
3058 else
3059 {
3060 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3061 StartPrivateStateThread();
3062 }
3063 return error;
3064 }
Greg Claytone996fd32011-03-08 22:40:15 +00003065 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003066 else
Greg Claytone996fd32011-03-08 22:40:15 +00003067 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003068 ProcessInstanceInfoList process_infos;
3069 PlatformSP platform_sp (m_target.GetPlatform ());
3070
3071 if (platform_sp)
3072 {
3073 ProcessInstanceInfoMatch match_info;
3074 match_info.GetProcessInfo() = attach_info;
3075 match_info.SetNameMatchType (eNameMatchEquals);
3076 platform_sp->FindProcesses (match_info, process_infos);
3077 const uint32_t num_matches = process_infos.GetSize();
3078 if (num_matches == 1)
3079 {
3080 attach_pid = process_infos.GetProcessIDAtIndex(0);
3081 // Fall through and attach using the above process ID
3082 }
3083 else
3084 {
3085 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3086 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003087 {
3088 StreamString s;
3089 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3090 for (size_t i = 0; i < num_matches; i++)
3091 {
3092 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3093 }
3094 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3095 process_name,
3096 s.GetData());
3097 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003098 else
3099 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3100 }
3101 }
3102 else
3103 {
3104 error.SetErrorString ("invalid platform, can't find processes by name");
3105 return error;
3106 }
Greg Claytone996fd32011-03-08 22:40:15 +00003107 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108 }
3109 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003110 {
3111 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003112 }
3113 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003114
3115 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003116 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003117 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003118 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003119 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003120
Ed Maste64fad602013-07-29 20:58:06 +00003121 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003122 {
3123 // Now attach using these arguments.
3124 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003125 const bool restarted = false;
3126 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003127 error = DoAttachToProcessWithID (attach_pid, attach_info);
3128 }
3129 else
3130 {
3131 // This shouldn't happen
3132 error.SetErrorString("failed to acquire process run lock");
3133 }
3134
Greg Clayton144f3a92011-11-15 03:53:30 +00003135 if (error.Success())
3136 {
3137
3138 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3139 StartPrivateStateThread();
3140 }
3141 else
Greg Claytone996fd32011-03-08 22:40:15 +00003142 {
3143 if (GetID() != LLDB_INVALID_PROCESS_ID)
3144 {
3145 SetID (LLDB_INVALID_PROCESS_ID);
3146 const char *error_string = error.AsCString();
3147 if (error_string == NULL)
3148 error_string = "attach failed";
3149
3150 SetExitStatus(-1, error_string);
3151 }
3152 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153 }
3154 }
3155 return error;
3156}
3157
Greg Clayton93d3c8332011-02-16 04:46:07 +00003158void
3159Process::CompleteAttach ()
3160{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003161 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3162 if (log)
3163 log->Printf ("Process::%s()", __FUNCTION__);
3164
Greg Clayton93d3c8332011-02-16 04:46:07 +00003165 // Let the process subclass figure out at much as it can about the process
3166 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003167 ArchSpec process_arch;
3168 DidAttach(process_arch);
3169
3170 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003171 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003172 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003173 if (log)
3174 {
3175 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3176 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3177 __FUNCTION__,
3178 triple_str ? triple_str : "<null>");
3179 }
3180 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003181
Jim Ingham4299fdb2011-09-15 01:10:17 +00003182 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3183 // the same as the one we've already set, switch architectures.
3184 PlatformSP platform_sp (m_target.GetPlatform ());
3185 assert (platform_sp.get());
3186 if (platform_sp)
3187 {
Greg Clayton70512312012-05-08 01:45:38 +00003188 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003189 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003190 {
3191 ArchSpec platform_arch;
3192 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3193 if (platform_sp)
3194 {
3195 m_target.SetPlatform (platform_sp);
3196 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003197 if (log)
3198 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 +00003199 }
3200 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003201 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003202 {
3203 ProcessInstanceInfo process_info;
3204 platform_sp->GetProcessInfo (GetID(), process_info);
3205 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003206 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003207 {
Greg Clayton70512312012-05-08 01:45:38 +00003208 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003209 if (log)
3210 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 ());
3211 }
Greg Clayton70512312012-05-08 01:45:38 +00003212 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003213 }
3214
3215 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003216 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003217 DynamicLoader *dyld = GetDynamicLoader ();
3218 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003219 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003220 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003221 if (log)
3222 {
3223 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3224 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3225 __FUNCTION__,
3226 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3227 dyld->GetPluginName().AsCString ("<unnamed>"));
3228 }
3229 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003230
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003231 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003232
Jason Molendaeef51062013-11-05 03:57:19 +00003233 SystemRuntime *system_runtime = GetSystemRuntime ();
3234 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003235 {
Jason Molendaeef51062013-11-05 03:57:19 +00003236 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003237 if (log)
3238 {
3239 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3240 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3241 __FUNCTION__,
3242 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3243 system_runtime->GetPluginName().AsCString("<unnamed>"));
3244 }
3245 }
Jason Molendaeef51062013-11-05 03:57:19 +00003246
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003247 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003248 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003249 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003250 Mutex::Locker modules_locker(target_modules.GetMutex());
3251 size_t num_modules = target_modules.GetSize();
3252 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003253
Andy Gibbsa297a972013-06-19 19:04:53 +00003254 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003255 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003256 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003257 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003258 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003259 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003260 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003261 break;
3262 }
3263 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003264 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003265 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003266 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003267 if (log)
3268 {
3269 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3270 log->Printf ("Process::%s after looping through modules, target executable is %s",
3271 __FUNCTION__,
3272 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3273 }
3274 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003275}
3276
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003277Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003278Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003279{
Greg Claytonb766a732011-02-04 01:58:07 +00003280 m_abi_sp.reset();
3281 m_process_input_reader.reset();
3282
3283 // Find the process and its architecture. Make sure it matches the architecture
3284 // of the current Target, and if not adjust it.
3285
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003286 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003287 if (error.Success())
3288 {
Greg Clayton71337622011-02-24 22:24:29 +00003289 if (GetID() != LLDB_INVALID_PROCESS_ID)
3290 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003291 EventSP event_sp;
3292 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3293
3294 if (state == eStateStopped || state == eStateCrashed)
3295 {
3296 // If we attached and actually have a process on the other end, then
3297 // this ended up being the equivalent of an attach.
3298 CompleteAttach ();
3299
3300 // This delays passing the stopped event to listeners till
3301 // CompleteAttach gets a chance to complete...
3302 HandlePrivateEvent (event_sp);
3303
3304 }
Greg Clayton71337622011-02-24 22:24:29 +00003305 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003306
3307 if (PrivateStateThreadIsValid ())
3308 ResumePrivateStateThread ();
3309 else
3310 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003311 }
3312 return error;
3313}
3314
3315
3316Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003317Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318{
Greg Clayton5160ce52013-03-27 23:08:40 +00003319 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003321 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003322 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003323 StateAsCString(m_public_state.GetValue()),
3324 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325
3326 Error error (WillResume());
3327 // Tell the process it is about to resume before the thread list
3328 if (error.Success())
3329 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003330 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331 // can let all of our threads know that they are about to be
3332 // resumed. Threads will each be called with
3333 // Thread::WillResume(StateType) where StateType contains the state
3334 // that they are supposed to have when the process is resumed
3335 // (suspended/running/stepping). Threads should also check
3336 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003337 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003338 if (m_thread_list.WillResume())
3339 {
Jim Ingham372787f2012-04-07 00:00:41 +00003340 // Last thing, do the PreResumeActions.
3341 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003342 {
Jim Ingham0161b492013-02-09 01:29:05 +00003343 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003344 }
3345 else
3346 {
3347 m_mod_id.BumpResumeID();
3348 error = DoResume();
3349 if (error.Success())
3350 {
3351 DidResume();
3352 m_thread_list.DidResume();
3353 if (log)
3354 log->Printf ("Process thinks the process has resumed.");
3355 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356 }
3357 }
3358 else
3359 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003360 // Somebody wanted to run without running. So generate a continue & a stopped event,
3361 // and let the world handle them.
3362 if (log)
3363 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3364
3365 SetPrivateState(eStateRunning);
3366 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003367 }
3368 }
Jim Ingham444586b2011-01-24 06:34:17 +00003369 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003370 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003371 return error;
3372}
3373
3374Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003375Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003376{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003377 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3378 // in case it was already set and some thread plan logic calls halt on its
3379 // own.
3380 m_clear_thread_plans_on_stop |= clear_thread_plans;
3381
Jim Inghamaacc3182012-06-06 00:29:30 +00003382 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3383 // we could just straightaway get another event. It just narrows the window...
3384 m_currently_handling_event.WaitForValueEqualTo(false);
3385
3386
Jim Inghambb3a2832011-01-29 01:49:25 +00003387 // Pause our private state thread so we can ensure no one else eats
3388 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003389 Listener halt_listener ("lldb.process.halt_listener");
3390 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003391
Jim Inghambb3a2832011-01-29 01:49:25 +00003392 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003393 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003394
Greg Clayton06357c92014-07-30 17:38:47 +00003395 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003396 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003397 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003398
Greg Clayton513c26c2011-01-29 07:10:55 +00003399 bool caused_stop = false;
3400
3401 // Ask the process subclass to actually halt our process
3402 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003404 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003405 if (m_public_state.GetValue() == eStateAttaching)
3406 {
Greg Clayton06357c92014-07-30 17:38:47 +00003407 // Don't hijack and eat the eStateExited as the code that was doing
3408 // the attach will be waiting for this event...
3409 RestorePrivateProcessEvents();
3410 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003411 SetExitStatus(SIGKILL, "Cancelled async attach.");
3412 Destroy ();
3413 }
3414 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003415 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003416 // If "caused_stop" is true, then DoHalt stopped the process. If
3417 // "caused_stop" is false, the process was already stopped.
3418 // If the DoHalt caused the process to stop, then we want to catch
3419 // this event and set the interrupted bool to true before we pass
3420 // this along so clients know that the process was interrupted by
3421 // a halt command.
3422 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003423 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003424 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003425 TimeValue timeout_time;
3426 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003427 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003428 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3429 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003430
Jim Ingham0f16e732011-02-08 05:20:59 +00003431 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003432 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003433 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003434 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003435 }
3436 else
3437 {
Greg Clayton2637f822011-11-17 01:23:07 +00003438 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003439 {
3440 // We caused the process to interrupt itself, so mark this
3441 // as such in the stop event so clients can tell an interrupted
3442 // process from a natural stop
3443 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3444 }
3445 else
3446 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003447 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003448 if (log)
3449 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3450 error.SetErrorString ("Did not get stopped event after halt.");
3451 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003452 }
3453 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003454 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003455 }
3456 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003457 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003458 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003459 if (!restored_process_events)
3460 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003461
3462 // Post any event we might have consumed. If all goes well, we will have
3463 // stopped the process, intercepted the event and set the interrupted
3464 // bool in the event. Post it to the private event queue and that will end up
3465 // correctly setting the state.
3466 if (event_sp)
3467 m_private_state_broadcaster.BroadcastEvent(event_sp);
3468
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003469 return error;
3470}
3471
3472Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003473Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3474{
3475 Error error;
3476 if (m_public_state.GetValue() == eStateRunning)
3477 {
3478 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3479 if (log)
3480 log->Printf("Process::Destroy() About to halt.");
3481 error = Halt();
3482 if (error.Success())
3483 {
3484 // Consume the halt event.
3485 TimeValue timeout (TimeValue::Now());
3486 timeout.OffsetWithSeconds(1);
3487 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3488
3489 // If the process exited while we were waiting for it to stop, put the exited event into
3490 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3491 // they don't have a process anymore...
3492
3493 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3494 {
3495 if (log)
3496 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3497 return error;
3498 }
3499 else
3500 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3501
3502 if (state != eStateStopped)
3503 {
3504 if (log)
3505 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3506 // If we really couldn't stop the process then we should just error out here, but if the
3507 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3508 StateType private_state = m_private_state.GetValue();
3509 if (private_state != eStateStopped)
3510 {
3511 return error;
3512 }
3513 }
3514 }
3515 else
3516 {
3517 if (log)
3518 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3519 }
3520 }
3521 return error;
3522}
3523
3524Error
Jim Inghamacff8952013-05-02 00:27:30 +00003525Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003526{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003527 EventSP exit_event_sp;
3528 Error error;
3529 m_destroy_in_process = true;
3530
3531 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532
3533 if (error.Success())
3534 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003535 if (DetachRequiresHalt())
3536 {
3537 error = HaltForDestroyOrDetach (exit_event_sp);
3538 if (!error.Success())
3539 {
3540 m_destroy_in_process = false;
3541 return error;
3542 }
3543 else if (exit_event_sp)
3544 {
3545 // We shouldn't need to do anything else here. There's no process left to detach from...
3546 StopPrivateStateThread();
3547 m_destroy_in_process = false;
3548 return error;
3549 }
3550 }
3551
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003552 m_thread_list.DiscardThreadPlans();
3553 DisableAllBreakpointSites();
3554
Jim Inghamacff8952013-05-02 00:27:30 +00003555 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003556 if (error.Success())
3557 {
3558 DidDetach();
3559 StopPrivateStateThread();
3560 }
Jim Inghamacff8952013-05-02 00:27:30 +00003561 else
3562 {
3563 return error;
3564 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003566 m_destroy_in_process = false;
3567
3568 // If we exited when we were waiting for a process to stop, then
3569 // forward the event here so we don't lose the event
3570 if (exit_event_sp)
3571 {
3572 // Directly broadcast our exited event because we shut down our
3573 // private state thread above
3574 BroadcastEvent(exit_event_sp);
3575 }
3576
3577 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3578 // the last events through the event system, in which case we might strand the write lock. Unlock
3579 // it here so when we do to tear down the process we don't get an error destroying the lock.
3580
Ed Maste64fad602013-07-29 20:58:06 +00003581 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003582 return error;
3583}
3584
3585Error
3586Process::Destroy ()
3587{
Jim Ingham09437922013-03-01 20:04:25 +00003588
3589 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3590 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3591 // failed and the process stays around for some reason it won't be in a confused state.
3592
3593 m_destroy_in_process = true;
3594
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003595 Error error (WillDestroy());
3596 if (error.Success())
3597 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003598 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003599 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003600 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003601 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003602 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003603
Jim Inghamaacc3182012-06-06 00:29:30 +00003604 if (m_public_state.GetValue() != eStateRunning)
3605 {
3606 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3607 // kill it, we don't want it hitting a breakpoint...
3608 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3609 // we're not going to have much luck doing this now.
3610 m_thread_list.DiscardThreadPlans();
3611 DisableAllBreakpointSites();
3612 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003613
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614 error = DoDestroy();
3615 if (error.Success())
3616 {
3617 DidDestroy();
3618 StopPrivateStateThread();
3619 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003620 m_stdio_communication.StopReadThread();
3621 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003622
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003623 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003624 {
3625 m_process_input_reader->SetIsDone(true);
3626 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003627 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003628 }
3629
Greg Clayton85fb1b92012-09-11 02:33:37 +00003630 // If we exited when we were waiting for a process to stop, then
3631 // forward the event here so we don't lose the event
3632 if (exit_event_sp)
3633 {
3634 // Directly broadcast our exited event because we shut down our
3635 // private state thread above
3636 BroadcastEvent(exit_event_sp);
3637 }
3638
Jim Inghamb1e2e842012-04-12 18:49:31 +00003639 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3640 // the last events through the event system, in which case we might strand the write lock. Unlock
3641 // 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 +00003642 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003643 }
Jim Ingham09437922013-03-01 20:04:25 +00003644
3645 m_destroy_in_process = false;
3646
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647 return error;
3648}
3649
3650Error
3651Process::Signal (int signal)
3652{
3653 Error error (WillSignal());
3654 if (error.Success())
3655 {
3656 error = DoSignal(signal);
3657 if (error.Success())
3658 DidSignal();
3659 }
3660 return error;
3661}
3662
Greg Clayton514487e2011-02-15 21:59:32 +00003663lldb::ByteOrder
3664Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003665{
Greg Clayton514487e2011-02-15 21:59:32 +00003666 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003667}
3668
3669uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003670Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003671{
Greg Clayton514487e2011-02-15 21:59:32 +00003672 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003673}
3674
Greg Clayton514487e2011-02-15 21:59:32 +00003675
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676bool
3677Process::ShouldBroadcastEvent (Event *event_ptr)
3678{
3679 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3680 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003681 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683 switch (state)
3684 {
Greg Claytonb766a732011-02-04 01:58:07 +00003685 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003686 case eStateAttaching:
3687 case eStateLaunching:
3688 case eStateDetached:
3689 case eStateExited:
3690 case eStateUnloaded:
3691 // These events indicate changes in the state of the debugging session, always report them.
3692 return_value = true;
3693 break;
3694 case eStateInvalid:
3695 // We stopped for no apparent reason, don't report it.
3696 return_value = false;
3697 break;
3698 case eStateRunning:
3699 case eStateStepping:
3700 // If we've started the target running, we handle the cases where we
3701 // are already running and where there is a transition from stopped to
3702 // running differently.
3703 // running -> running: Automatically suppress extra running events
3704 // stopped -> running: Report except when there is one or more no votes
3705 // and no yes votes.
3706 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003707 if (m_force_next_event_delivery)
3708 return_value = true;
3709 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003710 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003711 switch (m_last_broadcast_state)
3712 {
3713 case eStateRunning:
3714 case eStateStepping:
3715 // We always suppress multiple runnings with no PUBLIC stop in between.
3716 return_value = false;
3717 break;
3718 default:
3719 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003720 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003721 // events. If I run the lldb/test/thread/a.out file and
3722 // break at main.cpp:58, run and hit the breakpoints on
3723 // multiple threads, then somehow during the stepping over
3724 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725
Jim Ingham1460e4b2014-01-10 23:46:59 +00003726 // This is a transition from stop to run.
3727 switch (m_thread_list.ShouldReportRun (event_ptr))
3728 {
3729 case eVoteYes:
3730 case eVoteNoOpinion:
3731 return_value = true;
3732 break;
3733 case eVoteNo:
3734 return_value = false;
3735 break;
3736 }
3737 break;
3738 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739 }
3740 break;
3741 case eStateStopped:
3742 case eStateCrashed:
3743 case eStateSuspended:
3744 {
3745 // We've stopped. First see if we're going to restart the target.
3746 // If we are going to stop, then we always broadcast the event.
3747 // 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 +00003748 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003749
Jim Inghamcb4ca112012-05-16 01:32:14 +00003750 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003751 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003752 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003753 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003754 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003755 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003756 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003757 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3758 // so they can properly set their state.
3759 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003760 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003761 }
3762 else
3763 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003764 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3765 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003766
Jim Ingham0161b492013-02-09 01:29:05 +00003767 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3768 // Asking the thread list is also not likely to go well, since we are running again.
3769 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003770
Jim Ingham0161b492013-02-09 01:29:05 +00003771 if (!was_restarted)
3772 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003773
Jim Ingham221d51c2013-05-08 00:35:16 +00003774 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775 {
Jim Ingham0161b492013-02-09 01:29:05 +00003776 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3777 if (log)
3778 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003779 should_resume, StateAsCString(state),
3780 was_restarted, stop_vote);
3781
Jim Ingham0161b492013-02-09 01:29:05 +00003782 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783 {
3784 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003785 return_value = true;
3786 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003788 case eVoteNo:
3789 return_value = false;
3790 break;
3791 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003792
Jim Inghamcb95f342012-09-05 21:13:56 +00003793 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003794 {
3795 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003796 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3797 static_cast<void*>(event_ptr),
3798 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003799 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003800 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003801 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003802
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003803 }
3804 else
3805 {
3806 return_value = true;
3807 SynchronouslyNotifyStateChanged (state);
3808 }
3809 }
3810 }
Jim Ingham0161b492013-02-09 01:29:05 +00003811 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003812 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003813
Jim Ingham1460e4b2014-01-10 23:46:59 +00003814 // Forcing the next event delivery is a one shot deal. So reset it here.
3815 m_force_next_event_delivery = false;
3816
Jim Ingham0161b492013-02-09 01:29:05 +00003817 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3818 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3819 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3820 // because the PublicState reflects the last event pulled off the queue, and there may be several
3821 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3822 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003823
Jim Ingham0161b492013-02-09 01:29:05 +00003824 if (return_value)
3825 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003826
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003827 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003828 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003829 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003830 StateAsCString(m_last_broadcast_state),
3831 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832 return return_value;
3833}
3834
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003835
3836bool
Jim Ingham372787f2012-04-07 00:00:41 +00003837Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003838{
Greg Clayton5160ce52013-03-27 23:08:40 +00003839 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003840
Greg Clayton8b82f082011-04-12 05:54:46 +00003841 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003842 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003843 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3844
Jim Ingham372787f2012-04-07 00:00:41 +00003845 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003846 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847
3848 // Create a thread that watches our internal state and controls which
3849 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003850 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003851
Zachary Turner39de3112014-09-09 20:54:56 +00003852 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00003853 {
Zachary Turner39de3112014-09-09 20:54:56 +00003854 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3855 if (already_running)
3856 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3857 else
3858 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00003859 }
Jim Ingham372787f2012-04-07 00:00:41 +00003860 else
Todd Fiala17096d72014-07-16 19:03:16 +00003861 {
3862 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00003863 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003864 else
Zachary Turner39de3112014-09-09 20:54:56 +00003865 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003866 }
3867
Jim Ingham076b3042012-04-10 01:21:57 +00003868 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00003869 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
3870 if (m_private_state_thread.GetState() == eThreadStateRunning)
Jim Ingham076b3042012-04-10 01:21:57 +00003871 {
3872 ResumePrivateStateThread();
3873 return true;
3874 }
3875 else
3876 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877}
3878
3879void
3880Process::PausePrivateStateThread ()
3881{
3882 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3883}
3884
3885void
3886Process::ResumePrivateStateThread ()
3887{
3888 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3889}
3890
3891void
3892Process::StopPrivateStateThread ()
3893{
Greg Clayton8b82f082011-04-12 05:54:46 +00003894 if (PrivateStateThreadIsValid ())
3895 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003896 else
3897 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003898 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003899 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003900 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003901 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003902}
3903
3904void
3905Process::ControlPrivateStateThread (uint32_t signal)
3906{
Greg Clayton5160ce52013-03-27 23:08:40 +00003907 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003908
3909 assert (signal == eBroadcastInternalStateControlStop ||
3910 signal == eBroadcastInternalStateControlPause ||
3911 signal == eBroadcastInternalStateControlResume);
3912
3913 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003914 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003915
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003916 // Signal the private state thread. First we should copy this is case the
3917 // thread starts exiting since the private state thread will NULL this out
3918 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00003919 HostThread private_state_thread(m_private_state_thread);
3920 if (private_state_thread.GetState() == eThreadStateRunning)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921 {
3922 TimeValue timeout_time;
3923 bool timed_out;
3924
3925 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3926
3927 timeout_time = TimeValue::Now();
3928 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003929 if (log)
3930 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003931 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3932 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3933
3934 if (signal == eBroadcastInternalStateControlStop)
3935 {
3936 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003937 {
Zachary Turner39de3112014-09-09 20:54:56 +00003938 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003939 if (log)
3940 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3941 }
3942 else
3943 {
3944 if (log)
3945 log->Printf ("The control event killed the private state thread without having to cancel.");
3946 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947
3948 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00003949 private_state_thread.Join(&result);
3950 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003951 }
3952 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003953 else
3954 {
3955 if (log)
3956 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3957 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003958}
3959
3960void
Jim Inghamcfc09352012-07-27 23:57:19 +00003961Process::SendAsyncInterrupt ()
3962{
3963 if (PrivateStateThreadIsValid())
3964 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3965 else
3966 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3967}
3968
3969void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003970Process::HandlePrivateEvent (EventSP &event_sp)
3971{
Greg Clayton5160ce52013-03-27 23:08:40 +00003972 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003973 m_resume_requested = false;
3974
Jim Inghamaacc3182012-06-06 00:29:30 +00003975 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003976
Greg Clayton414f5d32011-01-25 02:58:48 +00003977 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003978
3979 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003980 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003981 {
Jim Ingham754ab982011-01-29 04:05:41 +00003982 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003983 if (log)
3984 log->Printf ("Ran next event action, result was %d.", action_result);
3985
Jim Inghambb3a2832011-01-29 01:49:25 +00003986 switch (action_result)
3987 {
3988 case NextEventAction::eEventActionSuccess:
3989 SetNextEventAction(NULL);
3990 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003991
Jim Inghambb3a2832011-01-29 01:49:25 +00003992 case NextEventAction::eEventActionRetry:
3993 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003994
Jim Inghambb3a2832011-01-29 01:49:25 +00003995 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003996 // Handle Exiting Here. If we already got an exited event,
3997 // we should just propagate it. Otherwise, swallow this event,
3998 // and set our state to exit so the next event will kill us.
3999 if (new_state != eStateExited)
4000 {
4001 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004002 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004003 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004004 SetNextEventAction(NULL);
4005 return;
4006 }
4007 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004008 break;
4009 }
4010 }
4011
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004012 // See if we should broadcast this state to external clients?
4013 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004014
4015 if (should_broadcast)
4016 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004017 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004018 if (log)
4019 {
Daniel Malead01b2952012-11-29 21:49:15 +00004020 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004021 __FUNCTION__,
4022 GetID(),
4023 StateAsCString(new_state),
4024 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004025 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004026 }
Jim Ingham9575d842011-03-11 03:53:59 +00004027 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004028 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004029 {
4030 // Only push the input handler if we aren't fowarding events,
4031 // as this means the curses GUI is in use...
4032 if (!GetTarget().GetDebugger().IsForwardingEvents())
4033 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004034 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004035 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004036 else if (StateIsStoppedState(new_state, false))
4037 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004038 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004039 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4040 {
4041 // If the lldb_private::Debugger is handling the events, we don't
4042 // want to pop the process IOHandler here, we want to do it when
4043 // we receive the stopped event so we can carefully control when
4044 // the process IOHandler is popped because when we stop we want to
4045 // display some text stating how and why we stopped, then maybe some
4046 // process/thread/frame info, and then we want the "(lldb) " prompt
4047 // to show up. If we pop the process IOHandler here, then we will
4048 // cause the command interpreter to become the top IOHandler after
4049 // the process pops off and it will update its prompt right away...
4050 // See the Debugger.cpp file where it calls the function as
4051 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4052 // Otherwise we end up getting overlapping "(lldb) " prompts and
4053 // garbled output.
4054 //
4055 // If we aren't handling the events in the debugger (which is indicated
4056 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4057 // are hijacked, then we always pop the process IO handler manually.
4058 // Hijacking happens when the internal process state thread is running
4059 // thread plans, or when commands want to run in synchronous mode
4060 // and they call "process->WaitForProcessToStop()". An example of something
4061 // that will hijack the events is a simple expression:
4062 //
4063 // (lldb) expr (int)puts("hello")
4064 //
4065 // This will cause the internal process state thread to resume and halt
4066 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4067 // events) and we do need the IO handler to be pushed and popped
4068 // correctly.
4069
4070 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4071 PopProcessIOHandler ();
4072 }
4073 }
Jim Ingham9575d842011-03-11 03:53:59 +00004074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004075 BroadcastEvent (event_sp);
4076 }
4077 else
4078 {
4079 if (log)
4080 {
Daniel Malead01b2952012-11-29 21:49:15 +00004081 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004082 __FUNCTION__,
4083 GetID(),
4084 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004085 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086 }
4087 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004088 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004089}
4090
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004091thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092Process::PrivateStateThread (void *arg)
4093{
4094 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004095 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096 return result;
4097}
4098
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004099thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100Process::RunPrivateStateThread ()
4101{
Jim Ingham076b3042012-04-10 01:21:57 +00004102 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004103 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104
Greg Clayton5160ce52013-03-27 23:08:40 +00004105 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004106 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004107 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4108 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004109
4110 bool exit_now = false;
4111 while (!exit_now)
4112 {
4113 EventSP event_sp;
4114 WaitForEventsPrivate (NULL, event_sp, control_only);
4115 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4116 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004117 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004118 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4119 __FUNCTION__, static_cast<void*>(this), GetID(),
4120 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004121
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004122 switch (event_sp->GetType())
4123 {
4124 case eBroadcastInternalStateControlStop:
4125 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004126 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004127
4128 case eBroadcastInternalStateControlPause:
4129 control_only = true;
4130 break;
4131
4132 case eBroadcastInternalStateControlResume:
4133 control_only = false;
4134 break;
4135 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004137 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004138 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004139 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004140 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4141 {
4142 if (m_public_state.GetValue() == eStateAttaching)
4143 {
4144 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004145 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4146 __FUNCTION__, static_cast<void*>(this),
4147 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004148 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4149 }
4150 else
4151 {
4152 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004153 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4154 __FUNCTION__, static_cast<void*>(this),
4155 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004156 Halt();
4157 }
4158 continue;
4159 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004160
4161 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4162
4163 if (internal_state != eStateInvalid)
4164 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004165 if (m_clear_thread_plans_on_stop &&
4166 StateIsStoppedState(internal_state, true))
4167 {
4168 m_clear_thread_plans_on_stop = false;
4169 m_thread_list.DiscardThreadPlans();
4170 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004171 HandlePrivateEvent (event_sp);
4172 }
4173
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004174 if (internal_state == eStateInvalid ||
4175 internal_state == eStateExited ||
4176 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004177 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004178 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004179 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4180 __FUNCTION__, static_cast<void*>(this), GetID(),
4181 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004182
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004184 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185 }
4186
Caroline Tice20ad3c42010-10-29 21:48:37 +00004187 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004188 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004189 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4190 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004191
Ed Maste64fad602013-07-29 20:58:06 +00004192 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004193 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004194 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004195 return NULL;
4196}
4197
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004198//------------------------------------------------------------------
4199// Process Event Data
4200//------------------------------------------------------------------
4201
4202Process::ProcessEventData::ProcessEventData () :
4203 EventData (),
4204 m_process_sp (),
4205 m_state (eStateInvalid),
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 (const ProcessSP &process_sp, StateType state) :
4213 EventData (),
4214 m_process_sp (process_sp),
4215 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004216 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004217 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004218 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004219{
4220}
4221
4222Process::ProcessEventData::~ProcessEventData()
4223{
4224}
4225
4226const ConstString &
4227Process::ProcessEventData::GetFlavorString ()
4228{
4229 static ConstString g_flavor ("Process::ProcessEventData");
4230 return g_flavor;
4231}
4232
4233const ConstString &
4234Process::ProcessEventData::GetFlavor () const
4235{
4236 return ProcessEventData::GetFlavorString ();
4237}
4238
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239void
4240Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4241{
4242 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004243 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4244 // the public event queue, then other times when we're pretending that this is where we stopped at the
4245 // end of expression evaluation. m_update_state is used to distinguish these
4246 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004247 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004248 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004249 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004250
Jim Ingham221d51c2013-05-08 00:35:16 +00004251 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004252
4253 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4254 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4255 // end up restarting the process.
4256 if (m_interrupted)
4257 return;
4258
4259 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004260 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004261 {
4262 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004263 uint32_t num_threads = curr_thread_list.GetSize();
4264 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004265
Jim Ingham4b536182011-08-09 02:12:22 +00004266 // The actions might change one of the thread's stop_info's opinions about whether we should
4267 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004268
4269 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4270 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4271 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4272 // 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
4273 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004274 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004275 for (idx = 0; idx < num_threads; ++idx)
4276 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4277
Jim Inghamc7078c22012-12-13 22:24:15 +00004278 // Use this to track whether we should continue from here. We will only continue the target running if
4279 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4280 // then it doesn't matter what the other threads say...
4281
4282 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004283
Jim Ingham0ad7e052013-04-25 02:04:59 +00004284 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4285 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4286 // thing to do is, and it's better to let the user decide than continue behind their backs.
4287
4288 bool does_anybody_have_an_opinion = false;
4289
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004290 for (idx = 0; idx < num_threads; ++idx)
4291 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004292 curr_thread_list = m_process_sp->GetThreadList();
4293 if (curr_thread_list.GetSize() != num_threads)
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("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004298 break;
4299 }
4300
4301 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4302
4303 if (thread_sp->GetIndexID() != thread_index_array[idx])
4304 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004305 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004306 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004307 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004308 idx,
4309 thread_index_array[idx],
4310 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004311 break;
4312 }
4313
Jim Inghamb15bfc72010-10-20 00:39:53 +00004314 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004315 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004316 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004317 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004318 bool this_thread_wants_to_stop;
4319 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004320 {
Jim Ingham0161b492013-02-09 01:29:05 +00004321 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4322 }
4323 else
4324 {
4325 stop_info_sp->PerformAction(event_ptr);
4326 // The stop action might restart the target. If it does, then we want to mark that in the
4327 // event so that whoever is receiving it will know to wait for the running event and reflect
4328 // that state appropriately.
4329 // We also need to stop processing actions, since they aren't expecting the target to be running.
4330
4331 // FIXME: we might have run.
4332 if (stop_info_sp->HasTargetRunSinceMe())
4333 {
4334 SetRestarted (true);
4335 break;
4336 }
4337
4338 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004339 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004340
Jim Inghamc7078c22012-12-13 22:24:15 +00004341 if (still_should_stop == false)
4342 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004343 }
4344 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004345
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004346
Jim Inghama8ca6e22013-05-03 23:04:37 +00004347 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004348 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004349 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004350 {
4351 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004352 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004353 // Use the public resume method here, since this is just
4354 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004355 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004356 }
4357 else
4358 {
4359 // If we didn't restart, run the Stop Hooks here:
4360 // They might also restart the target, so watch for that.
4361 m_process_sp->GetTarget().RunStopHooks();
4362 if (m_process_sp->GetPrivateState() == eStateRunning)
4363 SetRestarted(true);
4364 }
Jim Ingham9575d842011-03-11 03:53:59 +00004365 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004366 }
4367}
4368
4369void
4370Process::ProcessEventData::Dump (Stream *s) const
4371{
4372 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004373 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4374 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004375
Greg Clayton8b82f082011-04-12 05:54:46 +00004376 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004377}
4378
4379const Process::ProcessEventData *
4380Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4381{
4382 if (event_ptr)
4383 {
4384 const EventData *event_data = event_ptr->GetData();
4385 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4386 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4387 }
4388 return NULL;
4389}
4390
4391ProcessSP
4392Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4393{
4394 ProcessSP process_sp;
4395 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4396 if (data)
4397 process_sp = data->GetProcessSP();
4398 return process_sp;
4399}
4400
4401StateType
4402Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4403{
4404 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4405 if (data == NULL)
4406 return eStateInvalid;
4407 else
4408 return data->GetState();
4409}
4410
4411bool
4412Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4413{
4414 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4415 if (data == NULL)
4416 return false;
4417 else
4418 return data->GetRestarted();
4419}
4420
4421void
4422Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4423{
4424 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4425 if (data != NULL)
4426 data->SetRestarted(new_value);
4427}
4428
Jim Ingham0161b492013-02-09 01:29:05 +00004429size_t
4430Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4431{
4432 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4433 if (data != NULL)
4434 return data->GetNumRestartedReasons();
4435 else
4436 return 0;
4437}
4438
4439const char *
4440Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4441{
4442 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4443 if (data != NULL)
4444 return data->GetRestartedReasonAtIndex(idx);
4445 else
4446 return NULL;
4447}
4448
4449void
4450Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4451{
4452 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4453 if (data != NULL)
4454 data->AddRestartedReason(reason);
4455}
4456
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004457bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004458Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4459{
4460 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4461 if (data == NULL)
4462 return false;
4463 else
4464 return data->GetInterrupted ();
4465}
4466
4467void
4468Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4469{
4470 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4471 if (data != NULL)
4472 data->SetInterrupted(new_value);
4473}
4474
4475bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004476Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4477{
4478 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4479 if (data)
4480 {
4481 data->SetUpdateStateOnRemoval();
4482 return true;
4483 }
4484 return false;
4485}
4486
Greg Claytond9e416c2012-02-18 05:35:26 +00004487lldb::TargetSP
4488Process::CalculateTarget ()
4489{
4490 return m_target.shared_from_this();
4491}
4492
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004493void
Greg Clayton0603aa92010-10-04 01:05:56 +00004494Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004495{
Greg Claytonc14ee322011-09-22 04:58:26 +00004496 exe_ctx.SetTargetPtr (&m_target);
4497 exe_ctx.SetProcessPtr (this);
4498 exe_ctx.SetThreadPtr(NULL);
4499 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004500}
4501
Greg Claytone996fd32011-03-08 22:40:15 +00004502//uint32_t
4503//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4504//{
4505// return 0;
4506//}
4507//
4508//ArchSpec
4509//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4510//{
4511// return Host::GetArchSpecForExistingProcess (pid);
4512//}
4513//
4514//ArchSpec
4515//Process::GetArchSpecForExistingProcess (const char *process_name)
4516//{
4517// return Host::GetArchSpecForExistingProcess (process_name);
4518//}
4519//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004520void
4521Process::AppendSTDOUT (const char * s, size_t len)
4522{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004523 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004524 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004525 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004526}
4527
4528void
Greg Clayton93e86192011-11-13 04:45:22 +00004529Process::AppendSTDERR (const char * s, size_t len)
4530{
4531 Mutex::Locker locker (m_stdio_communication_mutex);
4532 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004533 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004534}
4535
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004536void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004537Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004538{
4539 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004540 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004541 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4542}
4543
4544size_t
4545Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4546{
4547 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004548 if (m_profile_data.empty())
4549 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004550
4551 std::string &one_profile_data = m_profile_data.front();
4552 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004553 if (bytes_available > 0)
4554 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004555 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004556 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004557 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4558 static_cast<void*>(buf),
4559 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004560 if (bytes_available > buf_size)
4561 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004562 memcpy(buf, one_profile_data.c_str(), buf_size);
4563 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004564 bytes_available = buf_size;
4565 }
4566 else
4567 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004568 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004569 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004570 }
4571 }
4572 return bytes_available;
4573}
4574
4575
Greg Clayton93e86192011-11-13 04:45:22 +00004576//------------------------------------------------------------------
4577// Process STDIO
4578//------------------------------------------------------------------
4579
4580size_t
4581Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4582{
4583 Mutex::Locker locker(m_stdio_communication_mutex);
4584 size_t bytes_available = m_stdout_data.size();
4585 if (bytes_available > 0)
4586 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004587 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004588 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004589 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4590 static_cast<void*>(buf),
4591 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004592 if (bytes_available > buf_size)
4593 {
4594 memcpy(buf, m_stdout_data.c_str(), buf_size);
4595 m_stdout_data.erase(0, buf_size);
4596 bytes_available = buf_size;
4597 }
4598 else
4599 {
4600 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4601 m_stdout_data.clear();
4602 }
4603 }
4604 return bytes_available;
4605}
4606
4607
4608size_t
4609Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4610{
4611 Mutex::Locker locker(m_stdio_communication_mutex);
4612 size_t bytes_available = m_stderr_data.size();
4613 if (bytes_available > 0)
4614 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004615 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004616 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004617 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4618 static_cast<void*>(buf),
4619 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004620 if (bytes_available > buf_size)
4621 {
4622 memcpy(buf, m_stderr_data.c_str(), buf_size);
4623 m_stderr_data.erase(0, buf_size);
4624 bytes_available = buf_size;
4625 }
4626 else
4627 {
4628 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4629 m_stderr_data.clear();
4630 }
4631 }
4632 return bytes_available;
4633}
4634
4635void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004636Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4637{
4638 Process *process = (Process *) baton;
4639 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4640}
4641
Greg Clayton44d93782014-01-27 23:43:24 +00004642class IOHandlerProcessSTDIO :
4643 public IOHandler
4644{
4645public:
4646 IOHandlerProcessSTDIO (Process *process,
4647 int write_fd) :
4648 IOHandler(process->GetTarget().GetDebugger()),
4649 m_process (process),
4650 m_read_file (),
4651 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004652 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004653 {
4654 m_read_file.SetDescriptor(GetInputFD(), false);
4655 }
4656
4657 virtual
4658 ~IOHandlerProcessSTDIO ()
4659 {
4660
4661 }
4662
4663 bool
4664 OpenPipes ()
4665 {
Greg Clayton100eb932014-07-02 21:10:39 +00004666 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004667 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004668 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004669 }
4670
4671 void
4672 ClosePipes()
4673 {
Greg Clayton100eb932014-07-02 21:10:39 +00004674 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004675 }
4676
4677 // Each IOHandler gets to run until it is done. It should read data
4678 // from the "in" and place output into "out" and "err and return
4679 // when done.
4680 virtual void
4681 Run ()
4682 {
4683 if (m_read_file.IsValid() && m_write_file.IsValid())
4684 {
4685 SetIsDone(false);
4686 if (OpenPipes())
4687 {
4688 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004689 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004690 TerminalState terminal_state;
4691 terminal_state.Save (read_fd, false);
4692 Terminal terminal(read_fd);
4693 terminal.SetCanonical(false);
4694 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004695// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004696#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004697 while (!GetIsDone())
4698 {
4699 fd_set read_fdset;
4700 FD_ZERO (&read_fdset);
4701 FD_SET (read_fd, &read_fdset);
4702 FD_SET (pipe_read_fd, &read_fdset);
4703 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4704 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4705 if (num_set_fds < 0)
4706 {
4707 const int select_errno = errno;
4708
4709 if (select_errno != EINTR)
4710 SetIsDone(true);
4711 }
4712 else if (num_set_fds > 0)
4713 {
4714 char ch = 0;
4715 size_t n;
4716 if (FD_ISSET (read_fd, &read_fdset))
4717 {
4718 n = 1;
4719 if (m_read_file.Read(&ch, n).Success() && n == 1)
4720 {
4721 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4722 SetIsDone(true);
4723 }
4724 else
4725 SetIsDone(true);
4726 }
4727 if (FD_ISSET (pipe_read_fd, &read_fdset))
4728 {
4729 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004730 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004731 {
Greg Clayton100eb932014-07-02 21:10:39 +00004732 switch (ch)
4733 {
4734 case 'q':
4735 SetIsDone(true);
4736 break;
4737 case 'i':
4738 if (StateIsRunningState(m_process->GetState()))
4739 m_process->Halt();
4740 break;
4741 }
Greg Clayton19e11352014-02-26 22:47:33 +00004742 }
Greg Clayton44d93782014-01-27 23:43:24 +00004743 }
4744 }
4745 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004746#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004747 terminal_state.Restore();
4748
4749 }
4750 else
4751 SetIsDone(true);
4752 }
4753 else
4754 SetIsDone(true);
4755 }
4756
4757 // Hide any characters that have been displayed so far so async
4758 // output can be displayed. Refresh() will be called after the
4759 // output has been displayed.
4760 virtual void
4761 Hide ()
4762 {
4763
4764 }
4765 // Called when the async output has been received in order to update
4766 // the input reader (refresh the prompt and redisplay any current
4767 // line(s) that are being edited
4768 virtual void
4769 Refresh ()
4770 {
4771
4772 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004773
Greg Clayton44d93782014-01-27 23:43:24 +00004774 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004775 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004776 {
Greg Clayton19e11352014-02-26 22:47:33 +00004777 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004778 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004779 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004780
Greg Claytonf0066ad2014-05-02 00:45:31 +00004781 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004782 Interrupt ()
4783 {
Greg Clayton19e11352014-02-26 22:47:33 +00004784 // Do only things that are safe to do in an interrupt context (like in
4785 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4786 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4787 // that was written to the pipe and then call m_process->Halt() from a
4788 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004789 if (m_active)
4790 {
4791 char ch = 'i'; // Send 'i' for interrupt
4792 return m_pipe.Write (&ch, 1) == 1;
4793 }
4794 else
4795 {
4796 // This IOHandler might be pushed on the stack, but not being run currently
4797 // so do the right thing if we aren't actively watching for STDIN by sending
4798 // the interrupt to the process. Otherwise the write to the pipe above would
4799 // do nothing. This can happen when the command interpreter is running and
4800 // gets a "expression ...". It will be on the IOHandler thread and sending
4801 // the input is complete to the delegate which will cause the expression to
4802 // run, which will push the process IO handler, but not run it.
4803
4804 if (StateIsRunningState(m_process->GetState()))
4805 {
4806 m_process->SendAsyncInterrupt();
4807 return true;
4808 }
4809 }
4810 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004811 }
Greg Clayton44d93782014-01-27 23:43:24 +00004812
4813 virtual void
4814 GotEOF()
4815 {
4816
4817 }
4818
4819protected:
4820 Process *m_process;
4821 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4822 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004823 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004824};
4825
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004826void
Greg Clayton44d93782014-01-27 23:43:24 +00004827Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004828{
4829 // First set up the Read Thread for reading/handling process I/O
4830
Greg Clayton44d93782014-01-27 23:43:24 +00004831 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004832
4833 if (conn_ap.get())
4834 {
4835 m_stdio_communication.SetConnection (conn_ap.release());
4836 if (m_stdio_communication.IsConnected())
4837 {
4838 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4839 m_stdio_communication.StartReadThread();
4840
4841 // Now read thread is set up, set up input reader.
4842
4843 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004844 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004845 }
4846 }
4847}
4848
Greg Claytonb4874f12014-02-28 18:22:24 +00004849bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004850Process::ProcessIOHandlerIsActive ()
4851{
4852 IOHandlerSP io_handler_sp (m_process_input_reader);
4853 if (io_handler_sp)
4854 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4855 return false;
4856}
4857bool
Greg Clayton44d93782014-01-27 23:43:24 +00004858Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004859{
Greg Clayton44d93782014-01-27 23:43:24 +00004860 IOHandlerSP io_handler_sp (m_process_input_reader);
4861 if (io_handler_sp)
4862 {
4863 io_handler_sp->SetIsDone(false);
4864 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004865 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004866 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004867 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004868}
4869
Greg Claytonb4874f12014-02-28 18:22:24 +00004870bool
Greg Clayton44d93782014-01-27 23:43:24 +00004871Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004872{
Greg Clayton44d93782014-01-27 23:43:24 +00004873 IOHandlerSP io_handler_sp (m_process_input_reader);
4874 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004875 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4876 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004877}
4878
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004879// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004880void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004881Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004882{
Greg Clayton6920b522012-08-22 18:39:03 +00004883 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004884}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004885
Greg Clayton99d0faf2010-11-18 23:32:35 +00004886void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004887Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004888{
Greg Clayton6920b522012-08-22 18:39:03 +00004889 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004890}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004891
Jim Ingham1624a2d2014-05-05 02:26:40 +00004892ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004893Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004894 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004895 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004896 Stream &errors)
4897{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004898 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004899
Jim Ingham77787032011-01-20 02:03:18 +00004900 if (thread_plan_sp.get() == NULL)
4901 {
4902 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004903 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004904 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004905
Jim Ingham7d7931d2013-03-28 00:05:34 +00004906 if (!thread_plan_sp->ValidatePlan(NULL))
4907 {
4908 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004909 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004910 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004911
Greg Claytonc14ee322011-09-22 04:58:26 +00004912 if (exe_ctx.GetProcessPtr() != this)
4913 {
4914 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004915 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004916 }
4917
4918 Thread *thread = exe_ctx.GetThreadPtr();
4919 if (thread == NULL)
4920 {
4921 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004922 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004923 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004924
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004925 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4926 // For that to be true the plan can't be private - since private plans suppress themselves in the
4927 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004928
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004929 bool orig_plan_private = thread_plan_sp->GetPrivate();
4930 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004931
Jim Ingham444586b2011-01-24 06:34:17 +00004932 if (m_private_state.GetValue() != eStateStopped)
4933 {
4934 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004935 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004936 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004937
Jim Ingham66243842011-08-13 00:56:10 +00004938 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004939 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004940 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004941 if (!selected_frame_sp)
4942 {
4943 thread->SetSelectedFrame(0);
4944 selected_frame_sp = thread->GetSelectedFrame();
4945 if (!selected_frame_sp)
4946 {
4947 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004948 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004949 }
4950 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004951
Jim Ingham11b0e052013-02-19 23:22:45 +00004952 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004953
4954 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4955 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004956
Greg Claytonc14ee322011-09-22 04:58:26 +00004957 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004958
Jim Ingham66243842011-08-13 00:56:10 +00004959 uint32_t selected_tid;
4960 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004961 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004962 {
4963 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004964 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004965 }
4966 else
4967 {
4968 selected_tid = LLDB_INVALID_THREAD_ID;
4969 }
4970
Zachary Turner39de3112014-09-09 20:54:56 +00004971 HostThread backup_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004972 lldb::StateType old_state;
4973 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004974
Greg Clayton5160ce52013-03-27 23:08:40 +00004975 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00004976 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00004977 {
Jim Ingham076b3042012-04-10 01:21:57 +00004978 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4979 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004980 // 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 +00004981 // we are fielding public events here.
4982 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004983 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 +00004984
Jim Ingham372787f2012-04-07 00:00:41 +00004985 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004986
4987 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4988 // returning control here.
4989 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4990 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4991 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4992 // do just what we want.
4993 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4994 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4995 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4996 old_state = m_public_state.GetValue();
4997 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004998
Jim Ingham076b3042012-04-10 01:21:57 +00004999 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005000 StartPrivateStateThread(true);
5001 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005002
Jim Ingham372787f2012-04-07 00:00:41 +00005003 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005004
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005005 if (options.GetDebug())
5006 {
5007 // In this case, we aren't actually going to run, we just want to stop right away.
5008 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5009 // FIXME: To make this prettier we should invent some stop reason for this, but that
5010 // is only cosmetic, and this functionality is only of use to lldb developers who can
5011 // live with not pretty...
5012 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005013 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005014 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005015
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005016 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005017
Sean Callanana46ec452012-07-11 21:31:24 +00005018 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005019
Jim Ingham77787032011-01-20 02:03:18 +00005020 {
Sean Callanana46ec452012-07-11 21:31:24 +00005021 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5022 // restored on exit to the function.
5023 //
5024 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5025 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005026
Sean Callanana46ec452012-07-11 21:31:24 +00005027 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005028
Jim Inghamf48169b2010-11-30 02:22:11 +00005029 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005030 {
5031 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005032 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005033 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005034 thread->GetIndexID(),
5035 thread->GetID(),
5036 s.GetData());
5037 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005038
Sean Callanana46ec452012-07-11 21:31:24 +00005039 bool got_event;
5040 lldb::EventSP event_sp;
5041 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005042
Sean Callanana46ec452012-07-11 21:31:24 +00005043 TimeValue* timeout_ptr = NULL;
5044 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005045
Jim Ingham0161b492013-02-09 01:29:05 +00005046 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 +00005047 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005048 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005049 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005050
Jim Ingham0161b492013-02-09 01:29:05 +00005051 // This is just for accounting:
5052 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005053
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005054 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005055 uint32_t one_thread_timeout_usec;
5056 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005057
5058 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5059 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5060 // first timeout already.
5061
5062 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005063 {
5064 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005065 one_thread_timeout_usec = 0;
5066 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005067 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005068 else
Jim Ingham0161b492013-02-09 01:29:05 +00005069 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005070 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005071
Jim Ingham914f4e72014-03-28 21:58:28 +00005072 // If the overall wait is forever, then we only need to set the one thread timeout:
5073 if (timeout_usec == 0)
5074 {
Ed Maste801335c2014-03-31 19:28:14 +00005075 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005076 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005077 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005078 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005079 }
Jim Ingham0161b492013-02-09 01:29:05 +00005080 else
5081 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005082 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5083 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5084 uint64_t computed_one_thread_timeout;
5085 if (option_one_thread_timeout != 0)
5086 {
5087 if (timeout_usec < option_one_thread_timeout)
5088 {
5089 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005090 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005091 }
5092 computed_one_thread_timeout = option_one_thread_timeout;
5093 }
5094 else
5095 {
5096 computed_one_thread_timeout = timeout_usec / 2;
5097 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5098 computed_one_thread_timeout = default_one_thread_timeout_usec;
5099 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005100 one_thread_timeout_usec = computed_one_thread_timeout;
5101 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5102
Jim Ingham0161b492013-02-09 01:29:05 +00005103 }
Jim Ingham0161b492013-02-09 01:29:05 +00005104 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005105
5106 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005107 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 +00005108 options.GetStopOthers(),
5109 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005110 before_first_timeout,
5111 one_thread_timeout_usec,
5112 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005113
Jim Ingham1460e4b2014-01-10 23:46:59 +00005114 // This isn't going to work if there are unfetched events on the queue.
5115 // Are there cases where we might want to run the remaining events here, and then try to
5116 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005117
Jim Ingham1460e4b2014-01-10 23:46:59 +00005118 Event *other_events = listener.PeekAtNextEvent();
5119 if (other_events != NULL)
5120 {
5121 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005122 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005123 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005124
Jim Ingham1460e4b2014-01-10 23:46:59 +00005125 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5126 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5127 // event coalescing to cause us to lose OUR running event...
5128 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005129
Jim Ingham8559a352012-11-26 23:52:18 +00005130 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5131 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005132
5133#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5134 // It's pretty much impossible to write test cases for things like:
5135 // One thread timeout expires, I go to halt, but the process already stopped
5136 // on the function call stop breakpoint. Turning on this define will make us not
5137 // fetch the first event till after the halt. So if you run a quick function, it will have
5138 // completed, and the completion event will be waiting, when you interrupt for halt.
5139 // The expression evaluation should still succeed.
5140 bool miss_first_event = true;
5141#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005142 TimeValue one_thread_timeout;
5143 TimeValue final_timeout;
5144
Jim Ingham35878c42014-04-08 21:33:21 +00005145
Sean Callanana46ec452012-07-11 21:31:24 +00005146 while (1)
5147 {
5148 // We usually want to resume the process if we get to the top of the loop.
5149 // The only exception is if we get two running events with no intervening
5150 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005151 if (log)
5152 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5153 do_resume,
5154 handle_running_event,
5155 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005156
Jim Ingham184e9812013-01-15 02:47:48 +00005157 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005158 {
5159 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005160
Jim Ingham184e9812013-01-15 02:47:48 +00005161 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005162 {
Jim Ingham0161b492013-02-09 01:29:05 +00005163 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005164 Error resume_error = PrivateResume ();
5165 if (!resume_error.Success())
5166 {
Jim Ingham0161b492013-02-09 01:29:05 +00005167 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5168 num_resumes,
5169 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005170 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005171 break;
5172 }
Sean Callanana46ec452012-07-11 21:31:24 +00005173 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005174
Jim Ingham0161b492013-02-09 01:29:05 +00005175 TimeValue resume_timeout = TimeValue::Now();
5176 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005177
Jim Ingham0161b492013-02-09 01:29:05 +00005178 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005179 if (!got_event)
5180 {
5181 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005182 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5183 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005184
Jim Ingham0161b492013-02-09 01:29:05 +00005185 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005186 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005187 break;
5188 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005189
Sean Callanana46ec452012-07-11 21:31:24 +00005190 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005191
Sean Callanana46ec452012-07-11 21:31:24 +00005192 if (stop_state != eStateRunning)
5193 {
Jim Ingham0161b492013-02-09 01:29:05 +00005194 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005195
Jim Ingham0161b492013-02-09 01:29:05 +00005196 if (stop_state == eStateStopped)
5197 {
5198 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5199 if (log)
5200 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5201 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5202 num_resumes,
5203 StateAsCString(stop_state),
5204 restarted,
5205 do_resume,
5206 handle_running_event);
5207 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005208
Jim Ingham0161b492013-02-09 01:29:05 +00005209 if (restarted)
5210 {
5211 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5212 // event here. But if I do, the best thing is to Halt and then get out of here.
5213 Halt();
5214 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005215
Jim Ingham35e1bda2012-10-16 21:41:58 +00005216 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5217 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005218 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005219 break;
5220 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005221
Sean Callanana46ec452012-07-11 21:31:24 +00005222 if (log)
5223 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5224 // We need to call the function synchronously, so spin waiting for it to return.
5225 // If we get interrupted while executing, we're going to lose our context, and
5226 // won't be able to gather the result at this point.
5227 // We set the timeout AFTER the resume, since the resume takes some time and we
5228 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005229 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005230 else
5231 {
Sean Callanana46ec452012-07-11 21:31:24 +00005232 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005233 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005234 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005235
Jim Ingham0161b492013-02-09 01:29:05 +00005236 if (before_first_timeout)
5237 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005238 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005239 {
5240 one_thread_timeout = TimeValue::Now();
5241 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005242 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005243 }
Jim Ingham0161b492013-02-09 01:29:05 +00005244 else
5245 {
5246 if (timeout_usec == 0)
5247 timeout_ptr = NULL;
5248 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005249 {
5250 final_timeout = TimeValue::Now();
5251 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005252 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005253 }
Jim Ingham0161b492013-02-09 01:29:05 +00005254 }
5255 }
5256 else
5257 {
5258 if (timeout_usec == 0)
5259 timeout_ptr = NULL;
5260 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005261 {
5262 final_timeout = TimeValue::Now();
5263 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005264 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005265 }
Jim Ingham0161b492013-02-09 01:29:05 +00005266 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005267
Jim Ingham0161b492013-02-09 01:29:05 +00005268 do_resume = true;
5269 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005270
Sean Callanana46ec452012-07-11 21:31:24 +00005271 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005272 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005273
Jim Ingham0f16e732011-02-08 05:20:59 +00005274 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005275 {
Sean Callanana46ec452012-07-11 21:31:24 +00005276 if (timeout_ptr)
5277 {
Matt Kopec676a4872013-02-21 23:55:31 +00005278 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005279 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5280 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005281 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005282 else
Sean Callanana46ec452012-07-11 21:31:24 +00005283 {
5284 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5285 }
5286 }
Jim Ingham35878c42014-04-08 21:33:21 +00005287
5288#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5289 // See comment above...
5290 if (miss_first_event)
5291 {
5292 usleep(1000);
5293 miss_first_event = false;
5294 got_event = false;
5295 }
5296 else
5297#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005298 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005299
Sean Callanana46ec452012-07-11 21:31:24 +00005300 if (got_event)
5301 {
5302 if (event_sp.get())
5303 {
5304 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005305 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005306 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005307 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005308 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005309 errors.Printf ("Execution halted by user interrupt.");
5310 if (log)
5311 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005312 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005313 }
5314 else
5315 {
5316 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5317 if (log)
5318 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005319
Jim Inghamcfc09352012-07-27 23:57:19 +00005320 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005321 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005322 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005323 {
Jim Ingham0161b492013-02-09 01:29:05 +00005324 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005325 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5326 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005327 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005328 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005329 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005330 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005331 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005332 }
5333 else
5334 {
Jim Ingham0161b492013-02-09 01:29:05 +00005335 // If we were restarted, we just need to go back up to fetch another event.
5336 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005337 {
5338 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005339 {
5340 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5341 }
5342 keep_going = true;
5343 do_resume = false;
5344 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005345
Jim Inghamcfc09352012-07-27 23:57:19 +00005346 }
5347 else
5348 {
Jim Ingham0161b492013-02-09 01:29:05 +00005349 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5350 StopReason stop_reason = eStopReasonInvalid;
5351 if (stop_info_sp)
5352 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005353
Jim Ingham0161b492013-02-09 01:29:05 +00005354 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5355 // it is OUR plan that is complete?
5356 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005357 {
5358 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005359 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5360 // Now mark this plan as private so it doesn't get reported as the stop reason
5361 // after this point.
5362 if (thread_plan_sp)
5363 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005364 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005365 }
5366 else
5367 {
Jim Ingham0161b492013-02-09 01:29:05 +00005368 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005369 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005370 {
5371 if (log)
5372 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005373 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005374 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005375 {
5376 event_to_broadcast_sp = event_sp;
5377 }
Jim Ingham0161b492013-02-09 01:29:05 +00005378 }
Jim Ingham184e9812013-01-15 02:47:48 +00005379 else
Jim Ingham0161b492013-02-09 01:29:05 +00005380 {
5381 if (log)
5382 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005383 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005384 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005385 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005386 }
Jim Ingham184e9812013-01-15 02:47:48 +00005387 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005388 }
Sean Callanana46ec452012-07-11 21:31:24 +00005389 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005390 }
5391 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005392
Jim Inghamcfc09352012-07-27 23:57:19 +00005393 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005394 // This shouldn't really happen, but sometimes we do get two running events without an
5395 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005396 do_resume = false;
5397 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005398 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005399 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005400
Jim Inghamcfc09352012-07-27 23:57:19 +00005401 default:
5402 if (log)
5403 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005404
Jim Inghamcfc09352012-07-27 23:57:19 +00005405 if (stop_state == eStateExited)
5406 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005407
Sean Callananbf154da2012-08-08 17:35:10 +00005408 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005409 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005410 break;
5411 }
Sean Callanana46ec452012-07-11 21:31:24 +00005412 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005413
Sean Callanana46ec452012-07-11 21:31:24 +00005414 if (keep_going)
5415 continue;
5416 else
5417 break;
5418 }
5419 else
5420 {
5421 if (log)
5422 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005423 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005424 break;
5425 }
5426 }
5427 else
5428 {
5429 // If we didn't get an event that means we've timed out...
5430 // We will interrupt the process here. Depending on what we were asked to do we will
5431 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005432
Sean Callanana46ec452012-07-11 21:31:24 +00005433 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005434 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005435 {
Jim Ingham0161b492013-02-09 01:29:05 +00005436 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005437 {
5438 if (timeout_usec != 0)
5439 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005440 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005441 "running for %" PRIu32 " usec with all threads enabled.",
5442 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005443 }
5444 else
5445 {
5446 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005447 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005448 }
5449 }
Sean Callanana46ec452012-07-11 21:31:24 +00005450 else
5451 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005452 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005453 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005454 }
5455 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005456 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005457 "abandoning execution.",
5458 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005459 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005460
Jim Ingham0161b492013-02-09 01:29:05 +00005461 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5462 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5463 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5464 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5465 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005466
Jim Ingham0161b492013-02-09 01:29:05 +00005467 bool back_to_top = true;
5468 uint32_t try_halt_again = 0;
5469 bool do_halt = true;
5470 const uint32_t num_retries = 5;
5471 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005472 {
Jim Ingham0161b492013-02-09 01:29:05 +00005473 Error halt_error;
5474 if (do_halt)
5475 {
5476 if (log)
5477 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5478 halt_error = Halt();
5479 }
5480 if (halt_error.Success())
5481 {
5482 if (log)
5483 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005484
Jim Ingham0161b492013-02-09 01:29:05 +00005485 real_timeout = TimeValue::Now();
5486 real_timeout.OffsetWithMicroSeconds(500000);
5487
5488 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005489
Jim Ingham0161b492013-02-09 01:29:05 +00005490 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005491 {
Jim Ingham0161b492013-02-09 01:29:05 +00005492 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5493 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005494 {
Jim Ingham0161b492013-02-09 01:29:05 +00005495 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5496 if (stop_state == lldb::eStateStopped
5497 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5498 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005499 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005500
Jim Ingham0161b492013-02-09 01:29:05 +00005501 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005502 {
Jim Ingham0161b492013-02-09 01:29:05 +00005503 // Between the time we initiated the Halt and the time we delivered it, the process could have
5504 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005505
Jim Ingham0161b492013-02-09 01:29:05 +00005506 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5507 {
5508 if (log)
5509 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5510 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005511 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005512 back_to_top = false;
5513 break;
5514 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005515
Jim Ingham0161b492013-02-09 01:29:05 +00005516 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5517 {
5518 if (log)
5519 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5520 "Exiting wait loop.");
5521 try_halt_again++;
5522 do_halt = false;
5523 continue;
5524 }
Sean Callanana46ec452012-07-11 21:31:24 +00005525
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005526 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005527 {
5528 if (log)
5529 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005530 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005531 back_to_top = false;
5532 break;
5533 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005534
Jim Ingham0161b492013-02-09 01:29:05 +00005535 if (before_first_timeout)
5536 {
5537 // Set all the other threads to run, and return to the top of the loop, which will continue;
5538 before_first_timeout = false;
5539 thread_plan_sp->SetStopOthers (false);
5540 if (log)
5541 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005542
Jim Ingham0161b492013-02-09 01:29:05 +00005543 back_to_top = true;
5544 break;
5545 }
5546 else
5547 {
5548 // Running all threads failed, so return Interrupted.
5549 if (log)
5550 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
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;
5554 }
Sean Callanana46ec452012-07-11 21:31:24 +00005555 }
5556 }
5557 else
Jim Ingham0161b492013-02-09 01:29:05 +00005558 { if (log)
5559 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5560 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005561 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005562 back_to_top = false;
5563 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005564 }
5565 }
Jim Ingham0161b492013-02-09 01:29:05 +00005566 else
5567 {
5568 try_halt_again++;
5569 continue;
5570 }
Sean Callanana46ec452012-07-11 21:31:24 +00005571 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005572
Jim Ingham0161b492013-02-09 01:29:05 +00005573 if (!back_to_top || try_halt_again > num_retries)
5574 break;
5575 else
5576 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005577 }
Sean Callanana46ec452012-07-11 21:31:24 +00005578 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005579
Sean Callanana46ec452012-07-11 21:31:24 +00005580 // 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 +00005581 if (backup_private_state_thread.GetState() != eThreadStateInvalid)
Sean Callanana46ec452012-07-11 21:31:24 +00005582 {
5583 StopPrivateStateThread();
5584 Error error;
5585 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005586 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005587 {
5588 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5589 }
5590 m_public_state.SetValueNoLock(old_state);
5591
5592 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005593
Jim Ingham184e9812013-01-15 02:47:48 +00005594 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5595 // could happen:
5596 // 1) The execution successfully completed
5597 // 2) We hit a breakpoint, and ignore_breakpoints was true
5598 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005599 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5600 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005601
Jim Ingham8646d3c2014-05-05 02:47:44 +00005602 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005603 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005604 {
5605 thread_plan_sp->RestoreThreadState();
5606 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005607
Sean Callanana46ec452012-07-11 21:31:24 +00005608 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005609 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005610 {
5611 if (log)
5612 {
5613 StreamString s;
5614 if (event_sp)
5615 event_sp->Dump (&s);
5616 else
5617 {
5618 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5619 }
5620
5621 StreamString ts;
5622
5623 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005624
Sean Callanana46ec452012-07-11 21:31:24 +00005625 do
5626 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005627 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005628 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005629 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005630 break;
5631 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005632 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005633 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005634 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005635 break;
5636 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005637 else
Sean Callanana46ec452012-07-11 21:31:24 +00005638 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005639 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5640
5641 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005642 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005643 event_explanation = "<no event data>";
5644 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005645 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005646
Jim Inghamcfc09352012-07-27 23:57:19 +00005647 Process *process = event_data->GetProcessSP().get();
5648
5649 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005650 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005651 event_explanation = "<no process>";
5652 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005653 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005654
Jim Inghamcfc09352012-07-27 23:57:19 +00005655 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005656
Jim Inghamcfc09352012-07-27 23:57:19 +00005657 uint32_t num_threads = thread_list.GetSize();
5658 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005659
Jim Inghamcfc09352012-07-27 23:57:19 +00005660 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005661
Jim Inghamcfc09352012-07-27 23:57:19 +00005662 for (thread_index = 0;
5663 thread_index < num_threads;
5664 ++thread_index)
5665 {
5666 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005667
Jim Inghamcfc09352012-07-27 23:57:19 +00005668 if (!thread)
5669 {
5670 ts.Printf("<?> ");
5671 continue;
5672 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005673
Daniel Malead01b2952012-11-29 21:49:15 +00005674 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005675 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005676
Jim Inghamcfc09352012-07-27 23:57:19 +00005677 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005678 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005679 else
5680 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005681
Jim Inghamcfc09352012-07-27 23:57:19 +00005682 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5683 if (stop_info_sp)
5684 {
5685 const char *stop_desc = stop_info_sp->GetDescription();
5686 if (stop_desc)
5687 ts.PutCString (stop_desc);
5688 }
5689 ts.Printf(">");
5690 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005691
Jim Inghamcfc09352012-07-27 23:57:19 +00005692 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005693 }
Sean Callanana46ec452012-07-11 21:31:24 +00005694 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005695
Jim Inghamcfc09352012-07-27 23:57:19 +00005696 if (event_explanation)
5697 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005698 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005699 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5700 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005701
Jim Inghame4483cf2013-09-27 01:13:01 +00005702 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005703 {
5704 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005705 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5706 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005707 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5708 thread_plan_sp->SetPrivate (orig_plan_private);
5709 }
5710 else
5711 {
5712 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005713 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5714 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005715 }
5716 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005717 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005718 {
5719 if (log)
5720 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005721
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005722 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005723 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005724 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005725 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005726 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005727 }
5728 else
5729 {
Sean Callanana46ec452012-07-11 21:31:24 +00005730 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005731 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005732 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005733 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005734 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005735 }
5736 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5737 {
5738 if (log)
5739 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005740 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005741 }
5742 else
5743 {
5744 if (log)
5745 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005746 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005747 {
5748 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005749 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005750 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5751 thread_plan_sp->SetPrivate (orig_plan_private);
5752 }
5753 }
5754 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005755
Sean Callanana46ec452012-07-11 21:31:24 +00005756 // Thread we ran the function in may have gone away because we ran the target
5757 // Check that it's still there, and if it is put it back in the context. Also restore the
5758 // frame in the context if it is still present.
5759 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5760 if (thread)
5761 {
5762 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5763 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005764
Sean Callanana46ec452012-07-11 21:31:24 +00005765 // Also restore the current process'es selected frame & thread, since this function calling may
5766 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005767
Sean Callanana46ec452012-07-11 21:31:24 +00005768 if (selected_tid != LLDB_INVALID_THREAD_ID)
5769 {
5770 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5771 {
5772 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005773 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005774 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005775 if (old_frame_sp)
5776 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005777 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005778 }
5779 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005780
Sean Callanana46ec452012-07-11 21:31:24 +00005781 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005782
Sean Callanana46ec452012-07-11 21:31:24 +00005783 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005784 {
Sean Callanana46ec452012-07-11 21:31:24 +00005785 if (log)
5786 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5787 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005788 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005789
Jim Inghamf48169b2010-11-30 02:22:11 +00005790 return return_value;
5791}
5792
5793const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005794Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005795{
5796 const char *result_name;
5797
5798 switch (result)
5799 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005800 case eExpressionCompleted:
5801 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005802 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005803 case eExpressionDiscarded:
5804 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005805 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005806 case eExpressionInterrupted:
5807 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005808 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005809 case eExpressionHitBreakpoint:
5810 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005811 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005812 case eExpressionSetupError:
5813 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005814 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005815 case eExpressionParseError:
5816 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005817 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005818 case eExpressionResultUnavailable:
5819 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005820 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005821 case eExpressionTimedOut:
5822 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005823 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005824 case eExpressionStoppedForDebug:
5825 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005826 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005827 }
5828 return result_name;
5829}
5830
Greg Clayton7260f622011-04-18 08:33:37 +00005831void
5832Process::GetStatus (Stream &strm)
5833{
5834 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005835 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005836 {
5837 if (state == eStateExited)
5838 {
5839 int exit_status = GetExitStatus();
5840 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005841 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005842 GetID(),
5843 exit_status,
5844 exit_status,
5845 exit_description ? exit_description : "");
5846 }
5847 else
5848 {
5849 if (state == eStateConnected)
5850 strm.Printf ("Connected to remote target.\n");
5851 else
Daniel Malead01b2952012-11-29 21:49:15 +00005852 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005853 }
5854 }
5855 else
5856 {
Daniel Malead01b2952012-11-29 21:49:15 +00005857 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005858 }
5859}
5860
5861size_t
5862Process::GetThreadStatus (Stream &strm,
5863 bool only_threads_with_stop_reason,
5864 uint32_t start_frame,
5865 uint32_t num_frames,
5866 uint32_t num_frames_with_source)
5867{
5868 size_t num_thread_infos_dumped = 0;
5869
Jim Ingham4a65fb12014-03-07 11:20:03 +00005870 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5871 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5872 // ID's, and look them up one by one:
5873
5874 uint32_t num_threads;
5875 std::vector<uint32_t> thread_index_array;
5876 //Scope for thread list locker;
5877 {
5878 Mutex::Locker locker (GetThreadList().GetMutex());
5879 ThreadList &curr_thread_list = GetThreadList();
5880 num_threads = curr_thread_list.GetSize();
5881 uint32_t idx;
5882 thread_index_array.resize(num_threads);
5883 for (idx = 0; idx < num_threads; ++idx)
5884 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5885 }
5886
Greg Clayton7260f622011-04-18 08:33:37 +00005887 for (uint32_t i = 0; i < num_threads; i++)
5888 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005889 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5890 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005891 {
5892 if (only_threads_with_stop_reason)
5893 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005894 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005895 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005896 continue;
5897 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005898 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005899 start_frame,
5900 num_frames,
5901 num_frames_with_source);
5902 ++num_thread_infos_dumped;
5903 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005904 else
5905 {
5906 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5907 if (log)
5908 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5909
5910 }
Greg Clayton7260f622011-04-18 08:33:37 +00005911 }
5912 return num_thread_infos_dumped;
5913}
5914
Greg Claytona9f40ad2012-02-22 04:37:26 +00005915void
5916Process::AddInvalidMemoryRegion (const LoadRange &region)
5917{
5918 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5919}
5920
5921bool
5922Process::RemoveInvalidMemoryRange (const LoadRange &region)
5923{
5924 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5925}
5926
Jim Ingham372787f2012-04-07 00:00:41 +00005927void
5928Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5929{
5930 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5931}
5932
5933bool
5934Process::RunPreResumeActions ()
5935{
5936 bool result = true;
5937 while (!m_pre_resume_actions.empty())
5938 {
5939 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5940 m_pre_resume_actions.pop_back();
5941 bool this_result = action.callback (action.baton);
5942 if (result == true) result = this_result;
5943 }
5944 return result;
5945}
5946
5947void
5948Process::ClearPreResumeActions ()
5949{
5950 m_pre_resume_actions.clear();
5951}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005952
Greg Claytonfa559e52012-05-18 02:38:05 +00005953void
5954Process::Flush ()
5955{
5956 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005957 m_extended_thread_list.Flush();
5958 m_extended_thread_stop_id = 0;
5959 m_queue_list.Clear();
5960 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005961}
Greg Clayton90ba8112012-12-05 00:16:59 +00005962
5963void
5964Process::DidExec ()
5965{
Todd Fiala76e0fc92014-08-27 22:58:26 +00005966 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5967 if (log)
5968 log->Printf ("Process::%s()", __FUNCTION__);
5969
Greg Clayton90ba8112012-12-05 00:16:59 +00005970 Target &target = GetTarget();
5971 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005972 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005973 m_dynamic_checkers_ap.reset();
5974 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005975 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005976 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005977 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005978 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005979 m_image_tokens.clear();
5980 m_allocated_memory_cache.Clear();
5981 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005982 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005983 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005984 DoDidExec();
5985 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005986 // Flush the process (threads and all stack frames) after running CompleteAttach()
5987 // in case the dynamic loader loaded things in new locations.
5988 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005989
5990 // After we figure out what was loaded/unloaded in CompleteAttach,
5991 // we need to let the target know so it can do any cleanup it needs to.
5992 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005993}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005994
Jim Ingham1460e4b2014-01-10 23:46:59 +00005995addr_t
5996Process::ResolveIndirectFunction(const Address *address, Error &error)
5997{
5998 if (address == nullptr)
5999 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006000 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006001 return LLDB_INVALID_ADDRESS;
6002 }
6003
6004 addr_t function_addr = LLDB_INVALID_ADDRESS;
6005
6006 addr_t addr = address->GetLoadAddress(&GetTarget());
6007 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6008 if (iter != m_resolved_indirect_addresses.end())
6009 {
6010 function_addr = (*iter).second;
6011 }
6012 else
6013 {
6014 if (!InferiorCall(this, address, function_addr))
6015 {
6016 Symbol *symbol = address->CalculateSymbolContextSymbol();
6017 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6018 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6019 function_addr = LLDB_INVALID_ADDRESS;
6020 }
6021 else
6022 {
6023 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6024 }
6025 }
6026 return function_addr;
6027}
6028
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006029void
6030Process::ModulesDidLoad (ModuleList &module_list)
6031{
6032 SystemRuntime *sys_runtime = GetSystemRuntime();
6033 if (sys_runtime)
6034 {
6035 sys_runtime->ModulesDidLoad (module_list);
6036 }
6037
6038 GetJITLoaders().ModulesDidLoad (module_list);
6039}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006040
6041ThreadCollectionSP
6042Process::GetHistoryThreads(lldb::addr_t addr)
6043{
6044 ThreadCollectionSP threads;
6045
6046 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6047
6048 if (! memory_history.get()) {
6049 return threads;
6050 }
6051
6052 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6053
6054 return threads;
6055}