blob: 4de1a5bd967efe3773c2bfa445cac78fe1e6b125 [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"
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000024#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000025#include "lldb/Expression/ClangUserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000026#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000029#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000030#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Interpreter/CommandInterpreter.h"
33#include "lldb/Symbol/Symbol.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));
Todd Fialaf72fa672014-10-07 16:05:21 +00002841
2842 // Note, the stop event was consumed above, but not handled. This was done
2843 // to give DidLaunch a chance to run. The target is either stopped or crashed.
2844 // Directly set the state. This is done to prevent a stop message with a bunch
2845 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
2846 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00002847
2848 if (PrivateStateThreadIsValid ())
2849 ResumePrivateStateThread ();
2850 else
2851 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 }
2853 else if (state == eStateExited)
2854 {
2855 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2856 // not likely to work, and return an invalid pid.
2857 HandlePrivateEvent (event_sp);
2858 }
2859 }
2860 }
2861 }
2862 else
2863 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002864 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865 }
2866 }
2867 return error;
2868}
2869
Greg Claytonc3776bf2012-02-09 06:16:32 +00002870
2871Error
2872Process::LoadCore ()
2873{
2874 Error error = DoLoadCore();
2875 if (error.Success())
2876 {
2877 if (PrivateStateThreadIsValid ())
2878 ResumePrivateStateThread ();
2879 else
2880 StartPrivateStateThread ();
2881
Greg Claytonc859e2d2012-02-13 23:10:39 +00002882 DynamicLoader *dyld = GetDynamicLoader ();
2883 if (dyld)
2884 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002885
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002886 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002887
Jason Molendaeef51062013-11-05 03:57:19 +00002888 SystemRuntime *system_runtime = GetSystemRuntime ();
2889 if (system_runtime)
2890 system_runtime->DidAttach();
2891
Greg Claytonc859e2d2012-02-13 23:10:39 +00002892 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002893 // We successfully loaded a core file, now pretend we stopped so we can
2894 // show all of the threads in the core file and explore the crashed
2895 // state.
2896 SetPrivateState (eStateStopped);
2897
2898 }
2899 return error;
2900}
2901
Greg Claytonc859e2d2012-02-13 23:10:39 +00002902DynamicLoader *
2903Process::GetDynamicLoader ()
2904{
2905 if (m_dyld_ap.get() == NULL)
2906 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2907 return m_dyld_ap.get();
2908}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002909
Todd Fialaaf245d12014-06-30 21:05:18 +00002910const lldb::DataBufferSP
2911Process::GetAuxvData()
2912{
2913 return DataBufferSP ();
2914}
2915
Andrew MacPherson17220c12014-03-05 10:12:43 +00002916JITLoaderList &
2917Process::GetJITLoaders ()
2918{
2919 if (!m_jit_loaders_ap)
2920 {
2921 m_jit_loaders_ap.reset(new JITLoaderList());
2922 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2923 }
2924 return *m_jit_loaders_ap;
2925}
2926
Jason Molendaeef51062013-11-05 03:57:19 +00002927SystemRuntime *
2928Process::GetSystemRuntime ()
2929{
2930 if (m_system_runtime_ap.get() == NULL)
2931 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
2932 return m_system_runtime_ap.get();
2933}
2934
Todd Fiala76e0fc92014-08-27 22:58:26 +00002935Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
2936 NextEventAction (process),
2937 m_exec_count (exec_count)
2938{
2939 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2940 if (log)
2941 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
2942}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002943
Jim Inghambb3a2832011-01-29 01:49:25 +00002944Process::NextEventAction::EventActionResult
2945Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946{
Todd Fiala76e0fc92014-08-27 22:58:26 +00002947 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2948
Jim Inghambb3a2832011-01-29 01:49:25 +00002949 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00002950 if (log)
2951 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
2952
2953 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002954 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002955 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002956 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002957 return eEventActionRetry;
2958
2959 case eStateStopped:
2960 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002961 {
2962 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002963 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002964 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002965 // We don't want these events to be reported, so go set the ShouldReportStop here:
2966 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2967
Greg Claytonc9ed4782011-11-12 02:10:56 +00002968 if (m_exec_count > 0)
2969 {
2970 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00002971
2972 if (log)
2973 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
2974
Jim Ingham221d51c2013-05-08 00:35:16 +00002975 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00002976 return eEventActionRetry;
2977 }
2978 else
2979 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00002980 if (log)
2981 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
2982
Greg Claytonc9ed4782011-11-12 02:10:56 +00002983 m_process->CompleteAttach ();
2984 return eEventActionSuccess;
2985 }
2986 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002987 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002988
Greg Clayton513c26c2011-01-29 07:10:55 +00002989 default:
2990 case eStateExited:
2991 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002992 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002993 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002994
2995 m_exit_string.assign ("No valid Process");
2996 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002997}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998
Jim Inghambb3a2832011-01-29 01:49:25 +00002999Process::NextEventAction::EventActionResult
3000Process::AttachCompletionHandler::HandleBeingInterrupted()
3001{
3002 return eEventActionSuccess;
3003}
3004
3005const char *
3006Process::AttachCompletionHandler::GetExitString ()
3007{
3008 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003009}
3010
3011Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003012Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003013{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003015 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003016 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003017 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003018 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003019 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003020
Greg Clayton144f3a92011-11-15 03:53:30 +00003021 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003022 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003023 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003024 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003025 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003026
Greg Clayton144f3a92011-11-15 03:53:30 +00003027 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003028 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003029 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3030
3031 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003033 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3034 if (error.Success())
3035 {
Ed Maste64fad602013-07-29 20:58:06 +00003036 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003037 {
3038 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003039 const bool restarted = false;
3040 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003041 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003042 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003043 }
3044 else
3045 {
3046 // This shouldn't happen
3047 error.SetErrorString("failed to acquire process run lock");
3048 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003049
Greg Clayton144f3a92011-11-15 03:53:30 +00003050 if (error.Fail())
3051 {
3052 if (GetID() != LLDB_INVALID_PROCESS_ID)
3053 {
3054 SetID (LLDB_INVALID_PROCESS_ID);
3055 if (error.AsCString() == NULL)
3056 error.SetErrorString("attach failed");
3057
3058 SetExitStatus(-1, error.AsCString());
3059 }
3060 }
3061 else
3062 {
3063 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3064 StartPrivateStateThread();
3065 }
3066 return error;
3067 }
Greg Claytone996fd32011-03-08 22:40:15 +00003068 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003069 else
Greg Claytone996fd32011-03-08 22:40:15 +00003070 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003071 ProcessInstanceInfoList process_infos;
3072 PlatformSP platform_sp (m_target.GetPlatform ());
3073
3074 if (platform_sp)
3075 {
3076 ProcessInstanceInfoMatch match_info;
3077 match_info.GetProcessInfo() = attach_info;
3078 match_info.SetNameMatchType (eNameMatchEquals);
3079 platform_sp->FindProcesses (match_info, process_infos);
3080 const uint32_t num_matches = process_infos.GetSize();
3081 if (num_matches == 1)
3082 {
3083 attach_pid = process_infos.GetProcessIDAtIndex(0);
3084 // Fall through and attach using the above process ID
3085 }
3086 else
3087 {
3088 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3089 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003090 {
3091 StreamString s;
3092 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3093 for (size_t i = 0; i < num_matches; i++)
3094 {
3095 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3096 }
3097 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3098 process_name,
3099 s.GetData());
3100 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003101 else
3102 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3103 }
3104 }
3105 else
3106 {
3107 error.SetErrorString ("invalid platform, can't find processes by name");
3108 return error;
3109 }
Greg Claytone996fd32011-03-08 22:40:15 +00003110 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003111 }
3112 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003113 {
3114 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003115 }
3116 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003117
3118 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003119 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003120 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003121 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003123
Ed Maste64fad602013-07-29 20:58:06 +00003124 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003125 {
3126 // Now attach using these arguments.
3127 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003128 const bool restarted = false;
3129 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003130 error = DoAttachToProcessWithID (attach_pid, attach_info);
3131 }
3132 else
3133 {
3134 // This shouldn't happen
3135 error.SetErrorString("failed to acquire process run lock");
3136 }
3137
Greg Clayton144f3a92011-11-15 03:53:30 +00003138 if (error.Success())
3139 {
3140
3141 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3142 StartPrivateStateThread();
3143 }
3144 else
Greg Claytone996fd32011-03-08 22:40:15 +00003145 {
3146 if (GetID() != LLDB_INVALID_PROCESS_ID)
3147 {
3148 SetID (LLDB_INVALID_PROCESS_ID);
3149 const char *error_string = error.AsCString();
3150 if (error_string == NULL)
3151 error_string = "attach failed";
3152
3153 SetExitStatus(-1, error_string);
3154 }
3155 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156 }
3157 }
3158 return error;
3159}
3160
Greg Clayton93d3c8332011-02-16 04:46:07 +00003161void
3162Process::CompleteAttach ()
3163{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003164 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3165 if (log)
3166 log->Printf ("Process::%s()", __FUNCTION__);
3167
Greg Clayton93d3c8332011-02-16 04:46:07 +00003168 // Let the process subclass figure out at much as it can about the process
3169 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003170 ArchSpec process_arch;
3171 DidAttach(process_arch);
3172
3173 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003174 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003175 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003176 if (log)
3177 {
3178 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3179 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3180 __FUNCTION__,
3181 triple_str ? triple_str : "<null>");
3182 }
3183 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003184
Jim Ingham4299fdb2011-09-15 01:10:17 +00003185 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3186 // the same as the one we've already set, switch architectures.
3187 PlatformSP platform_sp (m_target.GetPlatform ());
3188 assert (platform_sp.get());
3189 if (platform_sp)
3190 {
Greg Clayton70512312012-05-08 01:45:38 +00003191 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003192 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003193 {
3194 ArchSpec platform_arch;
3195 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3196 if (platform_sp)
3197 {
3198 m_target.SetPlatform (platform_sp);
3199 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003200 if (log)
3201 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 +00003202 }
3203 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003204 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003205 {
3206 ProcessInstanceInfo process_info;
3207 platform_sp->GetProcessInfo (GetID(), process_info);
3208 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003209 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003210 {
Greg Clayton70512312012-05-08 01:45:38 +00003211 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003212 if (log)
3213 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 ());
3214 }
Greg Clayton70512312012-05-08 01:45:38 +00003215 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003216 }
3217
3218 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003219 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003220 DynamicLoader *dyld = GetDynamicLoader ();
3221 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003222 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003223 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003224 if (log)
3225 {
3226 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3227 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3228 __FUNCTION__,
3229 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3230 dyld->GetPluginName().AsCString ("<unnamed>"));
3231 }
3232 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003233
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003234 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003235
Jason Molendaeef51062013-11-05 03:57:19 +00003236 SystemRuntime *system_runtime = GetSystemRuntime ();
3237 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003238 {
Jason Molendaeef51062013-11-05 03:57:19 +00003239 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003240 if (log)
3241 {
3242 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3243 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3244 __FUNCTION__,
3245 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3246 system_runtime->GetPluginName().AsCString("<unnamed>"));
3247 }
3248 }
Jason Molendaeef51062013-11-05 03:57:19 +00003249
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003250 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003251 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003252 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003253 Mutex::Locker modules_locker(target_modules.GetMutex());
3254 size_t num_modules = target_modules.GetSize();
3255 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003256
Andy Gibbsa297a972013-06-19 19:04:53 +00003257 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003258 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003259 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003260 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003261 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003262 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003263 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003264 break;
3265 }
3266 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003267 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003268 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003269 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003270 if (log)
3271 {
3272 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3273 log->Printf ("Process::%s after looping through modules, target executable is %s",
3274 __FUNCTION__,
3275 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3276 }
3277 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003278}
3279
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003281Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003282{
Greg Claytonb766a732011-02-04 01:58:07 +00003283 m_abi_sp.reset();
3284 m_process_input_reader.reset();
3285
3286 // Find the process and its architecture. Make sure it matches the architecture
3287 // of the current Target, and if not adjust it.
3288
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003289 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003290 if (error.Success())
3291 {
Greg Clayton71337622011-02-24 22:24:29 +00003292 if (GetID() != LLDB_INVALID_PROCESS_ID)
3293 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003294 EventSP event_sp;
3295 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3296
3297 if (state == eStateStopped || state == eStateCrashed)
3298 {
3299 // If we attached and actually have a process on the other end, then
3300 // this ended up being the equivalent of an attach.
3301 CompleteAttach ();
3302
3303 // This delays passing the stopped event to listeners till
3304 // CompleteAttach gets a chance to complete...
3305 HandlePrivateEvent (event_sp);
3306
3307 }
Greg Clayton71337622011-02-24 22:24:29 +00003308 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003309
3310 if (PrivateStateThreadIsValid ())
3311 ResumePrivateStateThread ();
3312 else
3313 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003314 }
3315 return error;
3316}
3317
3318
3319Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003320Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003321{
Greg Clayton5160ce52013-03-27 23:08:40 +00003322 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003323 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003324 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003325 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003326 StateAsCString(m_public_state.GetValue()),
3327 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328
3329 Error error (WillResume());
3330 // Tell the process it is about to resume before the thread list
3331 if (error.Success())
3332 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003333 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003334 // can let all of our threads know that they are about to be
3335 // resumed. Threads will each be called with
3336 // Thread::WillResume(StateType) where StateType contains the state
3337 // that they are supposed to have when the process is resumed
3338 // (suspended/running/stepping). Threads should also check
3339 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003340 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003341 if (m_thread_list.WillResume())
3342 {
Jim Ingham372787f2012-04-07 00:00:41 +00003343 // Last thing, do the PreResumeActions.
3344 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003345 {
Jim Ingham0161b492013-02-09 01:29:05 +00003346 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003347 }
3348 else
3349 {
3350 m_mod_id.BumpResumeID();
3351 error = DoResume();
3352 if (error.Success())
3353 {
3354 DidResume();
3355 m_thread_list.DidResume();
3356 if (log)
3357 log->Printf ("Process thinks the process has resumed.");
3358 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003359 }
3360 }
3361 else
3362 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003363 // Somebody wanted to run without running. So generate a continue & a stopped event,
3364 // and let the world handle them.
3365 if (log)
3366 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3367
3368 SetPrivateState(eStateRunning);
3369 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 }
3371 }
Jim Ingham444586b2011-01-24 06:34:17 +00003372 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003373 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374 return error;
3375}
3376
3377Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003378Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003379{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003380 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3381 // in case it was already set and some thread plan logic calls halt on its
3382 // own.
3383 m_clear_thread_plans_on_stop |= clear_thread_plans;
3384
Jim Inghamaacc3182012-06-06 00:29:30 +00003385 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3386 // we could just straightaway get another event. It just narrows the window...
3387 m_currently_handling_event.WaitForValueEqualTo(false);
3388
3389
Jim Inghambb3a2832011-01-29 01:49:25 +00003390 // Pause our private state thread so we can ensure no one else eats
3391 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003392 Listener halt_listener ("lldb.process.halt_listener");
3393 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003394
Jim Inghambb3a2832011-01-29 01:49:25 +00003395 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003396 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003397
Greg Clayton06357c92014-07-30 17:38:47 +00003398 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003399 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003400 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003401
Greg Clayton513c26c2011-01-29 07:10:55 +00003402 bool caused_stop = false;
3403
3404 // Ask the process subclass to actually halt our process
3405 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003407 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003408 if (m_public_state.GetValue() == eStateAttaching)
3409 {
Greg Clayton06357c92014-07-30 17:38:47 +00003410 // Don't hijack and eat the eStateExited as the code that was doing
3411 // the attach will be waiting for this event...
3412 RestorePrivateProcessEvents();
3413 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003414 SetExitStatus(SIGKILL, "Cancelled async attach.");
3415 Destroy ();
3416 }
3417 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003418 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003419 // If "caused_stop" is true, then DoHalt stopped the process. If
3420 // "caused_stop" is false, the process was already stopped.
3421 // If the DoHalt caused the process to stop, then we want to catch
3422 // this event and set the interrupted bool to true before we pass
3423 // this along so clients know that the process was interrupted by
3424 // a halt command.
3425 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003426 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003427 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003428 TimeValue timeout_time;
3429 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003430 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003431 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3432 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003433
Jim Ingham0f16e732011-02-08 05:20:59 +00003434 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003435 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003436 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003437 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003438 }
3439 else
3440 {
Greg Clayton2637f822011-11-17 01:23:07 +00003441 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003442 {
3443 // We caused the process to interrupt itself, so mark this
3444 // as such in the stop event so clients can tell an interrupted
3445 // process from a natural stop
3446 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3447 }
3448 else
3449 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003450 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003451 if (log)
3452 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3453 error.SetErrorString ("Did not get stopped event after halt.");
3454 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003455 }
3456 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003457 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003458 }
3459 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003460 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003461 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003462 if (!restored_process_events)
3463 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003464
3465 // Post any event we might have consumed. If all goes well, we will have
3466 // stopped the process, intercepted the event and set the interrupted
3467 // bool in the event. Post it to the private event queue and that will end up
3468 // correctly setting the state.
3469 if (event_sp)
3470 m_private_state_broadcaster.BroadcastEvent(event_sp);
3471
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003472 return error;
3473}
3474
3475Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003476Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3477{
3478 Error error;
3479 if (m_public_state.GetValue() == eStateRunning)
3480 {
3481 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3482 if (log)
3483 log->Printf("Process::Destroy() About to halt.");
3484 error = Halt();
3485 if (error.Success())
3486 {
3487 // Consume the halt event.
3488 TimeValue timeout (TimeValue::Now());
3489 timeout.OffsetWithSeconds(1);
3490 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3491
3492 // If the process exited while we were waiting for it to stop, put the exited event into
3493 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3494 // they don't have a process anymore...
3495
3496 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3497 {
3498 if (log)
3499 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3500 return error;
3501 }
3502 else
3503 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3504
3505 if (state != eStateStopped)
3506 {
3507 if (log)
3508 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3509 // If we really couldn't stop the process then we should just error out here, but if the
3510 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3511 StateType private_state = m_private_state.GetValue();
3512 if (private_state != eStateStopped)
3513 {
3514 return error;
3515 }
3516 }
3517 }
3518 else
3519 {
3520 if (log)
3521 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3522 }
3523 }
3524 return error;
3525}
3526
3527Error
Jim Inghamacff8952013-05-02 00:27:30 +00003528Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003530 EventSP exit_event_sp;
3531 Error error;
3532 m_destroy_in_process = true;
3533
3534 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003535
3536 if (error.Success())
3537 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003538 if (DetachRequiresHalt())
3539 {
3540 error = HaltForDestroyOrDetach (exit_event_sp);
3541 if (!error.Success())
3542 {
3543 m_destroy_in_process = false;
3544 return error;
3545 }
3546 else if (exit_event_sp)
3547 {
3548 // We shouldn't need to do anything else here. There's no process left to detach from...
3549 StopPrivateStateThread();
3550 m_destroy_in_process = false;
3551 return error;
3552 }
3553 }
3554
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003555 m_thread_list.DiscardThreadPlans();
3556 DisableAllBreakpointSites();
3557
Jim Inghamacff8952013-05-02 00:27:30 +00003558 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559 if (error.Success())
3560 {
3561 DidDetach();
3562 StopPrivateStateThread();
3563 }
Jim Inghamacff8952013-05-02 00:27:30 +00003564 else
3565 {
3566 return error;
3567 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003568 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003569 m_destroy_in_process = false;
3570
3571 // If we exited when we were waiting for a process to stop, then
3572 // forward the event here so we don't lose the event
3573 if (exit_event_sp)
3574 {
3575 // Directly broadcast our exited event because we shut down our
3576 // private state thread above
3577 BroadcastEvent(exit_event_sp);
3578 }
3579
3580 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3581 // the last events through the event system, in which case we might strand the write lock. Unlock
3582 // it here so when we do to tear down the process we don't get an error destroying the lock.
3583
Ed Maste64fad602013-07-29 20:58:06 +00003584 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003585 return error;
3586}
3587
3588Error
3589Process::Destroy ()
3590{
Jim Ingham09437922013-03-01 20:04:25 +00003591
3592 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3593 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3594 // failed and the process stays around for some reason it won't be in a confused state.
3595
3596 m_destroy_in_process = true;
3597
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003598 Error error (WillDestroy());
3599 if (error.Success())
3600 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003601 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003602 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003603 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003604 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003605 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003606
Jim Inghamaacc3182012-06-06 00:29:30 +00003607 if (m_public_state.GetValue() != eStateRunning)
3608 {
3609 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3610 // kill it, we don't want it hitting a breakpoint...
3611 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3612 // we're not going to have much luck doing this now.
3613 m_thread_list.DiscardThreadPlans();
3614 DisableAllBreakpointSites();
3615 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003616
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617 error = DoDestroy();
3618 if (error.Success())
3619 {
3620 DidDestroy();
3621 StopPrivateStateThread();
3622 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003623 m_stdio_communication.StopReadThread();
3624 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003625
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003626 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003627 {
3628 m_process_input_reader->SetIsDone(true);
3629 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003630 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003631 }
3632
Greg Clayton85fb1b92012-09-11 02:33:37 +00003633 // If we exited when we were waiting for a process to stop, then
3634 // forward the event here so we don't lose the event
3635 if (exit_event_sp)
3636 {
3637 // Directly broadcast our exited event because we shut down our
3638 // private state thread above
3639 BroadcastEvent(exit_event_sp);
3640 }
3641
Jim Inghamb1e2e842012-04-12 18:49:31 +00003642 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3643 // the last events through the event system, in which case we might strand the write lock. Unlock
3644 // 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 +00003645 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646 }
Jim Ingham09437922013-03-01 20:04:25 +00003647
3648 m_destroy_in_process = false;
3649
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650 return error;
3651}
3652
3653Error
3654Process::Signal (int signal)
3655{
3656 Error error (WillSignal());
3657 if (error.Success())
3658 {
3659 error = DoSignal(signal);
3660 if (error.Success())
3661 DidSignal();
3662 }
3663 return error;
3664}
3665
Greg Clayton514487e2011-02-15 21:59:32 +00003666lldb::ByteOrder
3667Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003668{
Greg Clayton514487e2011-02-15 21:59:32 +00003669 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003670}
3671
3672uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003673Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003674{
Greg Clayton514487e2011-02-15 21:59:32 +00003675 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676}
3677
Greg Clayton514487e2011-02-15 21:59:32 +00003678
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003679bool
3680Process::ShouldBroadcastEvent (Event *event_ptr)
3681{
3682 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3683 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003684 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003685
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003686 switch (state)
3687 {
Greg Claytonb766a732011-02-04 01:58:07 +00003688 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003689 case eStateAttaching:
3690 case eStateLaunching:
3691 case eStateDetached:
3692 case eStateExited:
3693 case eStateUnloaded:
3694 // These events indicate changes in the state of the debugging session, always report them.
3695 return_value = true;
3696 break;
3697 case eStateInvalid:
3698 // We stopped for no apparent reason, don't report it.
3699 return_value = false;
3700 break;
3701 case eStateRunning:
3702 case eStateStepping:
3703 // If we've started the target running, we handle the cases where we
3704 // are already running and where there is a transition from stopped to
3705 // running differently.
3706 // running -> running: Automatically suppress extra running events
3707 // stopped -> running: Report except when there is one or more no votes
3708 // and no yes votes.
3709 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003710 if (m_force_next_event_delivery)
3711 return_value = true;
3712 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003713 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003714 switch (m_last_broadcast_state)
3715 {
3716 case eStateRunning:
3717 case eStateStepping:
3718 // We always suppress multiple runnings with no PUBLIC stop in between.
3719 return_value = false;
3720 break;
3721 default:
3722 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003723 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003724 // events. If I run the lldb/test/thread/a.out file and
3725 // break at main.cpp:58, run and hit the breakpoints on
3726 // multiple threads, then somehow during the stepping over
3727 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728
Jim Ingham1460e4b2014-01-10 23:46:59 +00003729 // This is a transition from stop to run.
3730 switch (m_thread_list.ShouldReportRun (event_ptr))
3731 {
3732 case eVoteYes:
3733 case eVoteNoOpinion:
3734 return_value = true;
3735 break;
3736 case eVoteNo:
3737 return_value = false;
3738 break;
3739 }
3740 break;
3741 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003742 }
3743 break;
3744 case eStateStopped:
3745 case eStateCrashed:
3746 case eStateSuspended:
3747 {
3748 // We've stopped. First see if we're going to restart the target.
3749 // If we are going to stop, then we always broadcast the event.
3750 // 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 +00003751 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003752
Jim Inghamcb4ca112012-05-16 01:32:14 +00003753 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003754 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003755 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003756 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003757 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003758 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003759 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003760 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3761 // so they can properly set their state.
3762 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003763 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003764 }
3765 else
3766 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003767 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3768 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003769
Jim Ingham0161b492013-02-09 01:29:05 +00003770 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3771 // Asking the thread list is also not likely to go well, since we are running again.
3772 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003773
Jim Ingham0161b492013-02-09 01:29:05 +00003774 if (!was_restarted)
3775 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003776
Jim Ingham221d51c2013-05-08 00:35:16 +00003777 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003778 {
Jim Ingham0161b492013-02-09 01:29:05 +00003779 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3780 if (log)
3781 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003782 should_resume, StateAsCString(state),
3783 was_restarted, stop_vote);
3784
Jim Ingham0161b492013-02-09 01:29:05 +00003785 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786 {
3787 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003788 return_value = true;
3789 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003791 case eVoteNo:
3792 return_value = false;
3793 break;
3794 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003795
Jim Inghamcb95f342012-09-05 21:13:56 +00003796 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003797 {
3798 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003799 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3800 static_cast<void*>(event_ptr),
3801 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003802 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003803 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003804 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003805
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003806 }
3807 else
3808 {
3809 return_value = true;
3810 SynchronouslyNotifyStateChanged (state);
3811 }
3812 }
3813 }
Jim Ingham0161b492013-02-09 01:29:05 +00003814 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003815 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003816
Jim Ingham1460e4b2014-01-10 23:46:59 +00003817 // Forcing the next event delivery is a one shot deal. So reset it here.
3818 m_force_next_event_delivery = false;
3819
Jim Ingham0161b492013-02-09 01:29:05 +00003820 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3821 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3822 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3823 // because the PublicState reflects the last event pulled off the queue, and there may be several
3824 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3825 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003826
Jim Ingham0161b492013-02-09 01:29:05 +00003827 if (return_value)
3828 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003829
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003830 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003831 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003832 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00003833 StateAsCString(m_last_broadcast_state),
3834 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003835 return return_value;
3836}
3837
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003838
3839bool
Jim Ingham372787f2012-04-07 00:00:41 +00003840Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003841{
Greg Clayton5160ce52013-03-27 23:08:40 +00003842 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843
Greg Clayton8b82f082011-04-12 05:54:46 +00003844 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003845 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003846 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3847
Jim Ingham372787f2012-04-07 00:00:41 +00003848 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003849 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850
3851 // Create a thread that watches our internal state and controls which
3852 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003853 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00003854
Zachary Turner39de3112014-09-09 20:54:56 +00003855 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00003856 {
Zachary Turner39de3112014-09-09 20:54:56 +00003857 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
3858 if (already_running)
3859 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3860 else
3861 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00003862 }
Jim Ingham372787f2012-04-07 00:00:41 +00003863 else
Todd Fiala17096d72014-07-16 19:03:16 +00003864 {
3865 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00003866 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003867 else
Zachary Turner39de3112014-09-09 20:54:56 +00003868 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00003869 }
3870
Jim Ingham076b3042012-04-10 01:21:57 +00003871 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00003872 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00003873 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00003874 {
3875 ResumePrivateStateThread();
3876 return true;
3877 }
3878 else
3879 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003880}
3881
3882void
3883Process::PausePrivateStateThread ()
3884{
3885 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3886}
3887
3888void
3889Process::ResumePrivateStateThread ()
3890{
3891 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3892}
3893
3894void
3895Process::StopPrivateStateThread ()
3896{
Greg Clayton8b82f082011-04-12 05:54:46 +00003897 if (PrivateStateThreadIsValid ())
3898 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003899 else
3900 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003901 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003902 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003903 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003904 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003905}
3906
3907void
3908Process::ControlPrivateStateThread (uint32_t signal)
3909{
Greg Clayton5160ce52013-03-27 23:08:40 +00003910 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003911
3912 assert (signal == eBroadcastInternalStateControlStop ||
3913 signal == eBroadcastInternalStateControlPause ||
3914 signal == eBroadcastInternalStateControlResume);
3915
3916 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003917 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003918
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003919 // Signal the private state thread. First we should copy this is case the
3920 // thread starts exiting since the private state thread will NULL this out
3921 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00003922 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00003923 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003924 {
3925 TimeValue timeout_time;
3926 bool timed_out;
3927
3928 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3929
3930 timeout_time = TimeValue::Now();
3931 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003932 if (log)
3933 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003934 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3935 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3936
3937 if (signal == eBroadcastInternalStateControlStop)
3938 {
3939 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003940 {
Zachary Turner39de3112014-09-09 20:54:56 +00003941 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003942 if (log)
3943 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3944 }
3945 else
3946 {
3947 if (log)
3948 log->Printf ("The control event killed the private state thread without having to cancel.");
3949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003950
3951 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00003952 private_state_thread.Join(&result);
3953 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003954 }
3955 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003956 else
3957 {
3958 if (log)
3959 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3960 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003961}
3962
3963void
Jim Inghamcfc09352012-07-27 23:57:19 +00003964Process::SendAsyncInterrupt ()
3965{
3966 if (PrivateStateThreadIsValid())
3967 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3968 else
3969 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3970}
3971
3972void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003973Process::HandlePrivateEvent (EventSP &event_sp)
3974{
Greg Clayton5160ce52013-03-27 23:08:40 +00003975 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003976 m_resume_requested = false;
3977
Jim Inghamaacc3182012-06-06 00:29:30 +00003978 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003979
Greg Clayton414f5d32011-01-25 02:58:48 +00003980 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003981
3982 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003983 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003984 {
Jim Ingham754ab982011-01-29 04:05:41 +00003985 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003986 if (log)
3987 log->Printf ("Ran next event action, result was %d.", action_result);
3988
Jim Inghambb3a2832011-01-29 01:49:25 +00003989 switch (action_result)
3990 {
3991 case NextEventAction::eEventActionSuccess:
3992 SetNextEventAction(NULL);
3993 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003994
Jim Inghambb3a2832011-01-29 01:49:25 +00003995 case NextEventAction::eEventActionRetry:
3996 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003997
Jim Inghambb3a2832011-01-29 01:49:25 +00003998 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003999 // Handle Exiting Here. If we already got an exited event,
4000 // we should just propagate it. Otherwise, swallow this event,
4001 // and set our state to exit so the next event will kill us.
4002 if (new_state != eStateExited)
4003 {
4004 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004005 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004006 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004007 SetNextEventAction(NULL);
4008 return;
4009 }
4010 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004011 break;
4012 }
4013 }
4014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004015 // See if we should broadcast this state to external clients?
4016 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004017
4018 if (should_broadcast)
4019 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004020 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004021 if (log)
4022 {
Daniel Malead01b2952012-11-29 21:49:15 +00004023 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004024 __FUNCTION__,
4025 GetID(),
4026 StateAsCString(new_state),
4027 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004028 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004029 }
Jim Ingham9575d842011-03-11 03:53:59 +00004030 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004031 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004032 {
4033 // Only push the input handler if we aren't fowarding events,
4034 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004035 // Or don't push it if we are launching since it will come up stopped.
4036 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004037 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004038 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004039 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004040 else if (StateIsStoppedState(new_state, false))
4041 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004042 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004043 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4044 {
4045 // If the lldb_private::Debugger is handling the events, we don't
4046 // want to pop the process IOHandler here, we want to do it when
4047 // we receive the stopped event so we can carefully control when
4048 // the process IOHandler is popped because when we stop we want to
4049 // display some text stating how and why we stopped, then maybe some
4050 // process/thread/frame info, and then we want the "(lldb) " prompt
4051 // to show up. If we pop the process IOHandler here, then we will
4052 // cause the command interpreter to become the top IOHandler after
4053 // the process pops off and it will update its prompt right away...
4054 // See the Debugger.cpp file where it calls the function as
4055 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4056 // Otherwise we end up getting overlapping "(lldb) " prompts and
4057 // garbled output.
4058 //
4059 // If we aren't handling the events in the debugger (which is indicated
4060 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4061 // are hijacked, then we always pop the process IO handler manually.
4062 // Hijacking happens when the internal process state thread is running
4063 // thread plans, or when commands want to run in synchronous mode
4064 // and they call "process->WaitForProcessToStop()". An example of something
4065 // that will hijack the events is a simple expression:
4066 //
4067 // (lldb) expr (int)puts("hello")
4068 //
4069 // This will cause the internal process state thread to resume and halt
4070 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4071 // events) and we do need the IO handler to be pushed and popped
4072 // correctly.
4073
4074 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4075 PopProcessIOHandler ();
4076 }
4077 }
Jim Ingham9575d842011-03-11 03:53:59 +00004078
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004079 BroadcastEvent (event_sp);
4080 }
4081 else
4082 {
4083 if (log)
4084 {
Daniel Malead01b2952012-11-29 21:49:15 +00004085 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004086 __FUNCTION__,
4087 GetID(),
4088 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004089 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004090 }
4091 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004092 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004093}
4094
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004095thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096Process::PrivateStateThread (void *arg)
4097{
4098 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004099 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100 return result;
4101}
4102
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004103thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104Process::RunPrivateStateThread ()
4105{
Jim Ingham076b3042012-04-10 01:21:57 +00004106 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004107 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004108
Greg Clayton5160ce52013-03-27 23:08:40 +00004109 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004111 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4112 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004113
4114 bool exit_now = false;
4115 while (!exit_now)
4116 {
4117 EventSP event_sp;
4118 WaitForEventsPrivate (NULL, event_sp, control_only);
4119 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4120 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004121 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004122 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4123 __FUNCTION__, static_cast<void*>(this), GetID(),
4124 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004125
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004126 switch (event_sp->GetType())
4127 {
4128 case eBroadcastInternalStateControlStop:
4129 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004130 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131
4132 case eBroadcastInternalStateControlPause:
4133 control_only = true;
4134 break;
4135
4136 case eBroadcastInternalStateControlResume:
4137 control_only = false;
4138 break;
4139 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004140
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004141 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004142 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004143 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004144 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4145 {
4146 if (m_public_state.GetValue() == eStateAttaching)
4147 {
4148 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004149 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4150 __FUNCTION__, static_cast<void*>(this),
4151 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004152 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4153 }
4154 else
4155 {
4156 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004157 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4158 __FUNCTION__, static_cast<void*>(this),
4159 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004160 Halt();
4161 }
4162 continue;
4163 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004164
4165 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4166
4167 if (internal_state != eStateInvalid)
4168 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004169 if (m_clear_thread_plans_on_stop &&
4170 StateIsStoppedState(internal_state, true))
4171 {
4172 m_clear_thread_plans_on_stop = false;
4173 m_thread_list.DiscardThreadPlans();
4174 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004175 HandlePrivateEvent (event_sp);
4176 }
4177
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004178 if (internal_state == eStateInvalid ||
4179 internal_state == eStateExited ||
4180 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004181 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004182 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004183 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4184 __FUNCTION__, static_cast<void*>(this), GetID(),
4185 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004186
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004188 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004189 }
4190
Caroline Tice20ad3c42010-10-29 21:48:37 +00004191 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004192 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004193 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4194 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004195
Ed Maste64fad602013-07-29 20:58:06 +00004196 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004197 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004198 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004199 return NULL;
4200}
4201
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004202//------------------------------------------------------------------
4203// Process Event Data
4204//------------------------------------------------------------------
4205
4206Process::ProcessEventData::ProcessEventData () :
4207 EventData (),
4208 m_process_sp (),
4209 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004210 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004211 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004212 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213{
4214}
4215
4216Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4217 EventData (),
4218 m_process_sp (process_sp),
4219 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004220 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004221 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004222 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004223{
4224}
4225
4226Process::ProcessEventData::~ProcessEventData()
4227{
4228}
4229
4230const ConstString &
4231Process::ProcessEventData::GetFlavorString ()
4232{
4233 static ConstString g_flavor ("Process::ProcessEventData");
4234 return g_flavor;
4235}
4236
4237const ConstString &
4238Process::ProcessEventData::GetFlavor () const
4239{
4240 return ProcessEventData::GetFlavorString ();
4241}
4242
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004243void
4244Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4245{
4246 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004247 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4248 // the public event queue, then other times when we're pretending that this is where we stopped at the
4249 // end of expression evaluation. m_update_state is used to distinguish these
4250 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004251 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004252 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004253 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004254
Jim Ingham221d51c2013-05-08 00:35:16 +00004255 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004256
4257 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4258 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4259 // end up restarting the process.
4260 if (m_interrupted)
4261 return;
4262
4263 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004264 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004265 {
4266 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004267 uint32_t num_threads = curr_thread_list.GetSize();
4268 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004269
Jim Ingham4b536182011-08-09 02:12:22 +00004270 // The actions might change one of the thread's stop_info's opinions about whether we should
4271 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004272
4273 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4274 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4275 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4276 // 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
4277 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004278 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004279 for (idx = 0; idx < num_threads; ++idx)
4280 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4281
Jim Inghamc7078c22012-12-13 22:24:15 +00004282 // Use this to track whether we should continue from here. We will only continue the target running if
4283 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4284 // then it doesn't matter what the other threads say...
4285
4286 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004287
Jim Ingham0ad7e052013-04-25 02:04:59 +00004288 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4289 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4290 // thing to do is, and it's better to let the user decide than continue behind their backs.
4291
4292 bool does_anybody_have_an_opinion = false;
4293
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004294 for (idx = 0; idx < num_threads; ++idx)
4295 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004296 curr_thread_list = m_process_sp->GetThreadList();
4297 if (curr_thread_list.GetSize() != num_threads)
4298 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004299 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004300 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004301 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 +00004302 break;
4303 }
4304
4305 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4306
4307 if (thread_sp->GetIndexID() != thread_index_array[idx])
4308 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004309 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004310 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004311 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004312 idx,
4313 thread_index_array[idx],
4314 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004315 break;
4316 }
4317
Jim Inghamb15bfc72010-10-20 00:39:53 +00004318 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004319 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004320 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004321 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004322 bool this_thread_wants_to_stop;
4323 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004324 {
Jim Ingham0161b492013-02-09 01:29:05 +00004325 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4326 }
4327 else
4328 {
4329 stop_info_sp->PerformAction(event_ptr);
4330 // The stop action might restart the target. If it does, then we want to mark that in the
4331 // event so that whoever is receiving it will know to wait for the running event and reflect
4332 // that state appropriately.
4333 // We also need to stop processing actions, since they aren't expecting the target to be running.
4334
4335 // FIXME: we might have run.
4336 if (stop_info_sp->HasTargetRunSinceMe())
4337 {
4338 SetRestarted (true);
4339 break;
4340 }
4341
4342 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004343 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004344
Jim Inghamc7078c22012-12-13 22:24:15 +00004345 if (still_should_stop == false)
4346 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004347 }
4348 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004349
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004350
Jim Inghama8ca6e22013-05-03 23:04:37 +00004351 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004352 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004353 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004354 {
4355 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004356 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004357 // Use the public resume method here, since this is just
4358 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004359 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004360 }
4361 else
4362 {
4363 // If we didn't restart, run the Stop Hooks here:
4364 // They might also restart the target, so watch for that.
4365 m_process_sp->GetTarget().RunStopHooks();
4366 if (m_process_sp->GetPrivateState() == eStateRunning)
4367 SetRestarted(true);
4368 }
Jim Ingham9575d842011-03-11 03:53:59 +00004369 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004370 }
4371}
4372
4373void
4374Process::ProcessEventData::Dump (Stream *s) const
4375{
4376 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004377 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4378 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004379
Greg Clayton8b82f082011-04-12 05:54:46 +00004380 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004381}
4382
4383const Process::ProcessEventData *
4384Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4385{
4386 if (event_ptr)
4387 {
4388 const EventData *event_data = event_ptr->GetData();
4389 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4390 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4391 }
4392 return NULL;
4393}
4394
4395ProcessSP
4396Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4397{
4398 ProcessSP process_sp;
4399 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4400 if (data)
4401 process_sp = data->GetProcessSP();
4402 return process_sp;
4403}
4404
4405StateType
4406Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4407{
4408 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4409 if (data == NULL)
4410 return eStateInvalid;
4411 else
4412 return data->GetState();
4413}
4414
4415bool
4416Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4417{
4418 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4419 if (data == NULL)
4420 return false;
4421 else
4422 return data->GetRestarted();
4423}
4424
4425void
4426Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4427{
4428 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4429 if (data != NULL)
4430 data->SetRestarted(new_value);
4431}
4432
Jim Ingham0161b492013-02-09 01:29:05 +00004433size_t
4434Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4435{
4436 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4437 if (data != NULL)
4438 return data->GetNumRestartedReasons();
4439 else
4440 return 0;
4441}
4442
4443const char *
4444Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4445{
4446 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4447 if (data != NULL)
4448 return data->GetRestartedReasonAtIndex(idx);
4449 else
4450 return NULL;
4451}
4452
4453void
4454Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4455{
4456 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4457 if (data != NULL)
4458 data->AddRestartedReason(reason);
4459}
4460
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004461bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004462Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4463{
4464 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4465 if (data == NULL)
4466 return false;
4467 else
4468 return data->GetInterrupted ();
4469}
4470
4471void
4472Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4473{
4474 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4475 if (data != NULL)
4476 data->SetInterrupted(new_value);
4477}
4478
4479bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004480Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4481{
4482 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4483 if (data)
4484 {
4485 data->SetUpdateStateOnRemoval();
4486 return true;
4487 }
4488 return false;
4489}
4490
Greg Claytond9e416c2012-02-18 05:35:26 +00004491lldb::TargetSP
4492Process::CalculateTarget ()
4493{
4494 return m_target.shared_from_this();
4495}
4496
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004497void
Greg Clayton0603aa92010-10-04 01:05:56 +00004498Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004499{
Greg Claytonc14ee322011-09-22 04:58:26 +00004500 exe_ctx.SetTargetPtr (&m_target);
4501 exe_ctx.SetProcessPtr (this);
4502 exe_ctx.SetThreadPtr(NULL);
4503 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004504}
4505
Greg Claytone996fd32011-03-08 22:40:15 +00004506//uint32_t
4507//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4508//{
4509// return 0;
4510//}
4511//
4512//ArchSpec
4513//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4514//{
4515// return Host::GetArchSpecForExistingProcess (pid);
4516//}
4517//
4518//ArchSpec
4519//Process::GetArchSpecForExistingProcess (const char *process_name)
4520//{
4521// return Host::GetArchSpecForExistingProcess (process_name);
4522//}
4523//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004524void
4525Process::AppendSTDOUT (const char * s, size_t len)
4526{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004527 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004528 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004529 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004530}
4531
4532void
Greg Clayton93e86192011-11-13 04:45:22 +00004533Process::AppendSTDERR (const char * s, size_t len)
4534{
4535 Mutex::Locker locker (m_stdio_communication_mutex);
4536 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004537 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004538}
4539
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004540void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004541Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004542{
4543 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004544 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004545 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4546}
4547
4548size_t
4549Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4550{
4551 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004552 if (m_profile_data.empty())
4553 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004554
4555 std::string &one_profile_data = m_profile_data.front();
4556 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004557 if (bytes_available > 0)
4558 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004559 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004560 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004561 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4562 static_cast<void*>(buf),
4563 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004564 if (bytes_available > buf_size)
4565 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004566 memcpy(buf, one_profile_data.c_str(), buf_size);
4567 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004568 bytes_available = buf_size;
4569 }
4570 else
4571 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004572 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004573 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004574 }
4575 }
4576 return bytes_available;
4577}
4578
4579
Greg Clayton93e86192011-11-13 04:45:22 +00004580//------------------------------------------------------------------
4581// Process STDIO
4582//------------------------------------------------------------------
4583
4584size_t
4585Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4586{
4587 Mutex::Locker locker(m_stdio_communication_mutex);
4588 size_t bytes_available = m_stdout_data.size();
4589 if (bytes_available > 0)
4590 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004591 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004592 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004593 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4594 static_cast<void*>(buf),
4595 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004596 if (bytes_available > buf_size)
4597 {
4598 memcpy(buf, m_stdout_data.c_str(), buf_size);
4599 m_stdout_data.erase(0, buf_size);
4600 bytes_available = buf_size;
4601 }
4602 else
4603 {
4604 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4605 m_stdout_data.clear();
4606 }
4607 }
4608 return bytes_available;
4609}
4610
4611
4612size_t
4613Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4614{
4615 Mutex::Locker locker(m_stdio_communication_mutex);
4616 size_t bytes_available = m_stderr_data.size();
4617 if (bytes_available > 0)
4618 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004619 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004620 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004621 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4622 static_cast<void*>(buf),
4623 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004624 if (bytes_available > buf_size)
4625 {
4626 memcpy(buf, m_stderr_data.c_str(), buf_size);
4627 m_stderr_data.erase(0, buf_size);
4628 bytes_available = buf_size;
4629 }
4630 else
4631 {
4632 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4633 m_stderr_data.clear();
4634 }
4635 }
4636 return bytes_available;
4637}
4638
4639void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004640Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4641{
4642 Process *process = (Process *) baton;
4643 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4644}
4645
Greg Clayton44d93782014-01-27 23:43:24 +00004646class IOHandlerProcessSTDIO :
4647 public IOHandler
4648{
4649public:
4650 IOHandlerProcessSTDIO (Process *process,
4651 int write_fd) :
4652 IOHandler(process->GetTarget().GetDebugger()),
4653 m_process (process),
4654 m_read_file (),
4655 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004656 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004657 {
4658 m_read_file.SetDescriptor(GetInputFD(), false);
4659 }
4660
4661 virtual
4662 ~IOHandlerProcessSTDIO ()
4663 {
4664
4665 }
4666
4667 bool
4668 OpenPipes ()
4669 {
Greg Clayton100eb932014-07-02 21:10:39 +00004670 if (m_pipe.IsValid())
Greg Clayton44d93782014-01-27 23:43:24 +00004671 return true;
Greg Clayton100eb932014-07-02 21:10:39 +00004672 return m_pipe.Open();
Greg Clayton44d93782014-01-27 23:43:24 +00004673 }
4674
4675 void
4676 ClosePipes()
4677 {
Greg Clayton100eb932014-07-02 21:10:39 +00004678 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004679 }
4680
4681 // Each IOHandler gets to run until it is done. It should read data
4682 // from the "in" and place output into "out" and "err and return
4683 // when done.
4684 virtual void
4685 Run ()
4686 {
4687 if (m_read_file.IsValid() && m_write_file.IsValid())
4688 {
4689 SetIsDone(false);
4690 if (OpenPipes())
4691 {
4692 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004693 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004694 TerminalState terminal_state;
4695 terminal_state.Save (read_fd, false);
4696 Terminal terminal(read_fd);
4697 terminal.SetCanonical(false);
4698 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004699// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004700#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004701 while (!GetIsDone())
4702 {
4703 fd_set read_fdset;
4704 FD_ZERO (&read_fdset);
4705 FD_SET (read_fd, &read_fdset);
4706 FD_SET (pipe_read_fd, &read_fdset);
4707 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4708 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4709 if (num_set_fds < 0)
4710 {
4711 const int select_errno = errno;
4712
4713 if (select_errno != EINTR)
4714 SetIsDone(true);
4715 }
4716 else if (num_set_fds > 0)
4717 {
4718 char ch = 0;
4719 size_t n;
4720 if (FD_ISSET (read_fd, &read_fdset))
4721 {
4722 n = 1;
4723 if (m_read_file.Read(&ch, n).Success() && n == 1)
4724 {
4725 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4726 SetIsDone(true);
4727 }
4728 else
4729 SetIsDone(true);
4730 }
4731 if (FD_ISSET (pipe_read_fd, &read_fdset))
4732 {
4733 // Consume the interrupt byte
Greg Clayton100eb932014-07-02 21:10:39 +00004734 if (m_pipe.Read (&ch, 1) == 1)
Greg Clayton19e11352014-02-26 22:47:33 +00004735 {
Greg Clayton100eb932014-07-02 21:10:39 +00004736 switch (ch)
4737 {
4738 case 'q':
4739 SetIsDone(true);
4740 break;
4741 case 'i':
4742 if (StateIsRunningState(m_process->GetState()))
4743 m_process->Halt();
4744 break;
4745 }
Greg Clayton19e11352014-02-26 22:47:33 +00004746 }
Greg Clayton44d93782014-01-27 23:43:24 +00004747 }
4748 }
4749 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00004750#endif
Greg Clayton44d93782014-01-27 23:43:24 +00004751 terminal_state.Restore();
4752
4753 }
4754 else
4755 SetIsDone(true);
4756 }
4757 else
4758 SetIsDone(true);
4759 }
4760
4761 // Hide any characters that have been displayed so far so async
4762 // output can be displayed. Refresh() will be called after the
4763 // output has been displayed.
4764 virtual void
4765 Hide ()
4766 {
4767
4768 }
4769 // Called when the async output has been received in order to update
4770 // the input reader (refresh the prompt and redisplay any current
4771 // line(s) that are being edited
4772 virtual void
4773 Refresh ()
4774 {
4775
4776 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004777
Greg Clayton44d93782014-01-27 23:43:24 +00004778 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00004779 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00004780 {
Greg Clayton19e11352014-02-26 22:47:33 +00004781 char ch = 'q'; // Send 'q' for quit
Greg Clayton100eb932014-07-02 21:10:39 +00004782 m_pipe.Write (&ch, 1);
Greg Clayton44d93782014-01-27 23:43:24 +00004783 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004784
Greg Claytonf0066ad2014-05-02 00:45:31 +00004785 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00004786 Interrupt ()
4787 {
Greg Clayton19e11352014-02-26 22:47:33 +00004788 // Do only things that are safe to do in an interrupt context (like in
4789 // a SIGINT handler), like write 1 byte to a file descriptor. This will
4790 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4791 // that was written to the pipe and then call m_process->Halt() from a
4792 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004793 if (m_active)
4794 {
4795 char ch = 'i'; // Send 'i' for interrupt
4796 return m_pipe.Write (&ch, 1) == 1;
4797 }
4798 else
4799 {
4800 // This IOHandler might be pushed on the stack, but not being run currently
4801 // so do the right thing if we aren't actively watching for STDIN by sending
4802 // the interrupt to the process. Otherwise the write to the pipe above would
4803 // do nothing. This can happen when the command interpreter is running and
4804 // gets a "expression ...". It will be on the IOHandler thread and sending
4805 // the input is complete to the delegate which will cause the expression to
4806 // run, which will push the process IO handler, but not run it.
4807
4808 if (StateIsRunningState(m_process->GetState()))
4809 {
4810 m_process->SendAsyncInterrupt();
4811 return true;
4812 }
4813 }
4814 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00004815 }
Greg Clayton44d93782014-01-27 23:43:24 +00004816
4817 virtual void
4818 GotEOF()
4819 {
4820
4821 }
4822
4823protected:
4824 Process *m_process;
4825 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4826 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00004827 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00004828};
4829
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004830void
Greg Clayton44d93782014-01-27 23:43:24 +00004831Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004832{
4833 // First set up the Read Thread for reading/handling process I/O
4834
Greg Clayton44d93782014-01-27 23:43:24 +00004835 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004836
4837 if (conn_ap.get())
4838 {
4839 m_stdio_communication.SetConnection (conn_ap.release());
4840 if (m_stdio_communication.IsConnected())
4841 {
4842 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4843 m_stdio_communication.StartReadThread();
4844
4845 // Now read thread is set up, set up input reader.
4846
4847 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00004848 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004849 }
4850 }
4851}
4852
Greg Claytonb4874f12014-02-28 18:22:24 +00004853bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00004854Process::ProcessIOHandlerIsActive ()
4855{
4856 IOHandlerSP io_handler_sp (m_process_input_reader);
4857 if (io_handler_sp)
4858 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
4859 return false;
4860}
4861bool
Greg Clayton44d93782014-01-27 23:43:24 +00004862Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004863{
Greg Clayton44d93782014-01-27 23:43:24 +00004864 IOHandlerSP io_handler_sp (m_process_input_reader);
4865 if (io_handler_sp)
4866 {
4867 io_handler_sp->SetIsDone(false);
4868 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00004869 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00004870 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004871 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004872}
4873
Greg Claytonb4874f12014-02-28 18:22:24 +00004874bool
Greg Clayton44d93782014-01-27 23:43:24 +00004875Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004876{
Greg Clayton44d93782014-01-27 23:43:24 +00004877 IOHandlerSP io_handler_sp (m_process_input_reader);
4878 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00004879 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
4880 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004881}
4882
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004883// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004884void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004885Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004886{
Greg Clayton6920b522012-08-22 18:39:03 +00004887 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004888}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004889
Greg Clayton99d0faf2010-11-18 23:32:35 +00004890void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004891Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004892{
Greg Clayton6920b522012-08-22 18:39:03 +00004893 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004894}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004895
Jim Ingham1624a2d2014-05-05 02:26:40 +00004896ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004897Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004898 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004899 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004900 Stream &errors)
4901{
Jim Ingham8646d3c2014-05-05 02:47:44 +00004902 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004903
Jim Ingham77787032011-01-20 02:03:18 +00004904 if (thread_plan_sp.get() == NULL)
4905 {
4906 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004907 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004908 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004909
Jim Ingham7d7931d2013-03-28 00:05:34 +00004910 if (!thread_plan_sp->ValidatePlan(NULL))
4911 {
4912 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004913 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00004914 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004915
Greg Claytonc14ee322011-09-22 04:58:26 +00004916 if (exe_ctx.GetProcessPtr() != this)
4917 {
4918 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004919 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004920 }
4921
4922 Thread *thread = exe_ctx.GetThreadPtr();
4923 if (thread == NULL)
4924 {
4925 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004926 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00004927 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004928
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004929 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4930 // For that to be true the plan can't be private - since private plans suppress themselves in the
4931 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004932
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004933 bool orig_plan_private = thread_plan_sp->GetPrivate();
4934 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004935
Jim Ingham444586b2011-01-24 06:34:17 +00004936 if (m_private_state.GetValue() != eStateStopped)
4937 {
4938 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00004939 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004940 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004941
Jim Ingham66243842011-08-13 00:56:10 +00004942 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004943 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004944 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004945 if (!selected_frame_sp)
4946 {
4947 thread->SetSelectedFrame(0);
4948 selected_frame_sp = thread->GetSelectedFrame();
4949 if (!selected_frame_sp)
4950 {
4951 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00004952 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00004953 }
4954 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004955
Jim Ingham11b0e052013-02-19 23:22:45 +00004956 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004957
4958 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4959 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004960
Greg Claytonc14ee322011-09-22 04:58:26 +00004961 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004962
Jim Ingham66243842011-08-13 00:56:10 +00004963 uint32_t selected_tid;
4964 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004965 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004966 {
4967 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004968 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004969 }
4970 else
4971 {
4972 selected_tid = LLDB_INVALID_THREAD_ID;
4973 }
4974
Zachary Turner39de3112014-09-09 20:54:56 +00004975 HostThread backup_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004976 lldb::StateType old_state;
4977 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004978
Greg Clayton5160ce52013-03-27 23:08:40 +00004979 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00004980 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00004981 {
Jim Ingham076b3042012-04-10 01:21:57 +00004982 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4983 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004984 // 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 +00004985 // we are fielding public events here.
4986 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004987 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 +00004988
Jim Ingham372787f2012-04-07 00:00:41 +00004989 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004990
4991 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4992 // returning control here.
4993 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4994 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4995 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4996 // do just what we want.
4997 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4998 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4999 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5000 old_state = m_public_state.GetValue();
5001 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005002
Jim Ingham076b3042012-04-10 01:21:57 +00005003 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005004 StartPrivateStateThread(true);
5005 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005006
Jim Ingham372787f2012-04-07 00:00:41 +00005007 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005008
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005009 if (options.GetDebug())
5010 {
5011 // In this case, we aren't actually going to run, we just want to stop right away.
5012 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5013 // FIXME: To make this prettier we should invent some stop reason for this, but that
5014 // is only cosmetic, and this functionality is only of use to lldb developers who can
5015 // live with not pretty...
5016 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005017 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005018 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005019
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005020 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005021
Sean Callanana46ec452012-07-11 21:31:24 +00005022 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005023
Jim Ingham77787032011-01-20 02:03:18 +00005024 {
Sean Callanana46ec452012-07-11 21:31:24 +00005025 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5026 // restored on exit to the function.
5027 //
5028 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5029 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005030
Sean Callanana46ec452012-07-11 21:31:24 +00005031 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005032
Jim Inghamf48169b2010-11-30 02:22:11 +00005033 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005034 {
5035 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005036 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005037 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005038 thread->GetIndexID(),
5039 thread->GetID(),
5040 s.GetData());
5041 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005042
Sean Callanana46ec452012-07-11 21:31:24 +00005043 bool got_event;
5044 lldb::EventSP event_sp;
5045 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005046
Sean Callanana46ec452012-07-11 21:31:24 +00005047 TimeValue* timeout_ptr = NULL;
5048 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005049
Jim Ingham0161b492013-02-09 01:29:05 +00005050 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 +00005051 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005052 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005053 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005054
Jim Ingham0161b492013-02-09 01:29:05 +00005055 // This is just for accounting:
5056 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005057
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005058 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005059 uint32_t one_thread_timeout_usec;
5060 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005061
5062 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5063 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5064 // first timeout already.
5065
5066 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005067 {
5068 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005069 one_thread_timeout_usec = 0;
5070 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005071 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005072 else
Jim Ingham0161b492013-02-09 01:29:05 +00005073 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005074 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005075
Jim Ingham914f4e72014-03-28 21:58:28 +00005076 // If the overall wait is forever, then we only need to set the one thread timeout:
5077 if (timeout_usec == 0)
5078 {
Ed Maste801335c2014-03-31 19:28:14 +00005079 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005080 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005081 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005082 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005083 }
Jim Ingham0161b492013-02-09 01:29:05 +00005084 else
5085 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005086 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5087 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5088 uint64_t computed_one_thread_timeout;
5089 if (option_one_thread_timeout != 0)
5090 {
5091 if (timeout_usec < option_one_thread_timeout)
5092 {
5093 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005094 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005095 }
5096 computed_one_thread_timeout = option_one_thread_timeout;
5097 }
5098 else
5099 {
5100 computed_one_thread_timeout = timeout_usec / 2;
5101 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5102 computed_one_thread_timeout = default_one_thread_timeout_usec;
5103 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005104 one_thread_timeout_usec = computed_one_thread_timeout;
5105 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5106
Jim Ingham0161b492013-02-09 01:29:05 +00005107 }
Jim Ingham0161b492013-02-09 01:29:05 +00005108 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005109
5110 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005111 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 +00005112 options.GetStopOthers(),
5113 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005114 before_first_timeout,
5115 one_thread_timeout_usec,
5116 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005117
Jim Ingham1460e4b2014-01-10 23:46:59 +00005118 // This isn't going to work if there are unfetched events on the queue.
5119 // Are there cases where we might want to run the remaining events here, and then try to
5120 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005121
Jim Ingham1460e4b2014-01-10 23:46:59 +00005122 Event *other_events = listener.PeekAtNextEvent();
5123 if (other_events != NULL)
5124 {
5125 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005126 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005127 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005128
Jim Ingham1460e4b2014-01-10 23:46:59 +00005129 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5130 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5131 // event coalescing to cause us to lose OUR running event...
5132 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005133
Jim Ingham8559a352012-11-26 23:52:18 +00005134 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5135 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005136
5137#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5138 // It's pretty much impossible to write test cases for things like:
5139 // One thread timeout expires, I go to halt, but the process already stopped
5140 // on the function call stop breakpoint. Turning on this define will make us not
5141 // fetch the first event till after the halt. So if you run a quick function, it will have
5142 // completed, and the completion event will be waiting, when you interrupt for halt.
5143 // The expression evaluation should still succeed.
5144 bool miss_first_event = true;
5145#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005146 TimeValue one_thread_timeout;
5147 TimeValue final_timeout;
5148
Jim Ingham35878c42014-04-08 21:33:21 +00005149
Sean Callanana46ec452012-07-11 21:31:24 +00005150 while (1)
5151 {
5152 // We usually want to resume the process if we get to the top of the loop.
5153 // The only exception is if we get two running events with no intervening
5154 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005155 if (log)
5156 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5157 do_resume,
5158 handle_running_event,
5159 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005160
Jim Ingham184e9812013-01-15 02:47:48 +00005161 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005162 {
5163 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005164
Jim Ingham184e9812013-01-15 02:47:48 +00005165 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005166 {
Jim Ingham0161b492013-02-09 01:29:05 +00005167 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005168 Error resume_error = PrivateResume ();
5169 if (!resume_error.Success())
5170 {
Jim Ingham0161b492013-02-09 01:29:05 +00005171 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5172 num_resumes,
5173 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005174 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005175 break;
5176 }
Sean Callanana46ec452012-07-11 21:31:24 +00005177 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005178
Jim Ingham0161b492013-02-09 01:29:05 +00005179 TimeValue resume_timeout = TimeValue::Now();
5180 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005181
Jim Ingham0161b492013-02-09 01:29:05 +00005182 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005183 if (!got_event)
5184 {
5185 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005186 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5187 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005188
Jim Ingham0161b492013-02-09 01:29:05 +00005189 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005190 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005191 break;
5192 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005193
Sean Callanana46ec452012-07-11 21:31:24 +00005194 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005195
Sean Callanana46ec452012-07-11 21:31:24 +00005196 if (stop_state != eStateRunning)
5197 {
Jim Ingham0161b492013-02-09 01:29:05 +00005198 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005199
Jim Ingham0161b492013-02-09 01:29:05 +00005200 if (stop_state == eStateStopped)
5201 {
5202 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5203 if (log)
5204 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5205 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5206 num_resumes,
5207 StateAsCString(stop_state),
5208 restarted,
5209 do_resume,
5210 handle_running_event);
5211 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005212
Jim Ingham0161b492013-02-09 01:29:05 +00005213 if (restarted)
5214 {
5215 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5216 // event here. But if I do, the best thing is to Halt and then get out of here.
5217 Halt();
5218 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005219
Jim Ingham35e1bda2012-10-16 21:41:58 +00005220 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5221 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005222 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005223 break;
5224 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005225
Sean Callanana46ec452012-07-11 21:31:24 +00005226 if (log)
5227 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5228 // We need to call the function synchronously, so spin waiting for it to return.
5229 // If we get interrupted while executing, we're going to lose our context, and
5230 // won't be able to gather the result at this point.
5231 // We set the timeout AFTER the resume, since the resume takes some time and we
5232 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005233 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005234 else
5235 {
Sean Callanana46ec452012-07-11 21:31:24 +00005236 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005237 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005238 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005239
Jim Ingham0161b492013-02-09 01:29:05 +00005240 if (before_first_timeout)
5241 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005242 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005243 {
5244 one_thread_timeout = TimeValue::Now();
5245 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005246 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005247 }
Jim Ingham0161b492013-02-09 01:29:05 +00005248 else
5249 {
5250 if (timeout_usec == 0)
5251 timeout_ptr = NULL;
5252 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005253 {
5254 final_timeout = TimeValue::Now();
5255 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005256 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005257 }
Jim Ingham0161b492013-02-09 01:29:05 +00005258 }
5259 }
5260 else
5261 {
5262 if (timeout_usec == 0)
5263 timeout_ptr = NULL;
5264 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005265 {
5266 final_timeout = TimeValue::Now();
5267 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005268 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005269 }
Jim Ingham0161b492013-02-09 01:29:05 +00005270 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005271
Jim Ingham0161b492013-02-09 01:29:05 +00005272 do_resume = true;
5273 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005274
Sean Callanana46ec452012-07-11 21:31:24 +00005275 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005276 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005277
Jim Ingham0f16e732011-02-08 05:20:59 +00005278 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005279 {
Sean Callanana46ec452012-07-11 21:31:24 +00005280 if (timeout_ptr)
5281 {
Matt Kopec676a4872013-02-21 23:55:31 +00005282 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005283 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5284 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005285 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005286 else
Sean Callanana46ec452012-07-11 21:31:24 +00005287 {
5288 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5289 }
5290 }
Jim Ingham35878c42014-04-08 21:33:21 +00005291
5292#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5293 // See comment above...
5294 if (miss_first_event)
5295 {
5296 usleep(1000);
5297 miss_first_event = false;
5298 got_event = false;
5299 }
5300 else
5301#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005302 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005303
Sean Callanana46ec452012-07-11 21:31:24 +00005304 if (got_event)
5305 {
5306 if (event_sp.get())
5307 {
5308 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005309 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005310 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005311 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005312 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005313 errors.Printf ("Execution halted by user interrupt.");
5314 if (log)
5315 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005316 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005317 }
5318 else
5319 {
5320 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5321 if (log)
5322 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005323
Jim Inghamcfc09352012-07-27 23:57:19 +00005324 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005325 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005326 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005327 {
Jim Ingham0161b492013-02-09 01:29:05 +00005328 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005329 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5330 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005331 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005332 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005333 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005334 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005335 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005336 }
5337 else
5338 {
Jim Ingham0161b492013-02-09 01:29:05 +00005339 // If we were restarted, we just need to go back up to fetch another event.
5340 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005341 {
5342 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005343 {
5344 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5345 }
5346 keep_going = true;
5347 do_resume = false;
5348 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005349
Jim Inghamcfc09352012-07-27 23:57:19 +00005350 }
5351 else
5352 {
Jim Ingham0161b492013-02-09 01:29:05 +00005353 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5354 StopReason stop_reason = eStopReasonInvalid;
5355 if (stop_info_sp)
5356 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005357
Jim Ingham0161b492013-02-09 01:29:05 +00005358 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5359 // it is OUR plan that is complete?
5360 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005361 {
5362 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005363 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5364 // Now mark this plan as private so it doesn't get reported as the stop reason
5365 // after this point.
5366 if (thread_plan_sp)
5367 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005368 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005369 }
5370 else
5371 {
Jim Ingham0161b492013-02-09 01:29:05 +00005372 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005373 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005374 {
5375 if (log)
5376 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005377 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005378 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005379 {
5380 event_to_broadcast_sp = event_sp;
5381 }
Jim Ingham0161b492013-02-09 01:29:05 +00005382 }
Jim Ingham184e9812013-01-15 02:47:48 +00005383 else
Jim Ingham0161b492013-02-09 01:29:05 +00005384 {
5385 if (log)
5386 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005387 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005388 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005389 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005390 }
Jim Ingham184e9812013-01-15 02:47:48 +00005391 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005392 }
Sean Callanana46ec452012-07-11 21:31:24 +00005393 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005394 }
5395 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005396
Jim Inghamcfc09352012-07-27 23:57:19 +00005397 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005398 // This shouldn't really happen, but sometimes we do get two running events without an
5399 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005400 do_resume = false;
5401 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005402 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005403 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005404
Jim Inghamcfc09352012-07-27 23:57:19 +00005405 default:
5406 if (log)
5407 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005408
Jim Inghamcfc09352012-07-27 23:57:19 +00005409 if (stop_state == eStateExited)
5410 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005411
Sean Callananbf154da2012-08-08 17:35:10 +00005412 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005413 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005414 break;
5415 }
Sean Callanana46ec452012-07-11 21:31:24 +00005416 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005417
Sean Callanana46ec452012-07-11 21:31:24 +00005418 if (keep_going)
5419 continue;
5420 else
5421 break;
5422 }
5423 else
5424 {
5425 if (log)
5426 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005427 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005428 break;
5429 }
5430 }
5431 else
5432 {
5433 // If we didn't get an event that means we've timed out...
5434 // We will interrupt the process here. Depending on what we were asked to do we will
5435 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005436
Sean Callanana46ec452012-07-11 21:31:24 +00005437 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005438 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005439 {
Jim Ingham0161b492013-02-09 01:29:05 +00005440 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005441 {
5442 if (timeout_usec != 0)
5443 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005444 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005445 "running for %" PRIu32 " usec with all threads enabled.",
5446 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005447 }
5448 else
5449 {
5450 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005451 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005452 }
5453 }
Sean Callanana46ec452012-07-11 21:31:24 +00005454 else
5455 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005456 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005457 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005458 }
5459 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005460 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005461 "abandoning execution.",
5462 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005463 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005464
Jim Ingham0161b492013-02-09 01:29:05 +00005465 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5466 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5467 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5468 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5469 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005470
Jim Ingham0161b492013-02-09 01:29:05 +00005471 bool back_to_top = true;
5472 uint32_t try_halt_again = 0;
5473 bool do_halt = true;
5474 const uint32_t num_retries = 5;
5475 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005476 {
Jim Ingham0161b492013-02-09 01:29:05 +00005477 Error halt_error;
5478 if (do_halt)
5479 {
5480 if (log)
5481 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5482 halt_error = Halt();
5483 }
5484 if (halt_error.Success())
5485 {
5486 if (log)
5487 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005488
Jim Ingham0161b492013-02-09 01:29:05 +00005489 real_timeout = TimeValue::Now();
5490 real_timeout.OffsetWithMicroSeconds(500000);
5491
5492 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005493
Jim Ingham0161b492013-02-09 01:29:05 +00005494 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005495 {
Jim Ingham0161b492013-02-09 01:29:05 +00005496 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5497 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005498 {
Jim Ingham0161b492013-02-09 01:29:05 +00005499 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5500 if (stop_state == lldb::eStateStopped
5501 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5502 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005503 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005504
Jim Ingham0161b492013-02-09 01:29:05 +00005505 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005506 {
Jim Ingham0161b492013-02-09 01:29:05 +00005507 // Between the time we initiated the Halt and the time we delivered it, the process could have
5508 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005509
Jim Ingham0161b492013-02-09 01:29:05 +00005510 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5511 {
5512 if (log)
5513 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5514 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005515 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005516 back_to_top = false;
5517 break;
5518 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005519
Jim Ingham0161b492013-02-09 01:29:05 +00005520 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5521 {
5522 if (log)
5523 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5524 "Exiting wait loop.");
5525 try_halt_again++;
5526 do_halt = false;
5527 continue;
5528 }
Sean Callanana46ec452012-07-11 21:31:24 +00005529
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005530 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005531 {
5532 if (log)
5533 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005534 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005535 back_to_top = false;
5536 break;
5537 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005538
Jim Ingham0161b492013-02-09 01:29:05 +00005539 if (before_first_timeout)
5540 {
5541 // Set all the other threads to run, and return to the top of the loop, which will continue;
5542 before_first_timeout = false;
5543 thread_plan_sp->SetStopOthers (false);
5544 if (log)
5545 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005546
Jim Ingham0161b492013-02-09 01:29:05 +00005547 back_to_top = true;
5548 break;
5549 }
5550 else
5551 {
5552 // Running all threads failed, so return Interrupted.
5553 if (log)
5554 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005555 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005556 back_to_top = false;
5557 break;
5558 }
Sean Callanana46ec452012-07-11 21:31:24 +00005559 }
5560 }
5561 else
Jim Ingham0161b492013-02-09 01:29:05 +00005562 { if (log)
5563 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5564 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005565 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005566 back_to_top = false;
5567 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005568 }
5569 }
Jim Ingham0161b492013-02-09 01:29:05 +00005570 else
5571 {
5572 try_halt_again++;
5573 continue;
5574 }
Sean Callanana46ec452012-07-11 21:31:24 +00005575 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005576
Jim Ingham0161b492013-02-09 01:29:05 +00005577 if (!back_to_top || try_halt_again > num_retries)
5578 break;
5579 else
5580 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005581 }
Sean Callanana46ec452012-07-11 21:31:24 +00005582 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005583
Sean Callanana46ec452012-07-11 21:31:24 +00005584 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
Zachary Turneracee96a2014-09-23 18:32:09 +00005585 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005586 {
5587 StopPrivateStateThread();
5588 Error error;
5589 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005590 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005591 {
5592 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5593 }
5594 m_public_state.SetValueNoLock(old_state);
5595
5596 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005597
Jim Ingham184e9812013-01-15 02:47:48 +00005598 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5599 // could happen:
5600 // 1) The execution successfully completed
5601 // 2) We hit a breakpoint, and ignore_breakpoints was true
5602 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005603 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5604 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005605
Jim Ingham8646d3c2014-05-05 02:47:44 +00005606 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005607 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005608 {
5609 thread_plan_sp->RestoreThreadState();
5610 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005611
Sean Callanana46ec452012-07-11 21:31:24 +00005612 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005613 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005614 {
5615 if (log)
5616 {
5617 StreamString s;
5618 if (event_sp)
5619 event_sp->Dump (&s);
5620 else
5621 {
5622 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5623 }
5624
5625 StreamString ts;
5626
5627 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005628
Sean Callanana46ec452012-07-11 21:31:24 +00005629 do
5630 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005631 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005632 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005633 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005634 break;
5635 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005636 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005637 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005638 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005639 break;
5640 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005641 else
Sean Callanana46ec452012-07-11 21:31:24 +00005642 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005643 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5644
5645 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005646 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005647 event_explanation = "<no event data>";
5648 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005649 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005650
Jim Inghamcfc09352012-07-27 23:57:19 +00005651 Process *process = event_data->GetProcessSP().get();
5652
5653 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005654 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005655 event_explanation = "<no process>";
5656 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005657 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005658
Jim Inghamcfc09352012-07-27 23:57:19 +00005659 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005660
Jim Inghamcfc09352012-07-27 23:57:19 +00005661 uint32_t num_threads = thread_list.GetSize();
5662 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005663
Jim Inghamcfc09352012-07-27 23:57:19 +00005664 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005665
Jim Inghamcfc09352012-07-27 23:57:19 +00005666 for (thread_index = 0;
5667 thread_index < num_threads;
5668 ++thread_index)
5669 {
5670 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005671
Jim Inghamcfc09352012-07-27 23:57:19 +00005672 if (!thread)
5673 {
5674 ts.Printf("<?> ");
5675 continue;
5676 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005677
Daniel Malead01b2952012-11-29 21:49:15 +00005678 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005679 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005680
Jim Inghamcfc09352012-07-27 23:57:19 +00005681 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005682 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005683 else
5684 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005685
Jim Inghamcfc09352012-07-27 23:57:19 +00005686 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5687 if (stop_info_sp)
5688 {
5689 const char *stop_desc = stop_info_sp->GetDescription();
5690 if (stop_desc)
5691 ts.PutCString (stop_desc);
5692 }
5693 ts.Printf(">");
5694 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005695
Jim Inghamcfc09352012-07-27 23:57:19 +00005696 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005697 }
Sean Callanana46ec452012-07-11 21:31:24 +00005698 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005699
Jim Inghamcfc09352012-07-27 23:57:19 +00005700 if (event_explanation)
5701 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005702 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005703 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5704 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005705
Jim Inghame4483cf2013-09-27 01:13:01 +00005706 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005707 {
5708 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005709 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5710 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00005711 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5712 thread_plan_sp->SetPrivate (orig_plan_private);
5713 }
5714 else
5715 {
5716 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005717 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
5718 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00005719 }
5720 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00005721 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00005722 {
5723 if (log)
5724 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005725
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005726 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005727 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005728 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005729 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005730 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005731 }
5732 else
5733 {
Sean Callanana46ec452012-07-11 21:31:24 +00005734 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005735 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005736 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005737 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005738 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00005739 }
5740 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5741 {
5742 if (log)
5743 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005744 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00005745 }
5746 else
5747 {
5748 if (log)
5749 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005750 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005751 {
5752 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005753 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005754 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5755 thread_plan_sp->SetPrivate (orig_plan_private);
5756 }
5757 }
5758 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005759
Sean Callanana46ec452012-07-11 21:31:24 +00005760 // Thread we ran the function in may have gone away because we ran the target
5761 // Check that it's still there, and if it is put it back in the context. Also restore the
5762 // frame in the context if it is still present.
5763 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5764 if (thread)
5765 {
5766 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5767 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005768
Sean Callanana46ec452012-07-11 21:31:24 +00005769 // Also restore the current process'es selected frame & thread, since this function calling may
5770 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005771
Sean Callanana46ec452012-07-11 21:31:24 +00005772 if (selected_tid != LLDB_INVALID_THREAD_ID)
5773 {
5774 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5775 {
5776 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005777 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005778 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005779 if (old_frame_sp)
5780 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005781 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005782 }
5783 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005784
Sean Callanana46ec452012-07-11 21:31:24 +00005785 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005786
Sean Callanana46ec452012-07-11 21:31:24 +00005787 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005788 {
Sean Callanana46ec452012-07-11 21:31:24 +00005789 if (log)
5790 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5791 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005792 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005793
Jim Inghamf48169b2010-11-30 02:22:11 +00005794 return return_value;
5795}
5796
5797const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00005798Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00005799{
5800 const char *result_name;
5801
5802 switch (result)
5803 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00005804 case eExpressionCompleted:
5805 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005806 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005807 case eExpressionDiscarded:
5808 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00005809 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005810 case eExpressionInterrupted:
5811 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00005812 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005813 case eExpressionHitBreakpoint:
5814 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00005815 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005816 case eExpressionSetupError:
5817 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00005818 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005819 case eExpressionParseError:
5820 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005821 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005822 case eExpressionResultUnavailable:
5823 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00005824 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005825 case eExpressionTimedOut:
5826 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00005827 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005828 case eExpressionStoppedForDebug:
5829 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005830 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005831 }
5832 return result_name;
5833}
5834
Greg Clayton7260f622011-04-18 08:33:37 +00005835void
5836Process::GetStatus (Stream &strm)
5837{
5838 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005839 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005840 {
5841 if (state == eStateExited)
5842 {
5843 int exit_status = GetExitStatus();
5844 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005845 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005846 GetID(),
5847 exit_status,
5848 exit_status,
5849 exit_description ? exit_description : "");
5850 }
5851 else
5852 {
5853 if (state == eStateConnected)
5854 strm.Printf ("Connected to remote target.\n");
5855 else
Daniel Malead01b2952012-11-29 21:49:15 +00005856 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005857 }
5858 }
5859 else
5860 {
Daniel Malead01b2952012-11-29 21:49:15 +00005861 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005862 }
5863}
5864
5865size_t
5866Process::GetThreadStatus (Stream &strm,
5867 bool only_threads_with_stop_reason,
5868 uint32_t start_frame,
5869 uint32_t num_frames,
5870 uint32_t num_frames_with_source)
5871{
5872 size_t num_thread_infos_dumped = 0;
5873
Jim Ingham4a65fb12014-03-07 11:20:03 +00005874 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
5875 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
5876 // ID's, and look them up one by one:
5877
5878 uint32_t num_threads;
5879 std::vector<uint32_t> thread_index_array;
5880 //Scope for thread list locker;
5881 {
5882 Mutex::Locker locker (GetThreadList().GetMutex());
5883 ThreadList &curr_thread_list = GetThreadList();
5884 num_threads = curr_thread_list.GetSize();
5885 uint32_t idx;
5886 thread_index_array.resize(num_threads);
5887 for (idx = 0; idx < num_threads; ++idx)
5888 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5889 }
5890
Greg Clayton7260f622011-04-18 08:33:37 +00005891 for (uint32_t i = 0; i < num_threads; i++)
5892 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005893 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_index_array[i]));
5894 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00005895 {
5896 if (only_threads_with_stop_reason)
5897 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00005898 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00005899 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005900 continue;
5901 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005902 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00005903 start_frame,
5904 num_frames,
5905 num_frames_with_source);
5906 ++num_thread_infos_dumped;
5907 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00005908 else
5909 {
5910 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
5911 if (log)
5912 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
5913
5914 }
Greg Clayton7260f622011-04-18 08:33:37 +00005915 }
5916 return num_thread_infos_dumped;
5917}
5918
Greg Claytona9f40ad2012-02-22 04:37:26 +00005919void
5920Process::AddInvalidMemoryRegion (const LoadRange &region)
5921{
5922 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5923}
5924
5925bool
5926Process::RemoveInvalidMemoryRange (const LoadRange &region)
5927{
5928 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5929}
5930
Jim Ingham372787f2012-04-07 00:00:41 +00005931void
5932Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5933{
5934 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5935}
5936
5937bool
5938Process::RunPreResumeActions ()
5939{
5940 bool result = true;
5941 while (!m_pre_resume_actions.empty())
5942 {
5943 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5944 m_pre_resume_actions.pop_back();
5945 bool this_result = action.callback (action.baton);
5946 if (result == true) result = this_result;
5947 }
5948 return result;
5949}
5950
5951void
5952Process::ClearPreResumeActions ()
5953{
5954 m_pre_resume_actions.clear();
5955}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005956
Greg Claytonfa559e52012-05-18 02:38:05 +00005957void
5958Process::Flush ()
5959{
5960 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005961 m_extended_thread_list.Flush();
5962 m_extended_thread_stop_id = 0;
5963 m_queue_list.Clear();
5964 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005965}
Greg Clayton90ba8112012-12-05 00:16:59 +00005966
5967void
5968Process::DidExec ()
5969{
Todd Fiala76e0fc92014-08-27 22:58:26 +00005970 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5971 if (log)
5972 log->Printf ("Process::%s()", __FUNCTION__);
5973
Greg Clayton90ba8112012-12-05 00:16:59 +00005974 Target &target = GetTarget();
5975 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005976 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005977 m_dynamic_checkers_ap.reset();
5978 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005979 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005980 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005981 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00005982 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005983 m_image_tokens.clear();
5984 m_allocated_memory_cache.Clear();
5985 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005986 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005987 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005988 DoDidExec();
5989 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005990 // Flush the process (threads and all stack frames) after running CompleteAttach()
5991 // in case the dynamic loader loaded things in new locations.
5992 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005993
5994 // After we figure out what was loaded/unloaded in CompleteAttach,
5995 // we need to let the target know so it can do any cleanup it needs to.
5996 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005997}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005998
Jim Ingham1460e4b2014-01-10 23:46:59 +00005999addr_t
6000Process::ResolveIndirectFunction(const Address *address, Error &error)
6001{
6002 if (address == nullptr)
6003 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006004 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006005 return LLDB_INVALID_ADDRESS;
6006 }
6007
6008 addr_t function_addr = LLDB_INVALID_ADDRESS;
6009
6010 addr_t addr = address->GetLoadAddress(&GetTarget());
6011 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6012 if (iter != m_resolved_indirect_addresses.end())
6013 {
6014 function_addr = (*iter).second;
6015 }
6016 else
6017 {
6018 if (!InferiorCall(this, address, function_addr))
6019 {
6020 Symbol *symbol = address->CalculateSymbolContextSymbol();
6021 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6022 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6023 function_addr = LLDB_INVALID_ADDRESS;
6024 }
6025 else
6026 {
6027 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6028 }
6029 }
6030 return function_addr;
6031}
6032
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006033void
6034Process::ModulesDidLoad (ModuleList &module_list)
6035{
6036 SystemRuntime *sys_runtime = GetSystemRuntime();
6037 if (sys_runtime)
6038 {
6039 sys_runtime->ModulesDidLoad (module_list);
6040 }
6041
6042 GetJITLoaders().ModulesDidLoad (module_list);
6043}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006044
6045ThreadCollectionSP
6046Process::GetHistoryThreads(lldb::addr_t addr)
6047{
6048 ThreadCollectionSP threads;
6049
6050 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6051
6052 if (! memory_history.get()) {
6053 return threads;
6054 }
6055
6056 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6057
6058 return threads;
6059}