blob: d43ce743da9d73b91da6e6ac84aaabbddd22589b [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"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013#include "lldb/Breakpoint/StoppointCallbackContext.h"
14#include "lldb/Breakpoint/BreakpointLocation.h"
15#include "lldb/Core/Event.h"
16#include "lldb/Core/Debugger.h"
17#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000018#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000019#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/PluginManager.h"
21#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000022#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000024#include "lldb/Expression/IRDynamicChecks.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000025#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000027#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000028#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000029#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000030#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000031#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000032#include "lldb/Interpreter/OptionValueProperties.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000033#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"
Zachary Turner93749ab2015-03-03 21:51:25 +000036#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000037#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000039#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000040#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000041#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000042#include "lldb/Target/LanguageRuntime.h"
43#include "lldb/Target/CPPLanguageRuntime.h"
44#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000045#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000047#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000048#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Target/Target.h"
50#include "lldb/Target/TargetList.h"
51#include "lldb/Target/Thread.h"
52#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000053#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000054#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000055#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000056#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057
58using namespace lldb;
59using namespace lldb_private;
60
Greg Clayton67cc0632012-08-22 17:17:09 +000061
62// Comment out line below to disable memory caching, overriding the process setting
63// target.process.disable-memory-cache
64#define ENABLE_MEMORY_CACHING
65
66#ifdef ENABLE_MEMORY_CACHING
67#define DISABLE_MEM_CACHE_DEFAULT false
68#else
69#define DISABLE_MEM_CACHE_DEFAULT true
70#endif
71
72class ProcessOptionValueProperties : public OptionValueProperties
73{
74public:
75 ProcessOptionValueProperties (const ConstString &name) :
76 OptionValueProperties (name)
77 {
78 }
79
80 // This constructor is used when creating ProcessOptionValueProperties when it
81 // is part of a new lldb_private::Process instance. It will copy all current
82 // global property values as needed
83 ProcessOptionValueProperties (ProcessProperties *global_properties) :
84 OptionValueProperties(*global_properties->GetValueProperties())
85 {
86 }
87
88 virtual const Property *
89 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
90 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000091 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000092 // try and grab the setting from the current process if there is one. Else we just
93 // use the one from this instance.
94 if (exe_ctx)
95 {
96 Process *process = exe_ctx->GetProcessPtr();
97 if (process)
98 {
99 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
100 if (this != instance_properties)
101 return instance_properties->ProtectedGetPropertyAtIndex (idx);
102 }
103 }
104 return ProtectedGetPropertyAtIndex (idx);
105 }
106};
107
108static PropertyDefinition
109g_properties[] =
110{
111 { "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 +0000112 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
113 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000114 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
115 { "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 +0000116 { "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 +0000117 { "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 +0000118 { "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 +0000119 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Greg Clayton67cc0632012-08-22 17:17:09 +0000120 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
121};
122
123enum {
124 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000125 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000126 ePropertyIgnoreBreakpointsInExpressions,
127 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000128 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000129 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000130 ePropertyDetachKeepsStopped,
131 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09 +0000132};
133
Greg Clayton332e8b12015-01-13 21:13:08 +0000134ProcessProperties::ProcessProperties (lldb_private::Process *process) :
135 Properties (),
136 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000137{
Greg Clayton332e8b12015-01-13 21:13:08 +0000138 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000139 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000140 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000141 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
142 m_collection_sp->Initialize(g_properties);
143 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000144 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000145 true,
146 Thread::GetGlobalProperties()->GetValueProperties());
147 }
148 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000149 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000150 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000151 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
152 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000153}
154
155ProcessProperties::~ProcessProperties()
156{
157}
158
Greg Clayton332e8b12015-01-13 21:13:08 +0000159void
160ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
161{
162 ProcessProperties *properties = (ProcessProperties *)baton;
163 if (properties->m_process)
164 properties->m_process->LoadOperatingSystemPlugin(true);
165}
166
Greg Clayton67cc0632012-08-22 17:17:09 +0000167bool
168ProcessProperties::GetDisableMemoryCache() const
169{
170 const uint32_t idx = ePropertyDisableMemCache;
171 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
172}
173
Jason Molendaf0340c92014-09-03 22:30:54 +0000174uint64_t
175ProcessProperties::GetMemoryCacheLineSize() const
176{
177 const uint32_t idx = ePropertyMemCacheLineSize;
178 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
179}
180
Greg Clayton67cc0632012-08-22 17:17:09 +0000181Args
182ProcessProperties::GetExtraStartupCommands () const
183{
184 Args args;
185 const uint32_t idx = ePropertyExtraStartCommand;
186 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
187 return args;
188}
189
190void
191ProcessProperties::SetExtraStartupCommands (const Args &args)
192{
193 const uint32_t idx = ePropertyExtraStartCommand;
194 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
195}
196
Greg Claytonc9d645d2012-10-18 22:40:37 +0000197FileSpec
198ProcessProperties::GetPythonOSPluginPath () const
199{
200 const uint32_t idx = ePropertyPythonOSPluginPath;
201 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
202}
203
204void
205ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
206{
207 const uint32_t idx = ePropertyPythonOSPluginPath;
208 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
209}
210
Jim Ingham184e9812013-01-15 02:47:48 +0000211
212bool
213ProcessProperties::GetIgnoreBreakpointsInExpressions () const
214{
215 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
217}
218
219void
220ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
221{
222 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
223 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
224}
225
226bool
227ProcessProperties::GetUnwindOnErrorInExpressions () const
228{
229 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
230 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
231}
232
233void
234ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
235{
236 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
237 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
238}
239
Jim Ingham29950772013-01-26 02:19:28 +0000240bool
241ProcessProperties::GetStopOnSharedLibraryEvents () const
242{
243 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
244 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
245}
246
247void
248ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
249{
250 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
251 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
252}
253
Jim Inghamacff8952013-05-02 00:27:30 +0000254bool
255ProcessProperties::GetDetachKeepsStopped () const
256{
257 const uint32_t idx = ePropertyDetachKeepsStopped;
258 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
259}
260
261void
262ProcessProperties::SetDetachKeepsStopped (bool stop)
263{
264 const uint32_t idx = ePropertyDetachKeepsStopped;
265 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
266}
267
Greg Clayton32e0a752011-03-30 18:16:51 +0000268void
Greg Clayton8b82f082011-04-12 05:54:46 +0000269ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000270{
271 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000272 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000273 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000274
275 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000276 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000277
278 if (m_executable)
279 {
280 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
281 s.PutCString (" file = ");
282 m_executable.Dump(&s);
283 s.EOL();
284 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000285 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000286 if (argc > 0)
287 {
288 for (uint32_t i=0; i<argc; i++)
289 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000294 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000295 }
296 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000297
298 const uint32_t envc = m_environment.GetArgumentCount();
299 if (envc > 0)
300 {
301 for (uint32_t i=0; i<envc; i++)
302 {
303 const char *env = m_environment.GetArgumentAtIndex(i);
304 if (i < 10)
305 s.Printf (" env[%u] = %s\n", i, env);
306 else
307 s.Printf ("env[%u] = %s\n", i, env);
308 }
309 }
310
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000311 if (m_arch.IsValid())
312 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
313
Greg Clayton8b82f082011-04-12 05:54:46 +0000314 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000315 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000316 cstr = platform->GetUserName (m_uid);
317 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000318 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000319 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000320 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 cstr = platform->GetGroupName (m_gid);
322 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000323 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000324 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000325 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000326 cstr = platform->GetUserName (m_euid);
327 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000328 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000329 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000330 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000331 cstr = platform->GetGroupName (m_egid);
332 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000333 }
334}
335
336void
Greg Clayton8b82f082011-04-12 05:54:46 +0000337ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000338{
Greg Clayton8b82f082011-04-12 05:54:46 +0000339 const char *label;
340 if (show_args || verbose)
341 label = "ARGUMENTS";
342 else
343 label = "NAME";
344
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000345 if (verbose)
346 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000348 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
349 }
350 else
351 {
Jim Ingham368ac222014-08-15 17:05:27 +0000352 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
353 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000354 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000355}
356
357void
Greg Clayton8b82f082011-04-12 05:54:46 +0000358ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000359{
360 if (m_pid != LLDB_INVALID_PROCESS_ID)
361 {
362 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000363 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000364
Greg Clayton32e0a752011-03-30 18:16:51 +0000365
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000366 if (verbose)
367 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000368 cstr = platform->GetUserName (m_uid);
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_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000373
Greg Clayton8b82f082011-04-12 05:54:46 +0000374 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000375 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
376 s.Printf ("%-10s ", cstr);
377 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000378 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000379
Greg Clayton8b82f082011-04-12 05:54:46 +0000380 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000381 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
382 s.Printf ("%-10s ", cstr);
383 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000384 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000385
Greg Clayton8b82f082011-04-12 05:54:46 +0000386 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000387 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
388 s.Printf ("%-10s ", cstr);
389 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000390 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000391 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
392 }
393 else
394 {
Jim Ingham368ac222014-08-15 17:05:27 +0000395 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000396 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000397 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000398 }
399
Greg Clayton8b82f082011-04-12 05:54:46 +0000400 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000401 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000402 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000403 if (argc > 0)
404 {
405 for (uint32_t i=0; i<argc; i++)
406 {
407 if (i > 0)
408 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000410 }
411 }
412 }
413 else
414 {
415 s.PutCString (GetName());
416 }
417
418 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000419 }
420}
421
Greg Clayton8b82f082011-04-12 05:54:46 +0000422Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000423ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000424{
425 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000426 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000427
428 switch (short_option)
429 {
430 case 's': // Stop at program entry point
431 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
432 break;
433
Greg Clayton8b82f082011-04-12 05:54:46 +0000434 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000435 {
436 FileAction action;
437 if (action.Open (STDIN_FILENO, option_arg, true, false))
438 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000439 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000440 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000441
442 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000443 {
444 FileAction action;
445 if (action.Open (STDOUT_FILENO, option_arg, false, true))
446 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000447 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000448 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000449
450 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000451 {
452 FileAction action;
453 if (action.Open (STDERR_FILENO, option_arg, false, true))
454 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000455 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000456 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000457
Greg Clayton8b82f082011-04-12 05:54:46 +0000458 case 'p': // Process plug-in name
459 launch_info.SetProcessPluginName (option_arg);
460 break;
461
462 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000463 {
464 FileAction action;
465 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
466 launch_info.AppendFileAction (action);
467 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
468 launch_info.AppendFileAction (action);
469 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
470 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000471 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000472 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000473
474 case 'w':
475 launch_info.SetWorkingDirectory (option_arg);
476 break;
477
478 case 't': // Open process in new terminal window
479 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
480 break;
481
482 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000483 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
484 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000485 break;
486
Todd Fiala51637922014-08-19 17:40:43 +0000487 case 'A': // Disable ASLR.
488 {
489 bool success;
490 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
491 if (success)
492 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
493 else
494 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000495 break;
Todd Fiala51637922014-08-19 17:40:43 +0000496 }
497
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000498 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000499 {
500 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000501 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000502 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000503 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000504 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000505 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000506 break;
507 }
508
Todd Fiala51637922014-08-19 17:40:43 +0000509 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000510 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000511 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000512 else
Zachary Turner10687b02014-10-20 17:46:43 +0000513 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000514 break;
515
Greg Clayton8b82f082011-04-12 05:54:46 +0000516 case 'v':
517 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
518 break;
519
520 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000521 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000522 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000523 }
524 return error;
525}
526
527OptionDefinition
528ProcessLaunchCommandOptions::g_option_table[] =
529{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000530{ 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 +0000531{ 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 +0000532{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
533{ 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."},
534{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
535{ 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."},
Enrico Granatad7a83a92015-02-10 03:06:24 +0000536{ LLDB_OPT_SET_1|LLDB_OPT_SET_2|LLDB_OPT_SET_3, 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 +0000537
Zachary Turnerd37221d2014-07-09 16:31:49 +0000538{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
539{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
540{ 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 +0000541
Zachary Turnerd37221d2014-07-09 16:31:49 +0000542{ 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 +0000543
Zachary Turnerd37221d2014-07-09 16:31:49 +0000544{ 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."},
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000545{ LLDB_OPT_SET_4, false, "shell-expand-args", 'X', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to shell expand arguments to the process when launching."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000546{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000547};
548
549
550
551bool
552ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000553{
554 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
555 return true;
556 const char *match_name = m_match_info.GetName();
557 if (!match_name)
558 return true;
559
560 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
561}
562
563bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000564ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000565{
566 if (!NameMatches (proc_info.GetName()))
567 return false;
568
569 if (m_match_info.ProcessIDIsValid() &&
570 m_match_info.GetProcessID() != proc_info.GetProcessID())
571 return false;
572
573 if (m_match_info.ParentProcessIDIsValid() &&
574 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
575 return false;
576
Greg Clayton8b82f082011-04-12 05:54:46 +0000577 if (m_match_info.UserIDIsValid () &&
578 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000579 return false;
580
Greg Clayton8b82f082011-04-12 05:54:46 +0000581 if (m_match_info.GroupIDIsValid () &&
582 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000583 return false;
584
585 if (m_match_info.EffectiveUserIDIsValid () &&
586 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
587 return false;
588
589 if (m_match_info.EffectiveGroupIDIsValid () &&
590 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
591 return false;
592
593 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000594 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000595 return false;
596 return true;
597}
598
599bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000600ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000601{
602 if (m_name_match_type != eNameMatchIgnore)
603 return false;
604
605 if (m_match_info.ProcessIDIsValid())
606 return false;
607
608 if (m_match_info.ParentProcessIDIsValid())
609 return false;
610
Greg Clayton8b82f082011-04-12 05:54:46 +0000611 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000612 return false;
613
Greg Clayton8b82f082011-04-12 05:54:46 +0000614 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000615 return false;
616
617 if (m_match_info.EffectiveUserIDIsValid ())
618 return false;
619
620 if (m_match_info.EffectiveGroupIDIsValid ())
621 return false;
622
623 if (m_match_info.GetArchitecture().IsValid())
624 return false;
625
626 if (m_match_all_users)
627 return false;
628
629 return true;
630
631}
632
633void
Greg Clayton8b82f082011-04-12 05:54:46 +0000634ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000635{
636 m_match_info.Clear();
637 m_name_match_type = eNameMatchIgnore;
638 m_match_all_users = false;
639}
Greg Clayton58be07b2011-01-07 06:08:19 +0000640
Greg Claytonc3776bf2012-02-09 06:16:32 +0000641ProcessSP
642Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643{
Greg Clayton949e8222013-01-16 17:29:04 +0000644 static uint32_t g_process_unique_id = 0;
645
Greg Claytonc3776bf2012-02-09 06:16:32 +0000646 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000647 ProcessCreateInstance create_callback = NULL;
648 if (plugin_name)
649 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000650 ConstString const_plugin_name(plugin_name);
651 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 if (create_callback)
653 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000654 process_sp = create_callback(target, listener, crash_file_path);
655 if (process_sp)
656 {
Greg Clayton949e8222013-01-16 17:29:04 +0000657 if (process_sp->CanDebug(target, true))
658 {
659 process_sp->m_process_unique_id = ++g_process_unique_id;
660 }
661 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000662 process_sp.reset();
663 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664 }
665 }
666 else
667 {
Greg Claytonc982c762010-07-09 20:39:50 +0000668 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000670 process_sp = create_callback(target, listener, crash_file_path);
671 if (process_sp)
672 {
Greg Clayton949e8222013-01-16 17:29:04 +0000673 if (process_sp->CanDebug(target, false))
674 {
675 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000676 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000677 }
678 else
679 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000680 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000681 }
682 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000683 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684}
685
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000686ConstString &
687Process::GetStaticBroadcasterClass ()
688{
689 static ConstString class_name ("lldb.process");
690 return class_name;
691}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692
693//----------------------------------------------------------------------
694// Process constructor
695//----------------------------------------------------------------------
696Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000697 Process(target, listener, Host::GetUnixSignals ())
698{
699 // This constructor just delegates to the full Process constructor,
700 // defaulting to using the Host's UnixSignals.
701}
702
703Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000704 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 UserID (LLDB_INVALID_PROCESS_ID),
Ilia K8a00a562015-03-17 16:54:52 +0000706 Broadcaster (&(target.GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 m_public_state (eStateUnloaded),
709 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000710 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
711 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 m_private_state_listener ("lldb.process.internal_state_listener"),
713 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000714 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000715 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000717 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000718 m_exit_status (-1),
719 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000720 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000721 m_thread_mutex (Mutex::eMutexTypeRecursive),
722 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000724 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000725 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000726 m_queue_list (this),
727 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000729 m_image_tokens (),
730 m_listener (listener),
731 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000732 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000733 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000734 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000735 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000736 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000737 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000738 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000739 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000740 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000741 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
742 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000743 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000744 m_memory_cache (*this),
745 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000746 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000747 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000748 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000749 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000750 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000751 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58 +0000752 m_finalizing (false),
753 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000754 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000755 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000756 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000757 m_destroy_in_process (false),
758 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000760 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000761
Greg Clayton5160ce52013-03-27 23:08:40 +0000762 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000764 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000765
Todd Fiala4ceced32014-08-29 17:35:57 +0000766 if (!m_unix_signals_sp)
767 m_unix_signals_sp.reset (new UnixSignals ());
768
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000769 SetEventName (eBroadcastBitStateChanged, "state-changed");
770 SetEventName (eBroadcastBitInterrupt, "interrupt");
771 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
772 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000773 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000774
Greg Clayton35a4cc52012-10-29 20:52:08 +0000775 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
776 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
777 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
778
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779 listener.StartListeningForEvents (this,
780 eBroadcastBitStateChanged |
781 eBroadcastBitInterrupt |
782 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000783 eBroadcastBitSTDERR |
784 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785
786 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000787 eBroadcastBitStateChanged |
788 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789
790 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
791 eBroadcastInternalStateControlStop |
792 eBroadcastInternalStateControlPause |
793 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000794 // We need something valid here, even if just the default UnixSignalsSP.
795 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796}
797
798//----------------------------------------------------------------------
799// Destructor
800//----------------------------------------------------------------------
801Process::~Process()
802{
Greg Clayton5160ce52013-03-27 23:08:40 +0000803 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000805 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000807
808 // ThreadList::Clear() will try to acquire this process's mutex, so
809 // explicitly clear the thread list here to ensure that the mutex
810 // is not destroyed before the thread list.
811 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000812}
813
Greg Clayton67cc0632012-08-22 17:17:09 +0000814const ProcessPropertiesSP &
815Process::GetGlobalProperties()
816{
817 static ProcessPropertiesSP g_settings_sp;
818 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000819 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000820 return g_settings_sp;
821}
822
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823void
824Process::Finalize()
825{
Greg Claytonc00ca312015-04-02 18:44:58 +0000826 m_finalizing = true;
827
Ilia Kc7efd562015-03-26 07:40:40 +0000828 // Destroy this process if needed
829 switch (GetPrivateState())
830 {
831 case eStateConnected:
832 case eStateAttaching:
833 case eStateLaunching:
834 case eStateStopped:
835 case eStateRunning:
836 case eStateStepping:
837 case eStateCrashed:
838 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000839 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000840 break;
841
842 case eStateInvalid:
843 case eStateUnloaded:
844 case eStateDetached:
845 case eStateExited:
846 break;
847 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000848
Greg Clayton1ed54f52011-10-01 00:45:15 +0000849 // Clear our broadcaster before we proceed with destroying
850 Broadcaster::Clear();
851
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000852 // Do any cleanup needed prior to being destructed... Subclasses
853 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000854
855 // We need to destroy the loader before the derived Process class gets destroyed
856 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000857 m_dynamic_checkers_ap.reset();
858 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000859 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000860 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000861 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000862 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000863 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000864 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000865 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000866 m_queue_list.Clear();
867 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000868 std::vector<Notifications> empty_notifications;
869 m_notifications.swap(empty_notifications);
870 m_image_tokens.clear();
871 m_memory_cache.Clear();
872 m_allocated_memory_cache.Clear();
873 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000874 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000875 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000876 m_stop_info_override_callback = NULL;
Greg Clayton35a4cc52012-10-29 20:52:08 +0000877//#ifdef LLDB_CONFIGURATION_DEBUG
878// StreamFile s(stdout, false);
879// EventSP event_sp;
880// while (m_private_state_listener.GetNextEvent(event_sp))
881// {
882// event_sp->Dump (&s);
883// s.EOL();
884// }
885//#endif
886 // We have to be very careful here as the m_private_state_listener might
887 // contain events that have ProcessSP values in them which can keep this
888 // process around forever. These events need to be cleared out.
889 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000890 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
891 m_public_run_lock.SetStopped();
892 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
893 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000894 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000895}
896
897void
898Process::RegisterNotificationCallbacks (const Notifications& callbacks)
899{
900 m_notifications.push_back(callbacks);
901 if (callbacks.initialize != NULL)
902 callbacks.initialize (callbacks.baton, this);
903}
904
905bool
906Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
907{
908 std::vector<Notifications>::iterator pos, end = m_notifications.end();
909 for (pos = m_notifications.begin(); pos != end; ++pos)
910 {
911 if (pos->baton == callbacks.baton &&
912 pos->initialize == callbacks.initialize &&
913 pos->process_state_changed == callbacks.process_state_changed)
914 {
915 m_notifications.erase(pos);
916 return true;
917 }
918 }
919 return false;
920}
921
922void
923Process::SynchronouslyNotifyStateChanged (StateType state)
924{
925 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
926 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
927 {
928 if (notification_pos->process_state_changed)
929 notification_pos->process_state_changed (notification_pos->baton, this, state);
930 }
931}
932
933// FIXME: We need to do some work on events before the general Listener sees them.
934// For instance if we are continuing from a breakpoint, we need to ensure that we do
935// the little "insert real insn, step & stop" trick. But we can't do that when the
936// event is delivered by the broadcaster - since that is done on the thread that is
937// waiting for new events, so if we needed more than one event for our handling, we would
938// stall. So instead we do it when we fetch the event off of the queue.
939//
940
941StateType
942Process::GetNextEvent (EventSP &event_sp)
943{
944 StateType state = eStateInvalid;
945
946 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
947 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
948
949 return state;
950}
951
Todd Fialaa3b89e22014-08-12 14:33:19 +0000952bool
953Process::SyncIOHandler (uint64_t timeout_msec)
954{
955 bool timed_out = false;
956
957 // don't sync (potentially context switch) in case where there is no process IO
958 if (m_process_input_reader)
959 {
960 TimeValue timeout = TimeValue::Now();
961 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
962
963 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
964
965 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
966 if(log)
967 {
968 if(timed_out)
969 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
970 else
971 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
972 }
973
Shawn Best1ded74a2014-10-08 01:50:37 +0000974 // reset sync one-shot so it will be ready for next launch
Todd Fialaa3b89e22014-08-12 14:33:19 +0000975 m_iohandler_sync.SetValue(false, eBroadcastNever);
976 }
977
978 return !timed_out;
979}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980
981StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000982Process::WaitForProcessToStop (const TimeValue *timeout,
983 EventSP *event_sp_ptr,
984 bool wait_always,
985 Listener *hijack_listener,
986 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000987{
Jim Ingham4b536182011-08-09 02:12:22 +0000988 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
989 // We have to actually check each event, and in the case of a stopped event check the restarted flag
990 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000991 if (event_sp_ptr)
992 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000993 StateType state = GetState();
994 // If we are exited or detached, we won't ever get back to any
995 // other valid state...
996 if (state == eStateDetached || state == eStateExited)
997 return state;
998
Daniel Malea9e9919f2013-10-09 16:56:28 +0000999 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1000 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001001 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
1002 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001003
1004 if (!wait_always &&
1005 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +00001006 StateIsStoppedState(GetPrivateState(), true))
1007 {
Daniel Malea9e9919f2013-10-09 16:56:28 +00001008 if (log)
1009 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1010 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001011 // We need to toggle the run lock as this won't get done in
1012 // SetPublicState() if the process is hijacked.
1013 if (hijack_listener)
1014 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001015 return state;
1016 }
1017
Jim Ingham4b536182011-08-09 02:12:22 +00001018 while (state != eStateInvalid)
1019 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001020 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001021 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001022 if (event_sp_ptr && event_sp)
1023 *event_sp_ptr = event_sp;
1024
Greg Claytondc6224e2014-10-21 01:00:42 +00001025 bool pop_process_io_handler = hijack_listener != NULL;
1026 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1027
Jim Ingham4b536182011-08-09 02:12:22 +00001028 switch (state)
1029 {
1030 case eStateCrashed:
1031 case eStateDetached:
1032 case eStateExited:
1033 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001034 // We need to toggle the run lock as this won't get done in
1035 // SetPublicState() if the process is hijacked.
1036 if (hijack_listener)
1037 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001038 return state;
1039 case eStateStopped:
1040 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1041 continue;
1042 else
Greg Clayton44d93782014-01-27 23:43:24 +00001043 {
1044 // We need to toggle the run lock as this won't get done in
1045 // SetPublicState() if the process is hijacked.
1046 if (hijack_listener)
1047 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001048 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001049 }
Jim Ingham4b536182011-08-09 02:12:22 +00001050 default:
1051 continue;
1052 }
1053 }
1054 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001055}
1056
Greg Claytondc6224e2014-10-21 01:00:42 +00001057bool
1058Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1059 Stream *stream,
1060 bool &pop_process_io_handler)
1061{
1062 const bool handle_pop = pop_process_io_handler == true;
1063
1064 pop_process_io_handler = false;
1065 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1066
1067 if (!process_sp)
1068 return false;
1069
1070 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1071 if (event_state == eStateInvalid)
1072 return false;
1073
1074 switch (event_state)
1075 {
1076 case eStateInvalid:
1077 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001078 case eStateAttaching:
1079 case eStateLaunching:
1080 case eStateStepping:
1081 case eStateDetached:
1082 {
1083 if (stream)
1084 stream->Printf ("Process %" PRIu64 " %s\n",
1085 process_sp->GetID(),
1086 StateAsCString (event_state));
1087
1088 if (event_state == eStateDetached)
1089 pop_process_io_handler = true;
1090 }
1091 break;
1092
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001093 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001094 case eStateRunning:
1095 // Don't be chatty when we run...
1096 break;
1097
1098 case eStateExited:
1099 if (stream)
1100 process_sp->GetStatus(*stream);
1101 pop_process_io_handler = true;
1102 break;
1103
1104 case eStateStopped:
1105 case eStateCrashed:
1106 case eStateSuspended:
1107 // Make sure the program hasn't been auto-restarted:
1108 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1109 {
1110 if (stream)
1111 {
1112 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1113 if (num_reasons > 0)
1114 {
1115 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1116 if (num_reasons == 1)
1117 {
1118 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1119 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1120 process_sp->GetID(),
1121 reason ? reason : "<UNKNOWN REASON>");
1122 }
1123 else
1124 {
1125 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1126 process_sp->GetID());
1127
1128
1129 for (size_t i = 0; i < num_reasons; i++)
1130 {
1131 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1132 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1133 }
1134 }
1135 }
1136 }
1137 }
1138 else
1139 {
1140 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1141 {
1142 ThreadList &thread_list = process_sp->GetThreadList();
1143 Mutex::Locker locker (thread_list.GetMutex());
1144
1145 ThreadSP curr_thread (thread_list.GetSelectedThread());
1146 ThreadSP thread;
1147 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1148 if (curr_thread)
1149 curr_thread_stop_reason = curr_thread->GetStopReason();
1150 if (!curr_thread ||
1151 !curr_thread->IsValid() ||
1152 curr_thread_stop_reason == eStopReasonInvalid ||
1153 curr_thread_stop_reason == eStopReasonNone)
1154 {
1155 // Prefer a thread that has just completed its plan over another thread as current thread.
1156 ThreadSP plan_thread;
1157 ThreadSP other_thread;
1158 const size_t num_threads = thread_list.GetSize();
1159 size_t i;
1160 for (i = 0; i < num_threads; ++i)
1161 {
1162 thread = thread_list.GetThreadAtIndex(i);
1163 StopReason thread_stop_reason = thread->GetStopReason();
1164 switch (thread_stop_reason)
1165 {
1166 case eStopReasonInvalid:
1167 case eStopReasonNone:
1168 break;
1169
1170 case eStopReasonTrace:
1171 case eStopReasonBreakpoint:
1172 case eStopReasonWatchpoint:
1173 case eStopReasonSignal:
1174 case eStopReasonException:
1175 case eStopReasonExec:
1176 case eStopReasonThreadExiting:
1177 case eStopReasonInstrumentation:
1178 if (!other_thread)
1179 other_thread = thread;
1180 break;
1181 case eStopReasonPlanComplete:
1182 if (!plan_thread)
1183 plan_thread = thread;
1184 break;
1185 }
1186 }
1187 if (plan_thread)
1188 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1189 else if (other_thread)
1190 thread_list.SetSelectedThreadByID (other_thread->GetID());
1191 else
1192 {
1193 if (curr_thread && curr_thread->IsValid())
1194 thread = curr_thread;
1195 else
1196 thread = thread_list.GetThreadAtIndex(0);
1197
1198 if (thread)
1199 thread_list.SetSelectedThreadByID (thread->GetID());
1200 }
1201 }
1202 }
1203 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1204 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1205 // have a hard time restarting the process.
1206 if (stream)
1207 {
1208 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1209 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1210 {
1211 const bool only_threads_with_stop_reason = true;
1212 const uint32_t start_frame = 0;
1213 const uint32_t num_frames = 1;
1214 const uint32_t num_frames_with_source = 1;
1215 process_sp->GetStatus(*stream);
1216 process_sp->GetThreadStatus (*stream,
1217 only_threads_with_stop_reason,
1218 start_frame,
1219 num_frames,
1220 num_frames_with_source);
1221 }
1222 else
1223 {
1224 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1225 if (target_idx != UINT32_MAX)
1226 stream->Printf ("Target %d: (", target_idx);
1227 else
1228 stream->Printf ("Target <unknown index>: (");
1229 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1230 stream->Printf (") stopped.\n");
1231 }
1232 }
1233
1234 // Pop the process IO handler
1235 pop_process_io_handler = true;
1236 }
1237 break;
1238 }
1239
1240 if (handle_pop && pop_process_io_handler)
1241 process_sp->PopProcessIOHandler();
1242
1243 return true;
1244}
1245
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001246
1247StateType
1248Process::WaitForState
1249(
1250 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001251 const StateType *match_states,
1252 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001253)
1254{
1255 EventSP event_sp;
1256 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001257 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001258 while (state != eStateInvalid)
1259 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001260 // If we are exited or detached, we won't ever get back to any
1261 // other valid state...
1262 if (state == eStateDetached || state == eStateExited)
1263 return state;
1264
Greg Clayton44d93782014-01-27 23:43:24 +00001265 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266
1267 for (i=0; i<num_match_states; ++i)
1268 {
1269 if (match_states[i] == state)
1270 return state;
1271 }
1272 }
1273 return state;
1274}
1275
Jim Ingham30f9b212010-10-11 23:53:14 +00001276bool
1277Process::HijackProcessEvents (Listener *listener)
1278{
1279 if (listener != NULL)
1280 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001281 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001282 }
1283 else
1284 return false;
1285}
1286
1287void
1288Process::RestoreProcessEvents ()
1289{
1290 RestoreBroadcaster();
1291}
1292
Jim Ingham0f16e732011-02-08 05:20:59 +00001293bool
1294Process::HijackPrivateProcessEvents (Listener *listener)
1295{
1296 if (listener != NULL)
1297 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001298 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001299 }
1300 else
1301 return false;
1302}
1303
1304void
1305Process::RestorePrivateProcessEvents ()
1306{
1307 m_private_state_broadcaster.RestoreBroadcaster();
1308}
1309
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001310StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001311Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312{
Greg Clayton5160ce52013-03-27 23:08:40 +00001313 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314
1315 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001316 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1317 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318
Greg Clayton44d93782014-01-27 23:43:24 +00001319 Listener *listener = hijack_listener;
1320 if (listener == NULL)
1321 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001322
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001324 if (listener->WaitForEventForBroadcasterWithType (timeout,
1325 this,
1326 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1327 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001328 {
1329 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1330 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1331 else if (log)
1332 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1333 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334
1335 if (log)
1336 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001337 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338 StateAsCString(state));
1339 return state;
1340}
1341
1342Event *
1343Process::PeekAtStateChangedEvents ()
1344{
Greg Clayton5160ce52013-03-27 23:08:40 +00001345 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346
1347 if (log)
1348 log->Printf ("Process::%s...", __FUNCTION__);
1349
1350 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001351 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1352 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 if (log)
1354 {
1355 if (event_ptr)
1356 {
1357 log->Printf ("Process::%s (event_ptr) => %s",
1358 __FUNCTION__,
1359 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1360 }
1361 else
1362 {
1363 log->Printf ("Process::%s no events found",
1364 __FUNCTION__);
1365 }
1366 }
1367 return event_ptr;
1368}
1369
1370StateType
1371Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1372{
Greg Clayton5160ce52013-03-27 23:08:40 +00001373 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374
1375 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001376 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1377 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378
1379 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001380 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1381 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001382 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001383 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001384 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1385 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001386
1387 // This is a bit of a hack, but when we wait here we could very well return
1388 // to the command-line, and that could disable the log, which would render the
1389 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001391 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1392 __FUNCTION__, static_cast<const void *>(timeout),
1393 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001394 return state;
1395}
1396
1397bool
1398Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1399{
Greg Clayton5160ce52013-03-27 23:08:40 +00001400 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401
1402 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001403 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1404 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405
1406 if (control_only)
1407 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1408 else
1409 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1410}
1411
1412bool
1413Process::IsRunning () const
1414{
1415 return StateIsRunningState (m_public_state.GetValue());
1416}
1417
1418int
1419Process::GetExitStatus ()
1420{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001421 Mutex::Locker locker (m_exit_status_mutex);
1422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423 if (m_public_state.GetValue() == eStateExited)
1424 return m_exit_status;
1425 return -1;
1426}
1427
Greg Clayton85851dd2010-12-04 00:10:17 +00001428
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001429const char *
1430Process::GetExitDescription ()
1431{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001432 Mutex::Locker locker (m_exit_status_mutex);
1433
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1435 return m_exit_string.c_str();
1436 return NULL;
1437}
1438
Greg Clayton6779606a2011-01-22 23:43:18 +00001439bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001440Process::SetExitStatus (int status, const char *cstr)
1441{
Greg Clayton5160ce52013-03-27 23:08:40 +00001442 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001443 if (log)
1444 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1445 status, status,
1446 cstr ? "\"" : "",
1447 cstr ? cstr : "NULL",
1448 cstr ? "\"" : "");
1449
Greg Clayton6779606a2011-01-22 23:43:18 +00001450 // We were already in the exited state
1451 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001452 {
Greg Clayton385d6032011-01-26 23:47:29 +00001453 if (log)
1454 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001455 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001456 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001457
Todd Fiala7b0917a2014-09-15 20:07:33 +00001458 // use a mutex to protect the status and string during updating
1459 {
1460 Mutex::Locker locker (m_exit_status_mutex);
1461
1462 m_exit_status = status;
1463 if (cstr)
1464 m_exit_string = cstr;
1465 else
1466 m_exit_string.clear();
1467 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001468
Greg Clayton6779606a2011-01-22 23:43:18 +00001469 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001470
Greg Clayton6779606a2011-01-22 23:43:18 +00001471 SetPrivateState (eStateExited);
1472 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001473}
1474
1475// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001476// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477// found in the global target list (we want to be completely sure that the
1478// lldb_private::Process doesn't go away before we can deliver the signal.
1479bool
Greg Claytone4e45922011-11-16 05:37:56 +00001480Process::SetProcessExitStatus (void *callback_baton,
1481 lldb::pid_t pid,
1482 bool exited,
1483 int signo, // Zero for no signal
1484 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485)
1486{
Greg Clayton5160ce52013-03-27 23:08:40 +00001487 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001488 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001489 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001490 callback_baton,
1491 pid,
1492 exited,
1493 signo,
1494 exit_status);
1495
1496 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001497 {
Greg Clayton66111032010-06-23 01:19:29 +00001498 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499 if (target_sp)
1500 {
1501 ProcessSP process_sp (target_sp->GetProcessSP());
1502 if (process_sp)
1503 {
1504 const char *signal_cstr = NULL;
1505 if (signo)
1506 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1507
1508 process_sp->SetExitStatus (exit_status, signal_cstr);
1509 }
1510 }
1511 return true;
1512 }
1513 return false;
1514}
1515
1516
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001517void
1518Process::UpdateThreadListIfNeeded ()
1519{
1520 const uint32_t stop_id = GetStopID();
1521 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1522 {
Greg Clayton2637f822011-11-17 01:23:07 +00001523 const StateType state = GetPrivateState();
1524 if (StateIsStoppedState (state, true))
1525 {
1526 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001527 // m_thread_list does have its own mutex, but we need to
1528 // hold onto the mutex between the call to UpdateThreadList(...)
1529 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001530 ThreadList &old_thread_list = m_thread_list;
1531 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001532 ThreadList new_thread_list(this);
1533 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001534 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001535 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001536 {
Jim Ingham09437922013-03-01 20:04:25 +00001537 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1538 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1539 // shutting us down, causing a deadlock.
1540 if (!m_destroy_in_process)
1541 {
1542 OperatingSystem *os = GetOperatingSystem ();
1543 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001544 {
1545 // Clear any old backing threads where memory threads might have been
1546 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001547 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001548 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001549 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001550
Greg Clayton15484402015-05-15 18:40:24 +00001551 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1552 // can run an expression to determine if a SBValue is a dynamic type or not
1553 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1554 // that require running code...
1555
1556 Target &target = GetTarget();
1557 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1558 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1559 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1560
Greg Claytonb3ae8762013-04-12 20:07:46 +00001561 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001562
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001563 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1564 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1565 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Clayton15484402015-05-15 18:40:24 +00001566
1567 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1568 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001569 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001570 else
1571 {
1572 // No OS plug-in, the new thread list is the same as the real thread list
1573 new_thread_list = real_thread_list;
1574 }
Jim Ingham09437922013-03-01 20:04:25 +00001575 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001576
1577 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001578 m_thread_list.Update (new_thread_list);
1579 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001580
Jason Molenda4ff13262013-11-20 00:31:38 +00001581 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1582 {
1583 // Clear any extended threads that we may have accumulated previously
1584 m_extended_thread_list.Clear();
1585 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001586
1587 m_queue_list.Clear();
1588 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001589 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001590 }
Greg Clayton2637f822011-11-17 01:23:07 +00001591 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001592 }
1593}
1594
Jason Molenda5e8dce42013-12-13 00:29:16 +00001595void
1596Process::UpdateQueueListIfNeeded ()
1597{
1598 if (m_system_runtime_ap.get())
1599 {
1600 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1601 {
1602 const StateType state = GetPrivateState();
1603 if (StateIsStoppedState (state, true))
1604 {
1605 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1606 m_queue_list_stop_id = GetLastNaturalStopID();
1607 }
1608 }
1609 }
1610}
1611
Greg Claytona4d87472013-01-18 23:41:08 +00001612ThreadSP
1613Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1614{
1615 OperatingSystem *os = GetOperatingSystem ();
1616 if (os)
1617 return os->CreateThread(tid, context);
1618 return ThreadSP();
1619}
1620
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001621uint32_t
1622Process::GetNextThreadIndexID (uint64_t thread_id)
1623{
1624 return AssignIndexIDToThread(thread_id);
1625}
1626
1627bool
1628Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1629{
1630 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1631 if (iterator == m_thread_id_to_index_id_map.end())
1632 {
1633 return false;
1634 }
1635 else
1636 {
1637 return true;
1638 }
1639}
1640
1641uint32_t
1642Process::AssignIndexIDToThread(uint64_t thread_id)
1643{
1644 uint32_t result = 0;
1645 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1646 if (iterator == m_thread_id_to_index_id_map.end())
1647 {
1648 result = ++m_thread_index_id;
1649 m_thread_id_to_index_id_map[thread_id] = result;
1650 }
1651 else
1652 {
1653 result = iterator->second;
1654 }
1655
1656 return result;
1657}
1658
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659StateType
1660Process::GetState()
1661{
1662 // If any other threads access this we will need a mutex for it
1663 return m_public_state.GetValue ();
1664}
1665
Greg Claytondc6224e2014-10-21 01:00:42 +00001666bool
1667Process::StateChangedIsExternallyHijacked()
1668{
1669 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1670 {
1671 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1672 return true;
1673 }
1674 return false;
1675}
1676
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001677void
Jim Ingham221d51c2013-05-08 00:35:16 +00001678Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679{
Greg Clayton5160ce52013-03-27 23:08:40 +00001680 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001681 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001682 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001683 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001685
1686 // On the transition from Run to Stopped, we unlock the writer end of the
1687 // run lock. The lock gets locked in Resume, which is the public API
1688 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001689 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001690 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001691 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001692 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001693 if (log)
1694 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001695 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001696 }
1697 else
1698 {
1699 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1700 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001701 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001702 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001703 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001704 {
1705 if (log)
1706 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001707 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001708 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001709 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001710 }
1711 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001712}
1713
Jim Ingham3b8285d2012-04-19 01:40:33 +00001714Error
1715Process::Resume ()
1716{
Greg Clayton5160ce52013-03-27 23:08:40 +00001717 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001718 if (log)
1719 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001720 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001721 {
1722 Error error("Resume request failed - process still running.");
1723 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001724 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001725 return error;
1726 }
1727 return PrivateResume();
1728}
1729
Greg Claytondc6224e2014-10-21 01:00:42 +00001730Error
1731Process::ResumeSynchronous (Stream *stream)
1732{
1733 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1734 if (log)
1735 log->Printf("Process::ResumeSynchronous -- locking run lock");
1736 if (!m_public_run_lock.TrySetRunning())
1737 {
1738 Error error("Resume request failed - process still running.");
1739 if (log)
1740 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1741 return error;
1742 }
1743
1744 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1745 HijackProcessEvents(listener_sp.get());
1746
1747 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001748 if (error.Success())
1749 {
1750 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1751 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1752 if (!StateIsStoppedState(state, must_be_alive))
1753 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1754 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001755
1756 // Undo the hijacking of process events...
1757 RestoreProcessEvents();
1758
Greg Claytondc6224e2014-10-21 01:00:42 +00001759 return error;
1760}
1761
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762StateType
1763Process::GetPrivateState ()
1764{
1765 return m_private_state.GetValue();
1766}
1767
1768void
1769Process::SetPrivateState (StateType new_state)
1770{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001771 if (m_finalize_called)
1772 return;
1773
Greg Clayton5160ce52013-03-27 23:08:40 +00001774 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775 bool state_changed = false;
1776
1777 if (log)
1778 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1779
Andrew Kaylor29d65742013-05-10 17:19:04 +00001780 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001781 Mutex::Locker locker(m_private_state.GetMutex());
1782
1783 const StateType old_state = m_private_state.GetValueNoLock ();
1784 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001785
Greg Claytonaa49c832013-05-03 22:25:56 +00001786 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1787 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1788 if (old_state_is_stopped != new_state_is_stopped)
1789 {
1790 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001791 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001792 else
Ed Maste64fad602013-07-29 20:58:06 +00001793 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001794 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001795
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001796 if (state_changed)
1797 {
1798 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001799 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001800 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001802 // Note, this currently assumes that all threads in the list
1803 // stop when the process stops. In the future we will want to
1804 // support a debugging model where some threads continue to run
1805 // while others are stopped. When that happens we will either need
1806 // a way for the thread list to identify which threads are stopping
1807 // or create a special thread list containing only threads which
1808 // actually stopped.
1809 //
1810 // The process plugin is responsible for managing the actual
1811 // behavior of the threads and should have stopped any threads
1812 // that are going to stop before we get here.
1813 m_thread_list.DidStop();
1814
Jim Ingham4b536182011-08-09 02:12:22 +00001815 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001816 if (!m_mod_id.IsLastResumeForUserExpression())
1817 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001818 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001820 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001821 }
Ilia K38810f42015-05-20 10:15:47 +00001822
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001824 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:47 +00001825 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001826 else
Ilia K38810f42015-05-20 10:15:47 +00001827 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 }
1829 else
1830 {
1831 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001832 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833 }
1834}
1835
Jim Ingham0faa43f2011-11-08 03:00:11 +00001836void
1837Process::SetRunningUserExpression (bool on)
1838{
1839 m_mod_id.SetRunningUserExpression (on);
1840}
1841
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842addr_t
1843Process::GetImageInfoAddress()
1844{
1845 return LLDB_INVALID_ADDRESS;
1846}
1847
Greg Clayton8f343b02010-11-04 01:54:29 +00001848//----------------------------------------------------------------------
1849// LoadImage
1850//
1851// This function provides a default implementation that works for most
1852// unix variants. Any Process subclasses that need to do shared library
1853// loading differently should override LoadImage and UnloadImage and
1854// do what is needed.
1855//----------------------------------------------------------------------
1856uint32_t
1857Process::LoadImage (const FileSpec &image_spec, Error &error)
1858{
Greg Claytonc00ca312015-04-02 18:44:58 +00001859 if (m_finalizing)
1860 {
1861 error.SetErrorString("process is tearing itself down");
1862 return LLDB_INVALID_IMAGE_TOKEN;
1863 }
1864
Greg Claytonac7a3db2012-04-18 00:05:19 +00001865 char path[PATH_MAX];
1866 image_spec.GetPath(path, sizeof(path));
1867
Greg Clayton8f343b02010-11-04 01:54:29 +00001868 DynamicLoader *loader = GetDynamicLoader();
1869 if (loader)
1870 {
1871 error = loader->CanLoadImage();
1872 if (error.Fail())
1873 return LLDB_INVALID_IMAGE_TOKEN;
1874 }
1875
1876 if (error.Success())
1877 {
1878 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001879
1880 if (thread_sp)
1881 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001882 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001883
1884 if (frame_sp)
1885 {
1886 ExecutionContext exe_ctx;
1887 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001888 EvaluateExpressionOptions expr_options;
1889 expr_options.SetUnwindOnError(true);
1890 expr_options.SetIgnoreBreakpoints(true);
1891 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001892 expr_options.SetResultIsInternal(true);
1893
Greg Clayton8f343b02010-11-04 01:54:29 +00001894 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001895 expr.Printf(R"(
1896 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1897 the_result.image_ptr = dlopen ("%s", 2);
1898 if (the_result.image_ptr == (void *) 0x0)
1899 {
1900 the_result.error_str = dlerror();
1901 }
1902 else
1903 {
1904 the_result.error_str = (const char *) 0x0;
1905 }
1906 the_result;
1907 )",
1908 path);
1909 const char *prefix = R"(
1910 extern "C" void* dlopen (const char *path, int mode);
1911 extern "C" const char *dlerror (void);
1912 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001913 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001914 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001915 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001916 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001917 expr.GetData(),
1918 prefix,
1919 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001920 expr_error);
1921 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001922 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001923 error = result_valobj_sp->GetError();
1924 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001925 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001926 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001927 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1928 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001929 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001930 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1931 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1932 {
1933 uint32_t image_token = m_image_tokens.size();
1934 m_image_tokens.push_back (image_ptr);
1935 return image_token;
1936 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001937 else if (image_ptr == 0)
1938 {
Jim Ingham6971b862014-07-19 00:37:06 +00001939 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1940 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001941 {
Jim Ingham6971b862014-07-19 00:37:06 +00001942 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001943 {
Enrico Granata2206b482014-10-30 18:27:31 +00001944 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1945 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001946 if (error.Success() && num_chars > 0)
1947 {
1948 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001949 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1950 }
1951 else
1952 {
1953 error.Clear();
1954 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001955 }
1956 }
1957 }
1958 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001959 }
1960 }
1961 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001962 else
1963 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001964 }
1965 }
1966 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001967 if (!error.AsCString())
1968 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001969 return LLDB_INVALID_IMAGE_TOKEN;
1970}
1971
1972//----------------------------------------------------------------------
1973// UnloadImage
1974//
1975// This function provides a default implementation that works for most
1976// unix variants. Any Process subclasses that need to do shared library
1977// loading differently should override LoadImage and UnloadImage and
1978// do what is needed.
1979//----------------------------------------------------------------------
1980Error
1981Process::UnloadImage (uint32_t image_token)
1982{
1983 Error error;
Greg Claytonc00ca312015-04-02 18:44:58 +00001984
1985 if (m_finalizing)
1986 {
1987 error.SetErrorString("process is tearing itself down");
1988 return error;
1989 }
1990
Greg Clayton8f343b02010-11-04 01:54:29 +00001991 if (image_token < m_image_tokens.size())
1992 {
1993 const addr_t image_addr = m_image_tokens[image_token];
1994 if (image_addr == LLDB_INVALID_ADDRESS)
1995 {
1996 error.SetErrorString("image already unloaded");
1997 }
1998 else
1999 {
2000 DynamicLoader *loader = GetDynamicLoader();
2001 if (loader)
2002 error = loader->CanLoadImage();
2003
2004 if (error.Success())
2005 {
2006 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00002007
2008 if (thread_sp)
2009 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002010 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00002011
2012 if (frame_sp)
2013 {
2014 ExecutionContext exe_ctx;
2015 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00002016 EvaluateExpressionOptions expr_options;
2017 expr_options.SetUnwindOnError(true);
2018 expr_options.SetIgnoreBreakpoints(true);
2019 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00002020 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00002021 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00002022 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00002023 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00002024 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00002025 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002026 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00002027 expr.GetData(),
2028 prefix,
2029 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002030 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002031 if (result_valobj_sp->GetError().Success())
2032 {
2033 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002034 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002035 {
2036 if (scalar.UInt(1))
2037 {
2038 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2039 }
2040 else
2041 {
2042 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2043 }
2044 }
2045 }
2046 else
2047 {
2048 error = result_valobj_sp->GetError();
2049 }
2050 }
2051 }
2052 }
2053 }
2054 }
2055 else
2056 {
2057 error.SetErrorString("invalid image token");
2058 }
2059 return error;
2060}
2061
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002062const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002063Process::GetABI()
2064{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002065 if (!m_abi_sp)
2066 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2067 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068}
2069
Jim Ingham22777012010-09-23 02:01:19 +00002070LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002071Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002072{
Greg Claytonc00ca312015-04-02 18:44:58 +00002073 if (m_finalizing)
2074 return nullptr;
2075
Jim Ingham22777012010-09-23 02:01:19 +00002076 LanguageRuntimeCollection::iterator pos;
2077 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002078 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002079 {
Jim Inghamab175242012-03-10 00:22:19 +00002080 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002081
Jim Inghamab175242012-03-10 00:22:19 +00002082 m_language_runtimes[language] = runtime_sp;
2083 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002084 }
2085 else
2086 return (*pos).second.get();
2087}
2088
2089CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002090Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002091{
Jim Inghamab175242012-03-10 00:22:19 +00002092 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002093 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2094 return static_cast<CPPLanguageRuntime *> (runtime);
2095 return NULL;
2096}
2097
2098ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002099Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002100{
Jim Inghamab175242012-03-10 00:22:19 +00002101 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002102 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2103 return static_cast<ObjCLanguageRuntime *> (runtime);
2104 return NULL;
2105}
2106
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002107bool
2108Process::IsPossibleDynamicValue (ValueObject& in_value)
2109{
Greg Claytonc00ca312015-04-02 18:44:58 +00002110 if (m_finalizing)
2111 return false;
2112
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002113 if (in_value.IsDynamic())
2114 return false;
2115 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2116
2117 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2118 {
2119 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2120 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2121 }
2122
2123 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2124 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2125 return true;
2126
2127 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2128 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2129}
2130
Zachary Turner93749ab2015-03-03 21:51:25 +00002131void
2132Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2133{
2134 m_dynamic_checkers_ap.reset(dynamic_checkers);
2135}
2136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002137BreakpointSiteList &
2138Process::GetBreakpointSiteList()
2139{
2140 return m_breakpoint_site_list;
2141}
2142
2143const BreakpointSiteList &
2144Process::GetBreakpointSiteList() const
2145{
2146 return m_breakpoint_site_list;
2147}
2148
2149
2150void
2151Process::DisableAllBreakpointSites ()
2152{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002153 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2154// bp_site->SetEnabled(true);
2155 DisableBreakpointSite(bp_site);
2156 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002157}
2158
2159Error
2160Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2161{
2162 Error error (DisableBreakpointSiteByID (break_id));
2163
2164 if (error.Success())
2165 m_breakpoint_site_list.Remove(break_id);
2166
2167 return error;
2168}
2169
2170Error
2171Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2172{
2173 Error error;
2174 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2175 if (bp_site_sp)
2176 {
2177 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002178 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179 }
2180 else
2181 {
Daniel Malead01b2952012-11-29 21:49:15 +00002182 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183 }
2184
2185 return error;
2186}
2187
2188Error
2189Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2190{
2191 Error error;
2192 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2193 if (bp_site_sp)
2194 {
2195 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002196 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197 }
2198 else
2199 {
Daniel Malead01b2952012-11-29 21:49:15 +00002200 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201 }
2202 return error;
2203}
2204
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002205lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002206Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002208 addr_t load_addr = LLDB_INVALID_ADDRESS;
2209
2210 bool show_error = true;
2211 switch (GetState())
2212 {
2213 case eStateInvalid:
2214 case eStateUnloaded:
2215 case eStateConnected:
2216 case eStateAttaching:
2217 case eStateLaunching:
2218 case eStateDetached:
2219 case eStateExited:
2220 show_error = false;
2221 break;
2222
2223 case eStateStopped:
2224 case eStateRunning:
2225 case eStateStepping:
2226 case eStateCrashed:
2227 case eStateSuspended:
2228 show_error = IsAlive();
2229 break;
2230 }
2231
2232 // Reset the IsIndirect flag here, in case the location changes from
2233 // pointing to a indirect symbol to a regular symbol.
2234 owner->SetIsIndirect (false);
2235
2236 if (owner->ShouldResolveIndirectFunctions())
2237 {
2238 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2239 if (symbol && symbol->IsIndirect())
2240 {
2241 Error error;
2242 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2243 if (!error.Success() && show_error)
2244 {
Greg Clayton44d93782014-01-27 23:43:24 +00002245 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2246 symbol->GetAddress().GetLoadAddress(&m_target),
2247 owner->GetBreakpoint().GetID(),
2248 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002249 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002250 return LLDB_INVALID_BREAK_ID;
2251 }
2252 Address resolved_address(load_addr);
2253 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2254 owner->SetIsIndirect(true);
2255 }
2256 else
2257 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2258 }
2259 else
2260 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2261
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002262 if (load_addr != LLDB_INVALID_ADDRESS)
2263 {
2264 BreakpointSiteSP bp_site_sp;
2265
2266 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2267 // create a new breakpoint site and add it.
2268
2269 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2270
2271 if (bp_site_sp)
2272 {
2273 bp_site_sp->AddOwner (owner);
2274 owner->SetBreakpointSite (bp_site_sp);
2275 return bp_site_sp->GetID();
2276 }
2277 else
2278 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002279 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002280 if (bp_site_sp)
2281 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002282 Error error = EnableBreakpointSite (bp_site_sp.get());
2283 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002284 {
2285 owner->SetBreakpointSite (bp_site_sp);
2286 return m_breakpoint_site_list.Add (bp_site_sp);
2287 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002288 else
2289 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002290 if (show_error)
2291 {
2292 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002293 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2294 load_addr,
2295 owner->GetBreakpoint().GetID(),
2296 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002297 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002298 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002299 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002300 }
2301 }
2302 }
2303 // We failed to enable the breakpoint
2304 return LLDB_INVALID_BREAK_ID;
2305
2306}
2307
2308void
2309Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2310{
2311 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2312 if (num_owners == 0)
2313 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002314 // Don't try to disable the site if we don't have a live process anymore.
2315 if (IsAlive())
2316 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2318 }
2319}
2320
2321
2322size_t
2323Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2324{
2325 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002326 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327
Jim Ingham20c77192011-06-29 19:42:28 +00002328 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002330 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2331 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002333 addr_t intersect_addr;
2334 size_t intersect_size;
2335 size_t opcode_offset;
2336 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002337 {
2338 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2339 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002340 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002341 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002342 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002343 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002345 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 }
2347 return bytes_removed;
2348}
2349
2350
Greg Claytonded470d2011-03-19 01:12:21 +00002351
2352size_t
2353Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2354{
2355 PlatformSP platform_sp (m_target.GetPlatform());
2356 if (platform_sp)
2357 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2358 return 0;
2359}
2360
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361Error
2362Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2363{
2364 Error error;
2365 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002366 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002367 const addr_t bp_addr = bp_site->GetLoadAddress();
2368 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002369 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370 if (bp_site->IsEnabled())
2371 {
2372 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002373 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 +00002374 return error;
2375 }
2376
2377 if (bp_addr == LLDB_INVALID_ADDRESS)
2378 {
2379 error.SetErrorString("BreakpointSite contains an invalid load address.");
2380 return error;
2381 }
2382 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2383 // trap for the breakpoint site
2384 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2385
2386 if (bp_opcode_size == 0)
2387 {
Daniel Malead01b2952012-11-29 21:49:15 +00002388 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002389 }
2390 else
2391 {
2392 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2393
2394 if (bp_opcode_bytes == NULL)
2395 {
2396 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2397 return error;
2398 }
2399
2400 // Save the original opcode by reading it
2401 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2402 {
2403 // Write a software breakpoint in place of the original opcode
2404 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2405 {
2406 uint8_t verify_bp_opcode_bytes[64];
2407 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2408 {
2409 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2410 {
2411 bp_site->SetEnabled(true);
2412 bp_site->SetType (BreakpointSite::eSoftware);
2413 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002414 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002415 bp_site->GetID(),
2416 (uint64_t)bp_addr);
2417 }
2418 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002419 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420 }
2421 else
2422 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2423 }
2424 else
2425 error.SetErrorString("Unable to write breakpoint trap to memory.");
2426 }
2427 else
2428 error.SetErrorString("Unable to read memory at breakpoint address.");
2429 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002430 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002431 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 bp_site->GetID(),
2433 (uint64_t)bp_addr,
2434 error.AsCString());
2435 return error;
2436}
2437
2438Error
2439Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2440{
2441 Error error;
2442 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002443 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002444 addr_t bp_addr = bp_site->GetLoadAddress();
2445 lldb::user_id_t breakID = bp_site->GetID();
2446 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002447 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002448
2449 if (bp_site->IsHardware())
2450 {
2451 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2452 }
2453 else if (bp_site->IsEnabled())
2454 {
2455 const size_t break_op_size = bp_site->GetByteSize();
2456 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2457 if (break_op_size > 0)
2458 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002459 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002460 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002461 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462 bool break_op_found = false;
2463
2464 // Read the breakpoint opcode
2465 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2466 {
2467 bool verify = false;
2468 // Make sure we have the a breakpoint opcode exists at this address
2469 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2470 {
2471 break_op_found = true;
2472 // We found a valid breakpoint opcode at this address, now restore
2473 // the saved opcode.
2474 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2475 {
2476 verify = true;
2477 }
2478 else
2479 error.SetErrorString("Memory write failed when restoring original opcode.");
2480 }
2481 else
2482 {
2483 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2484 // Set verify to true and so we can check if the original opcode has already been restored
2485 verify = true;
2486 }
2487
2488 if (verify)
2489 {
Greg Claytonc982c762010-07-09 20:39:50 +00002490 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002491 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492 // Verify that our original opcode made it back to the inferior
2493 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2494 {
2495 // compare the memory we just read with the original opcode
2496 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2497 {
2498 // SUCCESS
2499 bp_site->SetEnabled(false);
2500 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002501 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 +00002502 return error;
2503 }
2504 else
2505 {
2506 if (break_op_found)
2507 error.SetErrorString("Failed to restore original opcode.");
2508 }
2509 }
2510 else
2511 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2512 }
2513 }
2514 else
2515 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2516 }
2517 }
2518 else
2519 {
2520 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002521 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 +00002522 return error;
2523 }
2524
2525 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002526 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002527 bp_site->GetID(),
2528 (uint64_t)bp_addr,
2529 error.AsCString());
2530 return error;
2531
2532}
2533
Greg Clayton58be07b2011-01-07 06:08:19 +00002534// Uncomment to verify memory caching works after making changes to caching code
2535//#define VERIFY_MEMORY_READS
2536
Sean Callanan64c0cf22012-06-07 22:26:42 +00002537size_t
2538Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2539{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002540 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002541 if (!GetDisableMemoryCache())
2542 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002543#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002544 // Memory caching is enabled, with debug verification
2545
2546 if (buf && size)
2547 {
2548 // Uncomment the line below to make sure memory caching is working.
2549 // I ran this through the test suite and got no assertions, so I am
2550 // pretty confident this is working well. If any changes are made to
2551 // memory caching, uncomment the line below and test your changes!
2552
2553 // Verify all memory reads by using the cache first, then redundantly
2554 // reading the same memory from the inferior and comparing to make sure
2555 // everything is exactly the same.
2556 std::string verify_buf (size, '\0');
2557 assert (verify_buf.size() == size);
2558 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2559 Error verify_error;
2560 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2561 assert (cache_bytes_read == verify_bytes_read);
2562 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2563 assert (verify_error.Success() == error.Success());
2564 return cache_bytes_read;
2565 }
2566 return 0;
2567#else // !defined(VERIFY_MEMORY_READS)
2568 // Memory caching is enabled, without debug verification
2569
2570 return m_memory_cache.Read (addr, buf, size, error);
2571#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002572 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002573 else
2574 {
2575 // Memory caching is disabled
2576
2577 return ReadMemoryFromInferior (addr, buf, size, error);
2578 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002579}
Greg Clayton58be07b2011-01-07 06:08:19 +00002580
Greg Clayton4c82d422012-05-18 23:20:01 +00002581size_t
2582Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2583{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002584 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002585 out_str.clear();
2586 addr_t curr_addr = addr;
2587 while (1)
2588 {
2589 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2590 if (length == 0)
2591 break;
2592 out_str.append(buf, length);
2593 // If we got "length - 1" bytes, we didn't get the whole C string, we
2594 // need to read some more characters
2595 if (length == sizeof(buf) - 1)
2596 curr_addr += length;
2597 else
2598 break;
2599 }
2600 return out_str.size();
2601}
2602
Greg Clayton58be07b2011-01-07 06:08:19 +00002603
2604size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002605Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2606 size_t type_width)
2607{
2608 size_t total_bytes_read = 0;
2609 if (dst && max_bytes && type_width && max_bytes >= type_width)
2610 {
2611 // Ensure a null terminator independent of the number of bytes that is read.
2612 memset (dst, 0, max_bytes);
2613 size_t bytes_left = max_bytes - type_width;
2614
2615 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2616 assert(sizeof(terminator) >= type_width &&
2617 "Attempting to validate a string with more than 4 bytes per character!");
2618
2619 addr_t curr_addr = addr;
2620 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2621 char *curr_dst = dst;
2622
2623 error.Clear();
2624 while (bytes_left > 0 && error.Success())
2625 {
2626 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2627 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2628 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2629
2630 if (bytes_read == 0)
2631 break;
2632
2633 // Search for a null terminator of correct size and alignment in bytes_read
2634 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2635 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2636 if (::strncmp(&dst[i], terminator, type_width) == 0)
2637 {
2638 error.Clear();
2639 return i;
2640 }
2641
2642 total_bytes_read += bytes_read;
2643 curr_dst += bytes_read;
2644 curr_addr += bytes_read;
2645 bytes_left -= bytes_read;
2646 }
2647 }
2648 else
2649 {
2650 if (max_bytes)
2651 error.SetErrorString("invalid arguments");
2652 }
2653 return total_bytes_read;
2654}
2655
2656// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2657// null terminators.
2658size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002659Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002660{
2661 size_t total_cstr_len = 0;
2662 if (dst && dst_max_len)
2663 {
Greg Claytone91b7952011-12-15 03:14:23 +00002664 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002665 // NULL out everything just to be safe
2666 memset (dst, 0, dst_max_len);
2667 Error error;
2668 addr_t curr_addr = addr;
2669 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2670 size_t bytes_left = dst_max_len - 1;
2671 char *curr_dst = dst;
2672
2673 while (bytes_left > 0)
2674 {
2675 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2676 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2677 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2678
2679 if (bytes_read == 0)
2680 {
Greg Claytone91b7952011-12-15 03:14:23 +00002681 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002682 dst[total_cstr_len] = '\0';
2683 break;
2684 }
2685 const size_t len = strlen(curr_dst);
2686
2687 total_cstr_len += len;
2688
2689 if (len < bytes_to_read)
2690 break;
2691
2692 curr_dst += bytes_read;
2693 curr_addr += bytes_read;
2694 bytes_left -= bytes_read;
2695 }
2696 }
Greg Claytone91b7952011-12-15 03:14:23 +00002697 else
2698 {
2699 if (dst == NULL)
2700 result_error.SetErrorString("invalid arguments");
2701 else
2702 result_error.Clear();
2703 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002704 return total_cstr_len;
2705}
2706
2707size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002708Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2709{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710 if (buf == NULL || size == 0)
2711 return 0;
2712
2713 size_t bytes_read = 0;
2714 uint8_t *bytes = (uint8_t *)buf;
2715
2716 while (bytes_read < size)
2717 {
2718 const size_t curr_size = size - bytes_read;
2719 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2720 bytes + bytes_read,
2721 curr_size,
2722 error);
2723 bytes_read += curr_bytes_read;
2724 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2725 break;
2726 }
2727
2728 // Replace any software breakpoint opcodes that fall into this range back
2729 // into "buf" before we return
2730 if (bytes_read > 0)
2731 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2732 return bytes_read;
2733}
2734
Greg Clayton58a4c462010-12-16 20:01:20 +00002735uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002736Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002737{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002738 Scalar scalar;
2739 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2740 return scalar.ULongLong(fail_value);
2741 return fail_value;
2742}
2743
2744addr_t
2745Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2746{
2747 Scalar scalar;
2748 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2749 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2750 return LLDB_INVALID_ADDRESS;
2751}
2752
2753
2754bool
2755Process::WritePointerToMemory (lldb::addr_t vm_addr,
2756 lldb::addr_t ptr_value,
2757 Error &error)
2758{
2759 Scalar scalar;
2760 const uint32_t addr_byte_size = GetAddressByteSize();
2761 if (addr_byte_size <= 4)
2762 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002763 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002764 scalar = ptr_value;
2765 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002766}
2767
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002768size_t
2769Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2770{
2771 size_t bytes_written = 0;
2772 const uint8_t *bytes = (const uint8_t *)buf;
2773
2774 while (bytes_written < size)
2775 {
2776 const size_t curr_size = size - bytes_written;
2777 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2778 bytes + bytes_written,
2779 curr_size,
2780 error);
2781 bytes_written += curr_bytes_written;
2782 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2783 break;
2784 }
2785 return bytes_written;
2786}
2787
2788size_t
2789Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2790{
Greg Clayton58be07b2011-01-07 06:08:19 +00002791#if defined (ENABLE_MEMORY_CACHING)
2792 m_memory_cache.Flush (addr, size);
2793#endif
2794
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795 if (buf == NULL || size == 0)
2796 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002797
Jim Ingham4b536182011-08-09 02:12:22 +00002798 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002799
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800 // We need to write any data that would go where any current software traps
2801 // (enabled software breakpoints) any software traps (breakpoints) that we
2802 // may have placed in our tasks memory.
2803
Greg Claytond8cf1a12013-06-12 00:46:38 +00002804 BreakpointSiteList bp_sites_in_range;
2805
2806 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002808 // No breakpoint sites overlap
2809 if (bp_sites_in_range.IsEmpty())
2810 return WriteMemoryPrivate (addr, buf, size, error);
2811 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002813 const uint8_t *ubuf = (const uint8_t *)buf;
2814 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815
Greg Claytond8cf1a12013-06-12 00:46:38 +00002816 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2817
2818 if (error.Success())
2819 {
2820 addr_t intersect_addr;
2821 size_t intersect_size;
2822 size_t opcode_offset;
2823 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2824 assert(intersects);
2825 assert(addr <= intersect_addr && intersect_addr < addr + size);
2826 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2827 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2828
2829 // Check for bytes before this breakpoint
2830 const addr_t curr_addr = addr + bytes_written;
2831 if (intersect_addr > curr_addr)
2832 {
2833 // There are some bytes before this breakpoint that we need to
2834 // just write to memory
2835 size_t curr_size = intersect_addr - curr_addr;
2836 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2837 ubuf + bytes_written,
2838 curr_size,
2839 error);
2840 bytes_written += curr_bytes_written;
2841 if (curr_bytes_written != curr_size)
2842 {
2843 // We weren't able to write all of the requested bytes, we
2844 // are done looping and will return the number of bytes that
2845 // we have written so far.
2846 if (error.Success())
2847 error.SetErrorToGenericError();
2848 }
2849 }
2850 // Now write any bytes that would cover up any software breakpoints
2851 // directly into the breakpoint opcode buffer
2852 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2853 bytes_written += intersect_size;
2854 }
2855 });
2856
2857 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002858 WriteMemoryPrivate (addr + bytes_written,
2859 ubuf + bytes_written,
2860 size - bytes_written,
2861 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002862 }
2863 }
2864 else
2865 {
2866 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002867 }
2868
2869 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002870 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002871}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002872
2873size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002874Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002875{
2876 if (byte_size == UINT32_MAX)
2877 byte_size = scalar.GetByteSize();
2878 if (byte_size > 0)
2879 {
2880 uint8_t buf[32];
2881 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2882 if (mem_size > 0)
2883 return WriteMemory(addr, buf, mem_size, error);
2884 else
2885 error.SetErrorString ("failed to get scalar as memory data");
2886 }
2887 else
2888 {
2889 error.SetErrorString ("invalid scalar value");
2890 }
2891 return 0;
2892}
2893
2894size_t
2895Process::ReadScalarIntegerFromMemory (addr_t addr,
2896 uint32_t byte_size,
2897 bool is_signed,
2898 Scalar &scalar,
2899 Error &error)
2900{
Greg Clayton7060f892013-05-01 23:41:30 +00002901 uint64_t uval = 0;
2902 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002903 {
Greg Clayton7060f892013-05-01 23:41:30 +00002904 error.SetErrorString ("byte size is zero");
2905 }
2906 else if (byte_size & (byte_size - 1))
2907 {
2908 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2909 }
2910 else if (byte_size <= sizeof(uval))
2911 {
2912 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002913 if (bytes_read == byte_size)
2914 {
2915 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002916 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002917 if (byte_size <= 4)
2918 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002919 else
Greg Clayton7060f892013-05-01 23:41:30 +00002920 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002921 if (is_signed)
2922 scalar.SignExtend(byte_size * 8);
2923 return bytes_read;
2924 }
2925 }
2926 else
2927 {
2928 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2929 }
2930 return 0;
2931}
2932
Greg Claytond495c532011-05-17 03:37:42 +00002933#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002934addr_t
2935Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2936{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002937 if (GetPrivateState() != eStateStopped)
2938 return LLDB_INVALID_ADDRESS;
2939
Greg Claytond495c532011-05-17 03:37:42 +00002940#if defined (USE_ALLOCATE_MEMORY_CACHE)
2941 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2942#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002943 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002944 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002945 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002946 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 +00002947 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002948 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002949 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002950 m_mod_id.GetStopID(),
2951 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002952 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002953#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954}
2955
Sean Callanan90539452011-09-20 23:01:51 +00002956bool
2957Process::CanJIT ()
2958{
Sean Callanana7b443a2012-02-14 22:50:38 +00002959 if (m_can_jit == eCanJITDontKnow)
2960 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002961 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002962 Error err;
2963
2964 uint64_t allocated_memory = AllocateMemory(8,
2965 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2966 err);
2967
2968 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002969 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002970 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002971 if (log)
2972 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2973 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002974 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002975 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002976 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002977 if (log)
2978 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2979 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002980
2981 DeallocateMemory (allocated_memory);
2982 }
2983
Sean Callanan90539452011-09-20 23:01:51 +00002984 return m_can_jit == eCanJITYes;
2985}
2986
2987void
2988Process::SetCanJIT (bool can_jit)
2989{
2990 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2991}
2992
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002993Error
2994Process::DeallocateMemory (addr_t ptr)
2995{
Greg Claytond495c532011-05-17 03:37:42 +00002996 Error error;
2997#if defined (USE_ALLOCATE_MEMORY_CACHE)
2998 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2999 {
Daniel Malead01b2952012-11-29 21:49:15 +00003000 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00003001 }
3002#else
3003 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00003004
Greg Clayton5160ce52013-03-27 23:08:40 +00003005 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00003006 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003007 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 +00003008 ptr,
3009 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00003010 m_mod_id.GetStopID(),
3011 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00003012#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00003013 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014}
3015
Han Ming Ongc811d382012-11-17 00:33:14 +00003016
Greg Claytonc9660542012-02-05 02:38:54 +00003017ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00003018Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00003019 lldb::addr_t header_addr,
3020 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00003021{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003022 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00003023 if (module_sp)
3024 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003025 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00003026 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003027 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003028 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00003029 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003030 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00003031}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032
Zachary Turner93749ab2015-03-03 21:51:25 +00003033bool
3034Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3035{
3036 MemoryRegionInfo range_info;
3037 permissions = 0;
3038 Error error (GetMemoryRegionInfo (load_addr, range_info));
3039 if (!error.Success())
3040 return false;
3041 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3042 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3043 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3044 {
3045 return false;
3046 }
3047
3048 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3049 permissions |= lldb::ePermissionsReadable;
3050
3051 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3052 permissions |= lldb::ePermissionsWritable;
3053
3054 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3055 permissions |= lldb::ePermissionsExecutable;
3056
3057 return true;
3058}
3059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003061Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062{
3063 Error error;
3064 error.SetErrorString("watchpoints are not supported");
3065 return error;
3066}
3067
3068Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003069Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003070{
3071 Error error;
3072 error.SetErrorString("watchpoints are not supported");
3073 return error;
3074}
3075
3076StateType
3077Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3078{
3079 StateType state;
3080 // Now wait for the process to launch and return control to us, and then
3081 // call DidLaunch:
3082 while (1)
3083 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003084 event_sp.reset();
3085 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3086
Greg Clayton2637f822011-11-17 01:23:07 +00003087 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003089
3090 // If state is invalid, then we timed out
3091 if (state == eStateInvalid)
3092 break;
3093
3094 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003095 HandlePrivateEvent (event_sp);
3096 }
3097 return state;
3098}
3099
Greg Clayton332e8b12015-01-13 21:13:08 +00003100void
3101Process::LoadOperatingSystemPlugin(bool flush)
3102{
3103 if (flush)
3104 m_thread_list.Clear();
3105 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3106 if (flush)
3107 Flush();
3108}
3109
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003111Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112{
3113 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003114 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003115 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003116 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003117 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003118 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003119 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003120 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121
Greg Claytonaa149cb2011-08-11 02:48:45 +00003122 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 if (exe_module)
3124 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003125 char local_exec_file_path[PATH_MAX];
3126 char platform_exec_file_path[PATH_MAX];
3127 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3128 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129 if (exe_module->GetFileSpec().Exists())
3130 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003131 // Install anything that might need to be installed prior to launching.
3132 // For host systems, this will do nothing, but if we are connected to a
3133 // remote platform it will install any needed binaries
3134 error = GetTarget().Install(&launch_info);
3135 if (error.Fail())
3136 return error;
3137
Greg Clayton71337622011-02-24 22:24:29 +00003138 if (PrivateStateThreadIsValid ())
3139 PausePrivateStateThread ();
3140
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 error = WillLaunch (exe_module);
3142 if (error.Success())
3143 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003144 const bool restarted = false;
3145 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003146 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147
Ed Maste64fad602013-07-29 20:58:06 +00003148 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003149 {
3150 // Now launch using these arguments.
3151 error = DoLaunch (exe_module, launch_info);
3152 }
3153 else
3154 {
3155 // This shouldn't happen
3156 error.SetErrorString("failed to acquire process run lock");
3157 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158
3159 if (error.Fail())
3160 {
3161 if (GetID() != LLDB_INVALID_PROCESS_ID)
3162 {
3163 SetID (LLDB_INVALID_PROCESS_ID);
3164 const char *error_string = error.AsCString();
3165 if (error_string == NULL)
3166 error_string = "launch failed";
3167 SetExitStatus (-1, error_string);
3168 }
3169 }
3170 else
3171 {
3172 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003173 TimeValue timeout_time;
3174 timeout_time = TimeValue::Now();
3175 timeout_time.OffsetWithSeconds(10);
3176 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003177
Greg Clayton1a38ea72011-06-22 01:42:17 +00003178 if (state == eStateInvalid || event_sp.get() == NULL)
3179 {
3180 // We were able to launch the process, but we failed to
3181 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003182 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003183 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003184 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003185 }
3186 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003188
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003189 DidLaunch ();
3190
Greg Claytonc859e2d2012-02-13 23:10:39 +00003191 DynamicLoader *dyld = GetDynamicLoader ();
3192 if (dyld)
3193 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003194
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003195 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003196
Jason Molendaeef51062013-11-05 03:57:19 +00003197 SystemRuntime *system_runtime = GetSystemRuntime ();
3198 if (system_runtime)
3199 system_runtime->DidLaunch();
3200
Greg Clayton332e8b12015-01-13 21:13:08 +00003201 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003202
3203 // Note, the stop event was consumed above, but not handled. This was done
3204 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3205 // Directly set the state. This is done to prevent a stop message with a bunch
3206 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3207 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003208
3209 if (PrivateStateThreadIsValid ())
3210 ResumePrivateStateThread ();
3211 else
3212 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003213
3214 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003215
3216 // Target was stopped at entry as was intended. Need to notify the listeners
3217 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003218 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003219 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003220 }
3221 else if (state == eStateExited)
3222 {
3223 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3224 // not likely to work, and return an invalid pid.
3225 HandlePrivateEvent (event_sp);
3226 }
3227 }
3228 }
3229 }
3230 else
3231 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003232 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 }
3234 }
3235 return error;
3236}
3237
Greg Claytonc3776bf2012-02-09 06:16:32 +00003238
3239Error
3240Process::LoadCore ()
3241{
3242 Error error = DoLoadCore();
3243 if (error.Success())
3244 {
Greg Clayton35824e32015-02-20 20:59:47 +00003245 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003246 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003247
Greg Claytonc3776bf2012-02-09 06:16:32 +00003248 if (PrivateStateThreadIsValid ())
3249 ResumePrivateStateThread ();
3250 else
3251 StartPrivateStateThread ();
3252
Greg Claytonc859e2d2012-02-13 23:10:39 +00003253 DynamicLoader *dyld = GetDynamicLoader ();
3254 if (dyld)
3255 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003256
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003257 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003258
Jason Molendaeef51062013-11-05 03:57:19 +00003259 SystemRuntime *system_runtime = GetSystemRuntime ();
3260 if (system_runtime)
3261 system_runtime->DidAttach();
3262
Greg Claytonc859e2d2012-02-13 23:10:39 +00003263 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003264 // We successfully loaded a core file, now pretend we stopped so we can
3265 // show all of the threads in the core file and explore the crashed
3266 // state.
3267 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003268
3269 // Wait indefinitely for a stopped event since we just posted one above...
3270 lldb::EventSP event_sp;
3271 listener.WaitForEvent (NULL, event_sp);
3272 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3273
3274 if (!StateIsStoppedState (state, false))
3275 {
3276 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3277 if (log)
3278 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3279 error.SetErrorString ("Did not get stopped event after loading the core file.");
3280 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003281 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003282 }
3283 return error;
3284}
3285
Greg Claytonc859e2d2012-02-13 23:10:39 +00003286DynamicLoader *
3287Process::GetDynamicLoader ()
3288{
3289 if (m_dyld_ap.get() == NULL)
3290 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3291 return m_dyld_ap.get();
3292}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003293
Todd Fialaaf245d12014-06-30 21:05:18 +00003294const lldb::DataBufferSP
3295Process::GetAuxvData()
3296{
3297 return DataBufferSP ();
3298}
3299
Andrew MacPherson17220c12014-03-05 10:12:43 +00003300JITLoaderList &
3301Process::GetJITLoaders ()
3302{
3303 if (!m_jit_loaders_ap)
3304 {
3305 m_jit_loaders_ap.reset(new JITLoaderList());
3306 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3307 }
3308 return *m_jit_loaders_ap;
3309}
3310
Jason Molendaeef51062013-11-05 03:57:19 +00003311SystemRuntime *
3312Process::GetSystemRuntime ()
3313{
3314 if (m_system_runtime_ap.get() == NULL)
3315 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3316 return m_system_runtime_ap.get();
3317}
3318
Todd Fiala76e0fc92014-08-27 22:58:26 +00003319Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3320 NextEventAction (process),
3321 m_exec_count (exec_count)
3322{
3323 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3324 if (log)
3325 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3326}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003327
Jim Inghambb3a2832011-01-29 01:49:25 +00003328Process::NextEventAction::EventActionResult
3329Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003331 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3332
Jim Inghambb3a2832011-01-29 01:49:25 +00003333 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003334 if (log)
3335 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3336
3337 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003338 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003339 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003340 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003341 return eEventActionRetry;
3342
3343 case eStateStopped:
3344 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003345 {
3346 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003347 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003348 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003349 // We don't want these events to be reported, so go set the ShouldReportStop here:
3350 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3351
Greg Claytonc9ed4782011-11-12 02:10:56 +00003352 if (m_exec_count > 0)
3353 {
3354 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003355
3356 if (log)
3357 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3358
Jim Ingham221d51c2013-05-08 00:35:16 +00003359 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003360 return eEventActionRetry;
3361 }
3362 else
3363 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003364 if (log)
3365 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3366
Greg Claytonc9ed4782011-11-12 02:10:56 +00003367 m_process->CompleteAttach ();
3368 return eEventActionSuccess;
3369 }
3370 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003371 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003372
Greg Clayton513c26c2011-01-29 07:10:55 +00003373 default:
3374 case eStateExited:
3375 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003376 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003377 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003378
3379 m_exit_string.assign ("No valid Process");
3380 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003381}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003382
Jim Inghambb3a2832011-01-29 01:49:25 +00003383Process::NextEventAction::EventActionResult
3384Process::AttachCompletionHandler::HandleBeingInterrupted()
3385{
3386 return eEventActionSuccess;
3387}
3388
3389const char *
3390Process::AttachCompletionHandler::GetExitString ()
3391{
3392 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393}
3394
Greg Clayton8012cad2014-11-17 19:39:20 +00003395Listener &
3396ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3397{
3398 if (m_listener_sp)
3399 return *m_listener_sp;
3400 else
3401 return debugger.GetListener();
3402}
3403
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003405Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003407 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003408 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003409 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003410 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003411 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003412 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003413 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003414
Greg Clayton144f3a92011-11-15 03:53:30 +00003415 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003416 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003417 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003418 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003419 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003420
Greg Clayton144f3a92011-11-15 03:53:30 +00003421 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003422 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003423 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3424
3425 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003426 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003427 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3428 if (error.Success())
3429 {
Ed Maste64fad602013-07-29 20:58:06 +00003430 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003431 {
3432 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003433 const bool restarted = false;
3434 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003435 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003436 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003437 }
3438 else
3439 {
3440 // This shouldn't happen
3441 error.SetErrorString("failed to acquire process run lock");
3442 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003443
Greg Clayton144f3a92011-11-15 03:53:30 +00003444 if (error.Fail())
3445 {
3446 if (GetID() != LLDB_INVALID_PROCESS_ID)
3447 {
3448 SetID (LLDB_INVALID_PROCESS_ID);
3449 if (error.AsCString() == NULL)
3450 error.SetErrorString("attach failed");
3451
3452 SetExitStatus(-1, error.AsCString());
3453 }
3454 }
3455 else
3456 {
3457 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3458 StartPrivateStateThread();
3459 }
3460 return error;
3461 }
Greg Claytone996fd32011-03-08 22:40:15 +00003462 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003463 else
Greg Claytone996fd32011-03-08 22:40:15 +00003464 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003465 ProcessInstanceInfoList process_infos;
3466 PlatformSP platform_sp (m_target.GetPlatform ());
3467
3468 if (platform_sp)
3469 {
3470 ProcessInstanceInfoMatch match_info;
3471 match_info.GetProcessInfo() = attach_info;
3472 match_info.SetNameMatchType (eNameMatchEquals);
3473 platform_sp->FindProcesses (match_info, process_infos);
3474 const uint32_t num_matches = process_infos.GetSize();
3475 if (num_matches == 1)
3476 {
3477 attach_pid = process_infos.GetProcessIDAtIndex(0);
3478 // Fall through and attach using the above process ID
3479 }
3480 else
3481 {
3482 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3483 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003484 {
3485 StreamString s;
3486 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3487 for (size_t i = 0; i < num_matches; i++)
3488 {
3489 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3490 }
3491 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3492 process_name,
3493 s.GetData());
3494 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003495 else
3496 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3497 }
3498 }
3499 else
3500 {
3501 error.SetErrorString ("invalid platform, can't find processes by name");
3502 return error;
3503 }
Greg Claytone996fd32011-03-08 22:40:15 +00003504 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003505 }
3506 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003507 {
3508 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003509 }
3510 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003511
3512 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003513 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003514 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003515 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003516 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003517
Ed Maste64fad602013-07-29 20:58:06 +00003518 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003519 {
3520 // Now attach using these arguments.
3521 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003522 const bool restarted = false;
3523 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003524 error = DoAttachToProcessWithID (attach_pid, attach_info);
3525 }
3526 else
3527 {
3528 // This shouldn't happen
3529 error.SetErrorString("failed to acquire process run lock");
3530 }
3531
Greg Clayton144f3a92011-11-15 03:53:30 +00003532 if (error.Success())
3533 {
3534
3535 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3536 StartPrivateStateThread();
3537 }
3538 else
Greg Claytone996fd32011-03-08 22:40:15 +00003539 {
3540 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003541 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003542
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003543 const char *error_string = error.AsCString();
3544 if (error_string == NULL)
3545 error_string = "attach failed";
3546
3547 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003549 }
3550 }
3551 return error;
3552}
3553
Greg Clayton93d3c8332011-02-16 04:46:07 +00003554void
3555Process::CompleteAttach ()
3556{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003557 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3558 if (log)
3559 log->Printf ("Process::%s()", __FUNCTION__);
3560
Greg Clayton93d3c8332011-02-16 04:46:07 +00003561 // Let the process subclass figure out at much as it can about the process
3562 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003563 ArchSpec process_arch;
3564 DidAttach(process_arch);
3565
3566 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003567 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003568 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003569 if (log)
3570 {
3571 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3572 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3573 __FUNCTION__,
3574 triple_str ? triple_str : "<null>");
3575 }
3576 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003577
Jim Ingham4299fdb2011-09-15 01:10:17 +00003578 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3579 // the same as the one we've already set, switch architectures.
3580 PlatformSP platform_sp (m_target.GetPlatform ());
3581 assert (platform_sp.get());
3582 if (platform_sp)
3583 {
Greg Clayton70512312012-05-08 01:45:38 +00003584 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003585 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003586 {
3587 ArchSpec platform_arch;
3588 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3589 if (platform_sp)
3590 {
3591 m_target.SetPlatform (platform_sp);
3592 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003593 if (log)
3594 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 +00003595 }
3596 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003597 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003598 {
3599 ProcessInstanceInfo process_info;
3600 platform_sp->GetProcessInfo (GetID(), process_info);
3601 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003602 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003603 {
Greg Clayton70512312012-05-08 01:45:38 +00003604 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003605 if (log)
3606 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 ());
3607 }
Greg Clayton70512312012-05-08 01:45:38 +00003608 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003609 }
3610
3611 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003612 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003613 DynamicLoader *dyld = GetDynamicLoader ();
3614 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003615 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003616 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003617 if (log)
3618 {
3619 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3620 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3621 __FUNCTION__,
3622 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3623 dyld->GetPluginName().AsCString ("<unnamed>"));
3624 }
3625 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003626
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003627 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003628
Jason Molendaeef51062013-11-05 03:57:19 +00003629 SystemRuntime *system_runtime = GetSystemRuntime ();
3630 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003631 {
Jason Molendaeef51062013-11-05 03:57:19 +00003632 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003633 if (log)
3634 {
3635 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3636 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3637 __FUNCTION__,
3638 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3639 system_runtime->GetPluginName().AsCString("<unnamed>"));
3640 }
3641 }
Jason Molendaeef51062013-11-05 03:57:19 +00003642
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003643 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003644 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003645 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003646 Mutex::Locker modules_locker(target_modules.GetMutex());
3647 size_t num_modules = target_modules.GetSize();
3648 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003649
Andy Gibbsa297a972013-06-19 19:04:53 +00003650 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003651 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003652 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003653 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003654 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003655 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003656 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003657 break;
3658 }
3659 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003660 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003661 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003662 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003663 if (log)
3664 {
3665 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3666 log->Printf ("Process::%s after looping through modules, target executable is %s",
3667 __FUNCTION__,
3668 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3669 }
3670 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003671
3672 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003673}
3674
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003676Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003677{
Greg Claytonb766a732011-02-04 01:58:07 +00003678 m_abi_sp.reset();
3679 m_process_input_reader.reset();
3680
3681 // Find the process and its architecture. Make sure it matches the architecture
3682 // of the current Target, and if not adjust it.
3683
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003684 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003685 if (error.Success())
3686 {
Greg Clayton71337622011-02-24 22:24:29 +00003687 if (GetID() != LLDB_INVALID_PROCESS_ID)
3688 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003689 EventSP event_sp;
3690 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3691
3692 if (state == eStateStopped || state == eStateCrashed)
3693 {
3694 // If we attached and actually have a process on the other end, then
3695 // this ended up being the equivalent of an attach.
3696 CompleteAttach ();
3697
3698 // This delays passing the stopped event to listeners till
3699 // CompleteAttach gets a chance to complete...
3700 HandlePrivateEvent (event_sp);
3701
3702 }
Greg Clayton71337622011-02-24 22:24:29 +00003703 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003704
3705 if (PrivateStateThreadIsValid ())
3706 ResumePrivateStateThread ();
3707 else
3708 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003709 }
3710 return error;
3711}
3712
3713
3714Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003715Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003716{
Greg Clayton5160ce52013-03-27 23:08:40 +00003717 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003718 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003719 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003720 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003721 StateAsCString(m_public_state.GetValue()),
3722 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723
3724 Error error (WillResume());
3725 // Tell the process it is about to resume before the thread list
3726 if (error.Success())
3727 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003728 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729 // can let all of our threads know that they are about to be
3730 // resumed. Threads will each be called with
3731 // Thread::WillResume(StateType) where StateType contains the state
3732 // that they are supposed to have when the process is resumed
3733 // (suspended/running/stepping). Threads should also check
3734 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003735 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736 if (m_thread_list.WillResume())
3737 {
Jim Ingham372787f2012-04-07 00:00:41 +00003738 // Last thing, do the PreResumeActions.
3739 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003740 {
Jim Ingham0161b492013-02-09 01:29:05 +00003741 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003742 }
3743 else
3744 {
3745 m_mod_id.BumpResumeID();
3746 error = DoResume();
3747 if (error.Success())
3748 {
3749 DidResume();
3750 m_thread_list.DidResume();
3751 if (log)
3752 log->Printf ("Process thinks the process has resumed.");
3753 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003754 }
3755 }
3756 else
3757 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003758 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3759 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003760 // and let the world handle them.
3761 if (log)
3762 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3763
3764 SetPrivateState(eStateRunning);
3765 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003766 }
3767 }
Jim Ingham444586b2011-01-24 06:34:17 +00003768 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003769 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770 return error;
3771}
3772
3773Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003774Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003776 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3777 // in case it was already set and some thread plan logic calls halt on its
3778 // own.
3779 m_clear_thread_plans_on_stop |= clear_thread_plans;
3780
Jim Inghamaacc3182012-06-06 00:29:30 +00003781 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3782 // we could just straightaway get another event. It just narrows the window...
3783 m_currently_handling_event.WaitForValueEqualTo(false);
3784
3785
Jim Inghambb3a2832011-01-29 01:49:25 +00003786 // Pause our private state thread so we can ensure no one else eats
3787 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003788 Listener halt_listener ("lldb.process.halt_listener");
3789 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003790
Jim Inghambb3a2832011-01-29 01:49:25 +00003791 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003792 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003793
Greg Clayton06357c92014-07-30 17:38:47 +00003794 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003795 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003796 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003797
Greg Clayton513c26c2011-01-29 07:10:55 +00003798 bool caused_stop = false;
3799
3800 // Ask the process subclass to actually halt our process
3801 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003803 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003804 if (m_public_state.GetValue() == eStateAttaching)
3805 {
Greg Clayton06357c92014-07-30 17:38:47 +00003806 // Don't hijack and eat the eStateExited as the code that was doing
3807 // the attach will be waiting for this event...
3808 RestorePrivateProcessEvents();
3809 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003810 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:58 +00003811 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:55 +00003812 }
3813 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003814 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003815 // If "caused_stop" is true, then DoHalt stopped the process. If
3816 // "caused_stop" is false, the process was already stopped.
3817 // If the DoHalt caused the process to stop, then we want to catch
3818 // this event and set the interrupted bool to true before we pass
3819 // this along so clients know that the process was interrupted by
3820 // a halt command.
3821 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003822 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003823 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003824 TimeValue timeout_time;
3825 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003826 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003827 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3828 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003829
Jim Ingham0f16e732011-02-08 05:20:59 +00003830 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003831 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003832 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003833 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003834 }
3835 else
3836 {
Greg Clayton2637f822011-11-17 01:23:07 +00003837 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003838 {
3839 // We caused the process to interrupt itself, so mark this
3840 // as such in the stop event so clients can tell an interrupted
3841 // process from a natural stop
3842 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3843 }
3844 else
3845 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003846 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003847 if (log)
3848 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3849 error.SetErrorString ("Did not get stopped event after halt.");
3850 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003851 }
3852 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003853 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003854 }
3855 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003856 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003857 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003858 if (!restored_process_events)
3859 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003860
3861 // Post any event we might have consumed. If all goes well, we will have
3862 // stopped the process, intercepted the event and set the interrupted
3863 // bool in the event. Post it to the private event queue and that will end up
3864 // correctly setting the state.
3865 if (event_sp)
3866 m_private_state_broadcaster.BroadcastEvent(event_sp);
3867
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868 return error;
3869}
3870
3871Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003872Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3873{
3874 Error error;
3875 if (m_public_state.GetValue() == eStateRunning)
3876 {
3877 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3878 if (log)
3879 log->Printf("Process::Destroy() About to halt.");
3880 error = Halt();
3881 if (error.Success())
3882 {
3883 // Consume the halt event.
3884 TimeValue timeout (TimeValue::Now());
3885 timeout.OffsetWithSeconds(1);
3886 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3887
3888 // If the process exited while we were waiting for it to stop, put the exited event into
3889 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3890 // they don't have a process anymore...
3891
3892 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3893 {
3894 if (log)
3895 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3896 return error;
3897 }
3898 else
3899 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3900
3901 if (state != eStateStopped)
3902 {
3903 if (log)
3904 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3905 // If we really couldn't stop the process then we should just error out here, but if the
3906 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3907 StateType private_state = m_private_state.GetValue();
3908 if (private_state != eStateStopped)
3909 {
3910 return error;
3911 }
3912 }
3913 }
3914 else
3915 {
3916 if (log)
3917 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3918 }
3919 }
3920 return error;
3921}
3922
3923Error
Jim Inghamacff8952013-05-02 00:27:30 +00003924Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003925{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003926 EventSP exit_event_sp;
3927 Error error;
3928 m_destroy_in_process = true;
3929
3930 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003931
3932 if (error.Success())
3933 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003934 if (DetachRequiresHalt())
3935 {
3936 error = HaltForDestroyOrDetach (exit_event_sp);
3937 if (!error.Success())
3938 {
3939 m_destroy_in_process = false;
3940 return error;
3941 }
3942 else if (exit_event_sp)
3943 {
3944 // We shouldn't need to do anything else here. There's no process left to detach from...
3945 StopPrivateStateThread();
3946 m_destroy_in_process = false;
3947 return error;
3948 }
3949 }
3950
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003951 m_thread_list.DiscardThreadPlans();
3952 DisableAllBreakpointSites();
3953
Jim Inghamacff8952013-05-02 00:27:30 +00003954 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003955 if (error.Success())
3956 {
3957 DidDetach();
3958 StopPrivateStateThread();
3959 }
Jim Inghamacff8952013-05-02 00:27:30 +00003960 else
3961 {
3962 return error;
3963 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003965 m_destroy_in_process = false;
3966
3967 // If we exited when we were waiting for a process to stop, then
3968 // forward the event here so we don't lose the event
3969 if (exit_event_sp)
3970 {
3971 // Directly broadcast our exited event because we shut down our
3972 // private state thread above
3973 BroadcastEvent(exit_event_sp);
3974 }
3975
3976 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3977 // the last events through the event system, in which case we might strand the write lock. Unlock
3978 // it here so when we do to tear down the process we don't get an error destroying the lock.
3979
Ed Maste64fad602013-07-29 20:58:06 +00003980 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981 return error;
3982}
3983
3984Error
Jason Molendaede31932015-04-17 05:01:58 +00003985Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003986{
Jim Ingham09437922013-03-01 20:04:25 +00003987
3988 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3989 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3990 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00003991
3992 if (force_kill)
3993 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00003994
Ilia Kfcc89a02015-03-26 07:08:47 +00003995 if (GetShouldDetach())
3996 {
3997 // FIXME: This will have to be a process setting:
3998 bool keep_stopped = false;
3999 Detach(keep_stopped);
4000 }
4001
Jim Ingham09437922013-03-01 20:04:25 +00004002 m_destroy_in_process = true;
4003
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004004 Error error (WillDestroy());
4005 if (error.Success())
4006 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00004007 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004008 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00004009 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004010 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00004011 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004012
Jim Inghamaacc3182012-06-06 00:29:30 +00004013 if (m_public_state.GetValue() != eStateRunning)
4014 {
4015 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4016 // kill it, we don't want it hitting a breakpoint...
4017 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4018 // we're not going to have much luck doing this now.
4019 m_thread_list.DiscardThreadPlans();
4020 DisableAllBreakpointSites();
4021 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004022
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004023 error = DoDestroy();
4024 if (error.Success())
4025 {
4026 DidDestroy();
4027 StopPrivateStateThread();
4028 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004029 m_stdio_communication.StopReadThread();
4030 m_stdio_communication.Disconnect();
Vince Harrondf3f00f2015-02-10 21:09:04 +00004031 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00004032
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004033 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00004034 {
4035 m_process_input_reader->SetIsDone(true);
4036 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004037 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00004038 }
4039
Greg Clayton85fb1b92012-09-11 02:33:37 +00004040 // If we exited when we were waiting for a process to stop, then
4041 // forward the event here so we don't lose the event
4042 if (exit_event_sp)
4043 {
4044 // Directly broadcast our exited event because we shut down our
4045 // private state thread above
4046 BroadcastEvent(exit_event_sp);
4047 }
4048
Jim Inghamb1e2e842012-04-12 18:49:31 +00004049 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4050 // the last events through the event system, in which case we might strand the write lock. Unlock
4051 // 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 +00004052 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053 }
Jim Ingham09437922013-03-01 20:04:25 +00004054
4055 m_destroy_in_process = false;
4056
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004057 return error;
4058}
4059
4060Error
4061Process::Signal (int signal)
4062{
4063 Error error (WillSignal());
4064 if (error.Success())
4065 {
4066 error = DoSignal(signal);
4067 if (error.Success())
4068 DidSignal();
4069 }
4070 return error;
4071}
4072
Zachary Turner93749ab2015-03-03 21:51:25 +00004073void
4074Process::SetUnixSignals (const UnixSignalsSP &signals_sp)
4075{
4076 assert (signals_sp && "null signals_sp");
4077 m_unix_signals_sp = signals_sp;
4078}
4079
4080UnixSignals &
4081Process::GetUnixSignals ()
4082{
4083 assert (m_unix_signals_sp && "null m_unix_signals_sp");
4084 return *m_unix_signals_sp;
4085}
4086
Greg Clayton514487e2011-02-15 21:59:32 +00004087lldb::ByteOrder
4088Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004089{
Greg Clayton514487e2011-02-15 21:59:32 +00004090 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091}
4092
4093uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00004094Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004095{
Greg Clayton514487e2011-02-15 21:59:32 +00004096 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004097}
4098
Greg Clayton514487e2011-02-15 21:59:32 +00004099
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100bool
4101Process::ShouldBroadcastEvent (Event *event_ptr)
4102{
4103 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4104 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00004105 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00004106
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004107 switch (state)
4108 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004109 case eStateDetached:
4110 case eStateExited:
4111 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00004112 m_stdio_communication.SynchronizeWithReadThread();
4113 // fall-through
4114 case eStateConnected:
4115 case eStateAttaching:
4116 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117 // These events indicate changes in the state of the debugging session, always report them.
4118 return_value = true;
4119 break;
4120 case eStateInvalid:
4121 // We stopped for no apparent reason, don't report it.
4122 return_value = false;
4123 break;
4124 case eStateRunning:
4125 case eStateStepping:
4126 // If we've started the target running, we handle the cases where we
4127 // are already running and where there is a transition from stopped to
4128 // running differently.
4129 // running -> running: Automatically suppress extra running events
4130 // stopped -> running: Report except when there is one or more no votes
4131 // and no yes votes.
4132 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004133 if (m_force_next_event_delivery)
4134 return_value = true;
4135 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004136 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004137 switch (m_last_broadcast_state)
4138 {
4139 case eStateRunning:
4140 case eStateStepping:
4141 // We always suppress multiple runnings with no PUBLIC stop in between.
4142 return_value = false;
4143 break;
4144 default:
4145 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004146 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004147 // events. If I run the lldb/test/thread/a.out file and
4148 // break at main.cpp:58, run and hit the breakpoints on
4149 // multiple threads, then somehow during the stepping over
4150 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004151
Jim Ingham1460e4b2014-01-10 23:46:59 +00004152 // This is a transition from stop to run.
4153 switch (m_thread_list.ShouldReportRun (event_ptr))
4154 {
4155 case eVoteYes:
4156 case eVoteNoOpinion:
4157 return_value = true;
4158 break;
4159 case eVoteNo:
4160 return_value = false;
4161 break;
4162 }
4163 break;
4164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165 }
4166 break;
4167 case eStateStopped:
4168 case eStateCrashed:
4169 case eStateSuspended:
4170 {
4171 // We've stopped. First see if we're going to restart the target.
4172 // If we are going to stop, then we always broadcast the event.
4173 // 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 +00004174 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004175
Pavel Labath3f5df532015-03-12 10:12:41 +00004176 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00004177 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004178 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004179 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004180 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004181 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004182 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004183 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004184 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4185 // so they can properly set their state.
4186 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004187 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004188 }
4189 else
4190 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004191 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4192 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004193
Jim Ingham0161b492013-02-09 01:29:05 +00004194 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4195 // Asking the thread list is also not likely to go well, since we are running again.
4196 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004197
Jim Ingham0161b492013-02-09 01:29:05 +00004198 if (!was_restarted)
4199 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004200
Jim Ingham221d51c2013-05-08 00:35:16 +00004201 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004202 {
Jim Ingham0161b492013-02-09 01:29:05 +00004203 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4204 if (log)
4205 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004206 should_resume, StateAsCString(state),
4207 was_restarted, stop_vote);
4208
Jim Ingham0161b492013-02-09 01:29:05 +00004209 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004210 {
4211 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004212 return_value = true;
4213 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004214 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004215 case eVoteNo:
4216 return_value = false;
4217 break;
4218 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004219
Jim Inghamcb95f342012-09-05 21:13:56 +00004220 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004221 {
4222 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004223 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4224 static_cast<void*>(event_ptr),
4225 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004226 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004227 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004228 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004229
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004230 }
4231 else
4232 {
4233 return_value = true;
4234 SynchronouslyNotifyStateChanged (state);
4235 }
4236 }
4237 }
Jim Ingham0161b492013-02-09 01:29:05 +00004238 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004240
Jim Ingham1460e4b2014-01-10 23:46:59 +00004241 // Forcing the next event delivery is a one shot deal. So reset it here.
4242 m_force_next_event_delivery = false;
4243
Jim Ingham0161b492013-02-09 01:29:05 +00004244 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4245 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4246 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4247 // because the PublicState reflects the last event pulled off the queue, and there may be several
4248 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4249 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004250
Jim Ingham0161b492013-02-09 01:29:05 +00004251 if (return_value)
4252 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004254 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004255 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004256 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004257 StateAsCString(m_last_broadcast_state),
4258 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004259 return return_value;
4260}
4261
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004262
4263bool
Jim Ingham372787f2012-04-07 00:00:41 +00004264Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004265{
Greg Clayton5160ce52013-03-27 23:08:40 +00004266 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004267
Greg Clayton8b82f082011-04-12 05:54:46 +00004268 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004269 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004270 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4271
Jim Ingham372787f2012-04-07 00:00:41 +00004272 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004273 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004274
4275 // Create a thread that watches our internal state and controls which
4276 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004277 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004278
Zachary Turner39de3112014-09-09 20:54:56 +00004279 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004280 {
Zachary Turner39de3112014-09-09 20:54:56 +00004281 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4282 if (already_running)
4283 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4284 else
4285 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004286 }
Jim Ingham372787f2012-04-07 00:00:41 +00004287 else
Todd Fiala17096d72014-07-16 19:03:16 +00004288 {
4289 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004290 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004291 else
Zachary Turner39de3112014-09-09 20:54:56 +00004292 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004293 }
4294
Jim Ingham076b3042012-04-10 01:21:57 +00004295 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00004296 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004297 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004298 {
4299 ResumePrivateStateThread();
4300 return true;
4301 }
4302 else
4303 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004304}
4305
4306void
4307Process::PausePrivateStateThread ()
4308{
4309 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4310}
4311
4312void
4313Process::ResumePrivateStateThread ()
4314{
4315 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4316}
4317
4318void
4319Process::StopPrivateStateThread ()
4320{
Greg Clayton8b82f082011-04-12 05:54:46 +00004321 if (PrivateStateThreadIsValid ())
4322 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004323 else
4324 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004325 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004326 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004327 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004328 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004329}
4330
4331void
4332Process::ControlPrivateStateThread (uint32_t signal)
4333{
Greg Clayton5160ce52013-03-27 23:08:40 +00004334 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004335
4336 assert (signal == eBroadcastInternalStateControlStop ||
4337 signal == eBroadcastInternalStateControlPause ||
4338 signal == eBroadcastInternalStateControlResume);
4339
4340 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004341 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004342
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004343 // Signal the private state thread. First we should copy this is case the
4344 // thread starts exiting since the private state thread will NULL this out
4345 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004346 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004347 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004348 {
4349 TimeValue timeout_time;
4350 bool timed_out;
4351
4352 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4353
4354 timeout_time = TimeValue::Now();
4355 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004356 if (log)
4357 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004358 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4359 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4360
4361 if (signal == eBroadcastInternalStateControlStop)
4362 {
4363 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004364 {
Zachary Turner39de3112014-09-09 20:54:56 +00004365 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004366 if (log)
4367 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4368 }
4369 else
4370 {
4371 if (log)
4372 log->Printf ("The control event killed the private state thread without having to cancel.");
4373 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004374
4375 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004376 private_state_thread.Join(&result);
4377 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004378 }
4379 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004380 else
4381 {
4382 if (log)
4383 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4384 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004385}
4386
4387void
Jim Inghamcfc09352012-07-27 23:57:19 +00004388Process::SendAsyncInterrupt ()
4389{
4390 if (PrivateStateThreadIsValid())
4391 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4392 else
4393 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4394}
4395
4396void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004397Process::HandlePrivateEvent (EventSP &event_sp)
4398{
Greg Clayton5160ce52013-03-27 23:08:40 +00004399 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004400 m_resume_requested = false;
4401
Jim Inghamaacc3182012-06-06 00:29:30 +00004402 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004403
Greg Clayton414f5d32011-01-25 02:58:48 +00004404 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004405
4406 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004407 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004408 {
Jim Ingham754ab982011-01-29 04:05:41 +00004409 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004410 if (log)
4411 log->Printf ("Ran next event action, result was %d.", action_result);
4412
Jim Inghambb3a2832011-01-29 01:49:25 +00004413 switch (action_result)
4414 {
4415 case NextEventAction::eEventActionSuccess:
4416 SetNextEventAction(NULL);
4417 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004418
Jim Inghambb3a2832011-01-29 01:49:25 +00004419 case NextEventAction::eEventActionRetry:
4420 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004421
Jim Inghambb3a2832011-01-29 01:49:25 +00004422 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004423 // Handle Exiting Here. If we already got an exited event,
4424 // we should just propagate it. Otherwise, swallow this event,
4425 // and set our state to exit so the next event will kill us.
4426 if (new_state != eStateExited)
4427 {
4428 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004429 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004430 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004431 SetNextEventAction(NULL);
4432 return;
4433 }
4434 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004435 break;
4436 }
4437 }
4438
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004439 // See if we should broadcast this state to external clients?
4440 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004441
4442 if (should_broadcast)
4443 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004444 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004445 if (log)
4446 {
Daniel Malead01b2952012-11-29 21:49:15 +00004447 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004448 __FUNCTION__,
4449 GetID(),
4450 StateAsCString(new_state),
4451 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004452 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004453 }
Jim Ingham9575d842011-03-11 03:53:59 +00004454 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004455 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004456 {
4457 // Only push the input handler if we aren't fowarding events,
4458 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004459 // Or don't push it if we are launching since it will come up stopped.
4460 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004461 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004462 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004463 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004464 else if (StateIsStoppedState(new_state, false))
4465 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004466 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004467 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4468 {
4469 // If the lldb_private::Debugger is handling the events, we don't
4470 // want to pop the process IOHandler here, we want to do it when
4471 // we receive the stopped event so we can carefully control when
4472 // the process IOHandler is popped because when we stop we want to
4473 // display some text stating how and why we stopped, then maybe some
4474 // process/thread/frame info, and then we want the "(lldb) " prompt
4475 // to show up. If we pop the process IOHandler here, then we will
4476 // cause the command interpreter to become the top IOHandler after
4477 // the process pops off and it will update its prompt right away...
4478 // See the Debugger.cpp file where it calls the function as
4479 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4480 // Otherwise we end up getting overlapping "(lldb) " prompts and
4481 // garbled output.
4482 //
4483 // If we aren't handling the events in the debugger (which is indicated
4484 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4485 // are hijacked, then we always pop the process IO handler manually.
4486 // Hijacking happens when the internal process state thread is running
4487 // thread plans, or when commands want to run in synchronous mode
4488 // and they call "process->WaitForProcessToStop()". An example of something
4489 // that will hijack the events is a simple expression:
4490 //
4491 // (lldb) expr (int)puts("hello")
4492 //
4493 // This will cause the internal process state thread to resume and halt
4494 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4495 // events) and we do need the IO handler to be pushed and popped
4496 // correctly.
4497
4498 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4499 PopProcessIOHandler ();
4500 }
4501 }
Jim Ingham9575d842011-03-11 03:53:59 +00004502
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004503 BroadcastEvent (event_sp);
4504 }
4505 else
4506 {
4507 if (log)
4508 {
Daniel Malead01b2952012-11-29 21:49:15 +00004509 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004510 __FUNCTION__,
4511 GetID(),
4512 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004513 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004514 }
4515 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004516 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004517}
4518
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004519thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004520Process::PrivateStateThread (void *arg)
4521{
4522 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004523 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004524 return result;
4525}
4526
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004527thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004528Process::RunPrivateStateThread ()
4529{
Jim Ingham076b3042012-04-10 01:21:57 +00004530 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004531 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004532
Greg Clayton5160ce52013-03-27 23:08:40 +00004533 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004534 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004535 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4536 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004537
4538 bool exit_now = false;
4539 while (!exit_now)
4540 {
4541 EventSP event_sp;
4542 WaitForEventsPrivate (NULL, event_sp, control_only);
4543 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4544 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004545 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004546 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4547 __FUNCTION__, static_cast<void*>(this), GetID(),
4548 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004549
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004550 switch (event_sp->GetType())
4551 {
4552 case eBroadcastInternalStateControlStop:
4553 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004554 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004555
4556 case eBroadcastInternalStateControlPause:
4557 control_only = true;
4558 break;
4559
4560 case eBroadcastInternalStateControlResume:
4561 control_only = false;
4562 break;
4563 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004564
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004565 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004566 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004567 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004568 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4569 {
4570 if (m_public_state.GetValue() == eStateAttaching)
4571 {
4572 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004573 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4574 __FUNCTION__, static_cast<void*>(this),
4575 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004576 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4577 }
4578 else
4579 {
4580 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004581 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4582 __FUNCTION__, static_cast<void*>(this),
4583 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004584 Halt();
4585 }
4586 continue;
4587 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004588
4589 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4590
4591 if (internal_state != eStateInvalid)
4592 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004593 if (m_clear_thread_plans_on_stop &&
4594 StateIsStoppedState(internal_state, true))
4595 {
4596 m_clear_thread_plans_on_stop = false;
4597 m_thread_list.DiscardThreadPlans();
4598 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004599 HandlePrivateEvent (event_sp);
4600 }
4601
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004602 if (internal_state == eStateInvalid ||
4603 internal_state == eStateExited ||
4604 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004605 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004606 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004607 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4608 __FUNCTION__, static_cast<void*>(this), GetID(),
4609 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004610
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004611 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004612 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004613 }
4614
Caroline Tice20ad3c42010-10-29 21:48:37 +00004615 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004616 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004617 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4618 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004619
Ed Maste64fad602013-07-29 20:58:06 +00004620 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004621 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004622 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004623 return NULL;
4624}
4625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004626//------------------------------------------------------------------
4627// Process Event Data
4628//------------------------------------------------------------------
4629
4630Process::ProcessEventData::ProcessEventData () :
4631 EventData (),
4632 m_process_sp (),
4633 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004634 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004635 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004636 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004637{
4638}
4639
4640Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4641 EventData (),
4642 m_process_sp (process_sp),
4643 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004644 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004645 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004646 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004647{
4648}
4649
4650Process::ProcessEventData::~ProcessEventData()
4651{
4652}
4653
4654const ConstString &
4655Process::ProcessEventData::GetFlavorString ()
4656{
4657 static ConstString g_flavor ("Process::ProcessEventData");
4658 return g_flavor;
4659}
4660
4661const ConstString &
4662Process::ProcessEventData::GetFlavor () const
4663{
4664 return ProcessEventData::GetFlavorString ();
4665}
4666
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004667void
4668Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4669{
4670 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004671 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4672 // the public event queue, then other times when we're pretending that this is where we stopped at the
4673 // end of expression evaluation. m_update_state is used to distinguish these
4674 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004675 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004676 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004677 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004678
Jim Ingham221d51c2013-05-08 00:35:16 +00004679 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004680
4681 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4682 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4683 // end up restarting the process.
4684 if (m_interrupted)
4685 return;
4686
4687 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004688 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004689 {
4690 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004691 uint32_t num_threads = curr_thread_list.GetSize();
4692 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004693
Jim Ingham4b536182011-08-09 02:12:22 +00004694 // The actions might change one of the thread's stop_info's opinions about whether we should
4695 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004696
4697 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4698 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4699 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4700 // 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
4701 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004702 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004703 for (idx = 0; idx < num_threads; ++idx)
4704 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4705
Jim Inghamc7078c22012-12-13 22:24:15 +00004706 // Use this to track whether we should continue from here. We will only continue the target running if
4707 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4708 // then it doesn't matter what the other threads say...
4709
4710 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004711
Jim Ingham0ad7e052013-04-25 02:04:59 +00004712 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4713 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4714 // thing to do is, and it's better to let the user decide than continue behind their backs.
4715
4716 bool does_anybody_have_an_opinion = false;
4717
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004718 for (idx = 0; idx < num_threads; ++idx)
4719 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004720 curr_thread_list = m_process_sp->GetThreadList();
4721 if (curr_thread_list.GetSize() != num_threads)
4722 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004723 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004724 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004725 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 +00004726 break;
4727 }
4728
4729 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4730
4731 if (thread_sp->GetIndexID() != thread_index_array[idx])
4732 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004733 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004734 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004735 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004736 idx,
4737 thread_index_array[idx],
4738 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004739 break;
4740 }
4741
Jim Inghamb15bfc72010-10-20 00:39:53 +00004742 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004743 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004744 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004745 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004746 bool this_thread_wants_to_stop;
4747 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004748 {
Jim Ingham0161b492013-02-09 01:29:05 +00004749 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4750 }
4751 else
4752 {
4753 stop_info_sp->PerformAction(event_ptr);
4754 // The stop action might restart the target. If it does, then we want to mark that in the
4755 // event so that whoever is receiving it will know to wait for the running event and reflect
4756 // that state appropriately.
4757 // We also need to stop processing actions, since they aren't expecting the target to be running.
4758
4759 // FIXME: we might have run.
4760 if (stop_info_sp->HasTargetRunSinceMe())
4761 {
4762 SetRestarted (true);
4763 break;
4764 }
4765
4766 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004767 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004768
Jim Inghamc7078c22012-12-13 22:24:15 +00004769 if (still_should_stop == false)
4770 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004771 }
4772 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004773
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004774
Jim Inghama8ca6e22013-05-03 23:04:37 +00004775 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004776 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004777 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004778 {
4779 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004780 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004781 // Use the public resume method here, since this is just
4782 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004783 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004784 }
4785 else
4786 {
4787 // If we didn't restart, run the Stop Hooks here:
4788 // They might also restart the target, so watch for that.
4789 m_process_sp->GetTarget().RunStopHooks();
4790 if (m_process_sp->GetPrivateState() == eStateRunning)
4791 SetRestarted(true);
4792 }
Jim Ingham9575d842011-03-11 03:53:59 +00004793 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004794 }
4795}
4796
4797void
4798Process::ProcessEventData::Dump (Stream *s) const
4799{
4800 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004801 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4802 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004803
Greg Clayton8b82f082011-04-12 05:54:46 +00004804 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004805}
4806
4807const Process::ProcessEventData *
4808Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4809{
4810 if (event_ptr)
4811 {
4812 const EventData *event_data = event_ptr->GetData();
4813 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4814 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4815 }
4816 return NULL;
4817}
4818
4819ProcessSP
4820Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4821{
4822 ProcessSP process_sp;
4823 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4824 if (data)
4825 process_sp = data->GetProcessSP();
4826 return process_sp;
4827}
4828
4829StateType
4830Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4831{
4832 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4833 if (data == NULL)
4834 return eStateInvalid;
4835 else
4836 return data->GetState();
4837}
4838
4839bool
4840Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4841{
4842 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4843 if (data == NULL)
4844 return false;
4845 else
4846 return data->GetRestarted();
4847}
4848
4849void
4850Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4851{
4852 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4853 if (data != NULL)
4854 data->SetRestarted(new_value);
4855}
4856
Jim Ingham0161b492013-02-09 01:29:05 +00004857size_t
4858Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4859{
4860 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4861 if (data != NULL)
4862 return data->GetNumRestartedReasons();
4863 else
4864 return 0;
4865}
4866
4867const char *
4868Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4869{
4870 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4871 if (data != NULL)
4872 return data->GetRestartedReasonAtIndex(idx);
4873 else
4874 return NULL;
4875}
4876
4877void
4878Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4879{
4880 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4881 if (data != NULL)
4882 data->AddRestartedReason(reason);
4883}
4884
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004885bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004886Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4887{
4888 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4889 if (data == NULL)
4890 return false;
4891 else
4892 return data->GetInterrupted ();
4893}
4894
4895void
4896Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4897{
4898 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4899 if (data != NULL)
4900 data->SetInterrupted(new_value);
4901}
4902
4903bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004904Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4905{
4906 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4907 if (data)
4908 {
4909 data->SetUpdateStateOnRemoval();
4910 return true;
4911 }
4912 return false;
4913}
4914
Greg Claytond9e416c2012-02-18 05:35:26 +00004915lldb::TargetSP
4916Process::CalculateTarget ()
4917{
4918 return m_target.shared_from_this();
4919}
4920
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004921void
Greg Clayton0603aa92010-10-04 01:05:56 +00004922Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004923{
Greg Claytonc14ee322011-09-22 04:58:26 +00004924 exe_ctx.SetTargetPtr (&m_target);
4925 exe_ctx.SetProcessPtr (this);
4926 exe_ctx.SetThreadPtr(NULL);
4927 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004928}
4929
Greg Claytone996fd32011-03-08 22:40:15 +00004930//uint32_t
4931//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4932//{
4933// return 0;
4934//}
4935//
4936//ArchSpec
4937//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4938//{
4939// return Host::GetArchSpecForExistingProcess (pid);
4940//}
4941//
4942//ArchSpec
4943//Process::GetArchSpecForExistingProcess (const char *process_name)
4944//{
4945// return Host::GetArchSpecForExistingProcess (process_name);
4946//}
4947//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004948void
4949Process::AppendSTDOUT (const char * s, size_t len)
4950{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004951 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004952 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004953 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004954}
4955
4956void
Greg Clayton93e86192011-11-13 04:45:22 +00004957Process::AppendSTDERR (const char * s, size_t len)
4958{
4959 Mutex::Locker locker (m_stdio_communication_mutex);
4960 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004961 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004962}
4963
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004964void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004965Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004966{
4967 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004968 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004969 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4970}
4971
4972size_t
4973Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4974{
4975 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004976 if (m_profile_data.empty())
4977 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004978
4979 std::string &one_profile_data = m_profile_data.front();
4980 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004981 if (bytes_available > 0)
4982 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004983 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004984 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004985 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4986 static_cast<void*>(buf),
4987 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004988 if (bytes_available > buf_size)
4989 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004990 memcpy(buf, one_profile_data.c_str(), buf_size);
4991 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004992 bytes_available = buf_size;
4993 }
4994 else
4995 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004996 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004997 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004998 }
4999 }
5000 return bytes_available;
5001}
5002
5003
Greg Clayton93e86192011-11-13 04:45:22 +00005004//------------------------------------------------------------------
5005// Process STDIO
5006//------------------------------------------------------------------
5007
5008size_t
5009Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5010{
5011 Mutex::Locker locker(m_stdio_communication_mutex);
5012 size_t bytes_available = m_stdout_data.size();
5013 if (bytes_available > 0)
5014 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005015 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005016 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005017 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5018 static_cast<void*>(buf),
5019 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005020 if (bytes_available > buf_size)
5021 {
5022 memcpy(buf, m_stdout_data.c_str(), buf_size);
5023 m_stdout_data.erase(0, buf_size);
5024 bytes_available = buf_size;
5025 }
5026 else
5027 {
5028 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5029 m_stdout_data.clear();
5030 }
5031 }
5032 return bytes_available;
5033}
5034
5035
5036size_t
5037Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5038{
5039 Mutex::Locker locker(m_stdio_communication_mutex);
5040 size_t bytes_available = m_stderr_data.size();
5041 if (bytes_available > 0)
5042 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005043 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005044 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005045 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5046 static_cast<void*>(buf),
5047 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005048 if (bytes_available > buf_size)
5049 {
5050 memcpy(buf, m_stderr_data.c_str(), buf_size);
5051 m_stderr_data.erase(0, buf_size);
5052 bytes_available = buf_size;
5053 }
5054 else
5055 {
5056 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5057 m_stderr_data.clear();
5058 }
5059 }
5060 return bytes_available;
5061}
5062
5063void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005064Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5065{
5066 Process *process = (Process *) baton;
5067 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5068}
5069
Greg Clayton44d93782014-01-27 23:43:24 +00005070class IOHandlerProcessSTDIO :
5071 public IOHandler
5072{
5073public:
5074 IOHandlerProcessSTDIO (Process *process,
5075 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005076 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005077 m_process (process),
5078 m_read_file (),
5079 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005080 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005081 {
5082 m_read_file.SetDescriptor(GetInputFD(), false);
5083 }
5084
5085 virtual
5086 ~IOHandlerProcessSTDIO ()
5087 {
5088
5089 }
5090
5091 bool
5092 OpenPipes ()
5093 {
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005094 if (m_pipe.CanRead() && m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005095 return true;
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005096 Error result = m_pipe.CreateNew(false);
5097 return result.Success();
Greg Clayton44d93782014-01-27 23:43:24 +00005098 }
5099
5100 void
5101 ClosePipes()
5102 {
Greg Clayton100eb932014-07-02 21:10:39 +00005103 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00005104 }
5105
5106 // Each IOHandler gets to run until it is done. It should read data
5107 // from the "in" and place output into "out" and "err and return
5108 // when done.
5109 virtual void
5110 Run ()
5111 {
5112 if (m_read_file.IsValid() && m_write_file.IsValid())
5113 {
5114 SetIsDone(false);
5115 if (OpenPipes())
5116 {
5117 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00005118 TerminalState terminal_state;
5119 terminal_state.Save (read_fd, false);
5120 Terminal terminal(read_fd);
5121 terminal.SetCanonical(false);
5122 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005123// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005124#ifndef _WIN32
Zachary Turner48b475c2015-04-02 20:57:38 +00005125 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00005126 while (!GetIsDone())
5127 {
5128 fd_set read_fdset;
5129 FD_ZERO (&read_fdset);
5130 FD_SET (read_fd, &read_fdset);
5131 FD_SET (pipe_read_fd, &read_fdset);
5132 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5133 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5134 if (num_set_fds < 0)
5135 {
5136 const int select_errno = errno;
5137
5138 if (select_errno != EINTR)
5139 SetIsDone(true);
5140 }
5141 else if (num_set_fds > 0)
5142 {
5143 char ch = 0;
5144 size_t n;
5145 if (FD_ISSET (read_fd, &read_fdset))
5146 {
5147 n = 1;
5148 if (m_read_file.Read(&ch, n).Success() && n == 1)
5149 {
5150 if (m_write_file.Write(&ch, n).Fail() || n != 1)
5151 SetIsDone(true);
5152 }
5153 else
5154 SetIsDone(true);
5155 }
5156 if (FD_ISSET (pipe_read_fd, &read_fdset))
5157 {
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005158 size_t bytes_read;
Greg Clayton44d93782014-01-27 23:43:24 +00005159 // Consume the interrupt byte
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005160 Error error = m_pipe.Read(&ch, 1, bytes_read);
5161 if (error.Success())
Greg Clayton19e11352014-02-26 22:47:33 +00005162 {
Greg Clayton100eb932014-07-02 21:10:39 +00005163 switch (ch)
5164 {
5165 case 'q':
5166 SetIsDone(true);
5167 break;
5168 case 'i':
5169 if (StateIsRunningState(m_process->GetState()))
5170 m_process->Halt();
5171 break;
5172 }
Greg Clayton19e11352014-02-26 22:47:33 +00005173 }
Greg Clayton44d93782014-01-27 23:43:24 +00005174 }
5175 }
5176 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00005177#endif
Greg Clayton44d93782014-01-27 23:43:24 +00005178 terminal_state.Restore();
5179
5180 }
5181 else
5182 SetIsDone(true);
5183 }
5184 else
5185 SetIsDone(true);
5186 }
5187
5188 // Hide any characters that have been displayed so far so async
5189 // output can be displayed. Refresh() will be called after the
5190 // output has been displayed.
5191 virtual void
5192 Hide ()
5193 {
5194
5195 }
5196 // Called when the async output has been received in order to update
5197 // the input reader (refresh the prompt and redisplay any current
5198 // line(s) that are being edited
5199 virtual void
5200 Refresh ()
5201 {
5202
5203 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005204
Greg Clayton44d93782014-01-27 23:43:24 +00005205 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00005206 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00005207 {
Greg Clayton19e11352014-02-26 22:47:33 +00005208 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005209 size_t bytes_written = 0;
5210 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005211 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005212
Greg Claytonf0066ad2014-05-02 00:45:31 +00005213 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00005214 Interrupt ()
5215 {
Greg Clayton19e11352014-02-26 22:47:33 +00005216 // Do only things that are safe to do in an interrupt context (like in
5217 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5218 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5219 // that was written to the pipe and then call m_process->Halt() from a
5220 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005221 if (m_active)
5222 {
5223 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005224 size_t bytes_written = 0;
5225 Error result = m_pipe.Write(&ch, 1, bytes_written);
5226 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005227 }
5228 else
5229 {
5230 // This IOHandler might be pushed on the stack, but not being run currently
5231 // so do the right thing if we aren't actively watching for STDIN by sending
5232 // the interrupt to the process. Otherwise the write to the pipe above would
5233 // do nothing. This can happen when the command interpreter is running and
5234 // gets a "expression ...". It will be on the IOHandler thread and sending
5235 // the input is complete to the delegate which will cause the expression to
5236 // run, which will push the process IO handler, but not run it.
5237
5238 if (StateIsRunningState(m_process->GetState()))
5239 {
5240 m_process->SendAsyncInterrupt();
5241 return true;
5242 }
5243 }
5244 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005245 }
Greg Clayton44d93782014-01-27 23:43:24 +00005246
5247 virtual void
5248 GotEOF()
5249 {
5250
5251 }
5252
5253protected:
5254 Process *m_process;
5255 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5256 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005257 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005258};
5259
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005260void
Greg Clayton44d93782014-01-27 23:43:24 +00005261Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005262{
5263 // First set up the Read Thread for reading/handling process I/O
5264
Greg Clayton44d93782014-01-27 23:43:24 +00005265 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005266
5267 if (conn_ap.get())
5268 {
5269 m_stdio_communication.SetConnection (conn_ap.release());
5270 if (m_stdio_communication.IsConnected())
5271 {
5272 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5273 m_stdio_communication.StartReadThread();
5274
5275 // Now read thread is set up, set up input reader.
5276
5277 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005278 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005279 }
5280 }
5281}
5282
Greg Claytonb4874f12014-02-28 18:22:24 +00005283bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005284Process::ProcessIOHandlerIsActive ()
5285{
5286 IOHandlerSP io_handler_sp (m_process_input_reader);
5287 if (io_handler_sp)
5288 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5289 return false;
5290}
5291bool
Greg Clayton44d93782014-01-27 23:43:24 +00005292Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005293{
Greg Clayton44d93782014-01-27 23:43:24 +00005294 IOHandlerSP io_handler_sp (m_process_input_reader);
5295 if (io_handler_sp)
5296 {
5297 io_handler_sp->SetIsDone(false);
5298 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005299 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005300 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005301 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005302}
5303
Greg Claytonb4874f12014-02-28 18:22:24 +00005304bool
Greg Clayton44d93782014-01-27 23:43:24 +00005305Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005306{
Greg Clayton44d93782014-01-27 23:43:24 +00005307 IOHandlerSP io_handler_sp (m_process_input_reader);
5308 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005309 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5310 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005311}
5312
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005313// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005314void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005315Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005316{
Greg Clayton6920b522012-08-22 18:39:03 +00005317 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005318}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005319
Greg Clayton99d0faf2010-11-18 23:32:35 +00005320void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005321Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005322{
Greg Clayton6920b522012-08-22 18:39:03 +00005323 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005324}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005325
Jim Ingham1624a2d2014-05-05 02:26:40 +00005326ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005327Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005328 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005329 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005330 Stream &errors)
5331{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005332 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005333
Jim Ingham77787032011-01-20 02:03:18 +00005334 if (thread_plan_sp.get() == NULL)
5335 {
5336 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005337 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005338 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005339
Jim Ingham7d7931d2013-03-28 00:05:34 +00005340 if (!thread_plan_sp->ValidatePlan(NULL))
5341 {
5342 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005343 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005344 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005345
Greg Claytonc14ee322011-09-22 04:58:26 +00005346 if (exe_ctx.GetProcessPtr() != this)
5347 {
5348 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005349 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005350 }
5351
5352 Thread *thread = exe_ctx.GetThreadPtr();
5353 if (thread == NULL)
5354 {
5355 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005356 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005357 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005358
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005359 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5360 // For that to be true the plan can't be private - since private plans suppress themselves in the
5361 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005362
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005363 bool orig_plan_private = thread_plan_sp->GetPrivate();
5364 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005365
Jim Ingham444586b2011-01-24 06:34:17 +00005366 if (m_private_state.GetValue() != eStateStopped)
5367 {
5368 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005369 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005370 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005371
Jim Ingham66243842011-08-13 00:56:10 +00005372 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005373 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005374 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005375 if (!selected_frame_sp)
5376 {
5377 thread->SetSelectedFrame(0);
5378 selected_frame_sp = thread->GetSelectedFrame();
5379 if (!selected_frame_sp)
5380 {
5381 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005382 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005383 }
5384 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005385
Jim Ingham11b0e052013-02-19 23:22:45 +00005386 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005387
5388 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5389 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005390
Greg Claytonc14ee322011-09-22 04:58:26 +00005391 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005392
Jim Ingham66243842011-08-13 00:56:10 +00005393 uint32_t selected_tid;
5394 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005395 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005396 {
5397 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005398 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005399 }
5400 else
5401 {
5402 selected_tid = LLDB_INVALID_THREAD_ID;
5403 }
5404
Zachary Turner39de3112014-09-09 20:54:56 +00005405 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005406 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005407 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005408
Greg Clayton5160ce52013-03-27 23:08:40 +00005409 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005410 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005411 {
Jim Ingham076b3042012-04-10 01:21:57 +00005412 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5413 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005414 // 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 +00005415 // we are fielding public events here.
5416 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005417 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 +00005418
Jim Ingham372787f2012-04-07 00:00:41 +00005419 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005420
5421 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5422 // returning control here.
5423 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5424 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5425 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5426 // do just what we want.
5427 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5428 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5429 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5430 old_state = m_public_state.GetValue();
5431 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005432
Jim Ingham076b3042012-04-10 01:21:57 +00005433 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005434 StartPrivateStateThread(true);
5435 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005436
Jim Ingham372787f2012-04-07 00:00:41 +00005437 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005438
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005439 if (options.GetDebug())
5440 {
5441 // In this case, we aren't actually going to run, we just want to stop right away.
5442 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5443 // FIXME: To make this prettier we should invent some stop reason for this, but that
5444 // is only cosmetic, and this functionality is only of use to lldb developers who can
5445 // live with not pretty...
5446 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005447 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005448 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005449
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005450 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005451
Sean Callanana46ec452012-07-11 21:31:24 +00005452 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005453
Jim Ingham77787032011-01-20 02:03:18 +00005454 {
Sean Callanana46ec452012-07-11 21:31:24 +00005455 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5456 // restored on exit to the function.
5457 //
5458 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5459 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005460
Sean Callanana46ec452012-07-11 21:31:24 +00005461 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005462
Jim Inghamf48169b2010-11-30 02:22:11 +00005463 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005464 {
5465 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005466 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005467 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005468 thread->GetIndexID(),
5469 thread->GetID(),
5470 s.GetData());
5471 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005472
Sean Callanana46ec452012-07-11 21:31:24 +00005473 bool got_event;
5474 lldb::EventSP event_sp;
5475 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005476
Sean Callanana46ec452012-07-11 21:31:24 +00005477 TimeValue* timeout_ptr = NULL;
5478 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005479
Jim Ingham0161b492013-02-09 01:29:05 +00005480 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 +00005481 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005482 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005483 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005484
Jim Ingham0161b492013-02-09 01:29:05 +00005485 // This is just for accounting:
5486 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005487
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005488 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005489 uint32_t one_thread_timeout_usec;
5490 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005491
5492 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5493 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5494 // first timeout already.
5495
5496 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005497 {
5498 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005499 one_thread_timeout_usec = 0;
5500 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005501 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005502 else
Jim Ingham0161b492013-02-09 01:29:05 +00005503 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005504 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005505
Jim Ingham914f4e72014-03-28 21:58:28 +00005506 // If the overall wait is forever, then we only need to set the one thread timeout:
5507 if (timeout_usec == 0)
5508 {
Ed Maste801335c2014-03-31 19:28:14 +00005509 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005510 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005511 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005512 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005513 }
Jim Ingham0161b492013-02-09 01:29:05 +00005514 else
5515 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005516 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5517 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5518 uint64_t computed_one_thread_timeout;
5519 if (option_one_thread_timeout != 0)
5520 {
5521 if (timeout_usec < option_one_thread_timeout)
5522 {
5523 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005524 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005525 }
5526 computed_one_thread_timeout = option_one_thread_timeout;
5527 }
5528 else
5529 {
5530 computed_one_thread_timeout = timeout_usec / 2;
5531 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5532 computed_one_thread_timeout = default_one_thread_timeout_usec;
5533 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005534 one_thread_timeout_usec = computed_one_thread_timeout;
5535 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5536
Jim Ingham0161b492013-02-09 01:29:05 +00005537 }
Jim Ingham0161b492013-02-09 01:29:05 +00005538 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005539
5540 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005541 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 +00005542 options.GetStopOthers(),
5543 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005544 before_first_timeout,
5545 one_thread_timeout_usec,
5546 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005547
Jim Ingham1460e4b2014-01-10 23:46:59 +00005548 // This isn't going to work if there are unfetched events on the queue.
5549 // Are there cases where we might want to run the remaining events here, and then try to
5550 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005551
Jim Ingham1460e4b2014-01-10 23:46:59 +00005552 Event *other_events = listener.PeekAtNextEvent();
5553 if (other_events != NULL)
5554 {
5555 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005556 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005557 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005558
Jim Ingham1460e4b2014-01-10 23:46:59 +00005559 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5560 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5561 // event coalescing to cause us to lose OUR running event...
5562 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005563
Jim Ingham8559a352012-11-26 23:52:18 +00005564 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5565 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005566
5567#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5568 // It's pretty much impossible to write test cases for things like:
5569 // One thread timeout expires, I go to halt, but the process already stopped
5570 // on the function call stop breakpoint. Turning on this define will make us not
5571 // fetch the first event till after the halt. So if you run a quick function, it will have
5572 // completed, and the completion event will be waiting, when you interrupt for halt.
5573 // The expression evaluation should still succeed.
5574 bool miss_first_event = true;
5575#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005576 TimeValue one_thread_timeout;
5577 TimeValue final_timeout;
5578
Jim Ingham35878c42014-04-08 21:33:21 +00005579
Sean Callanana46ec452012-07-11 21:31:24 +00005580 while (1)
5581 {
5582 // We usually want to resume the process if we get to the top of the loop.
5583 // The only exception is if we get two running events with no intervening
5584 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005585 if (log)
5586 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5587 do_resume,
5588 handle_running_event,
5589 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005590
Jim Ingham184e9812013-01-15 02:47:48 +00005591 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005592 {
5593 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005594
Jim Ingham184e9812013-01-15 02:47:48 +00005595 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005596 {
Jim Ingham0161b492013-02-09 01:29:05 +00005597 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005598 Error resume_error = PrivateResume ();
5599 if (!resume_error.Success())
5600 {
Jim Ingham0161b492013-02-09 01:29:05 +00005601 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5602 num_resumes,
5603 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005604 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005605 break;
5606 }
Sean Callanana46ec452012-07-11 21:31:24 +00005607 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005608
Jim Ingham0161b492013-02-09 01:29:05 +00005609 TimeValue resume_timeout = TimeValue::Now();
5610 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005611
Jim Ingham0161b492013-02-09 01:29:05 +00005612 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005613 if (!got_event)
5614 {
5615 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005616 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5617 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005618
Jim Ingham0161b492013-02-09 01:29:05 +00005619 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005620 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005621 break;
5622 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005623
Sean Callanana46ec452012-07-11 21:31:24 +00005624 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005625
Sean Callanana46ec452012-07-11 21:31:24 +00005626 if (stop_state != eStateRunning)
5627 {
Jim Ingham0161b492013-02-09 01:29:05 +00005628 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005629
Jim Ingham0161b492013-02-09 01:29:05 +00005630 if (stop_state == eStateStopped)
5631 {
5632 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5633 if (log)
5634 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5635 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5636 num_resumes,
5637 StateAsCString(stop_state),
5638 restarted,
5639 do_resume,
5640 handle_running_event);
5641 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005642
Jim Ingham0161b492013-02-09 01:29:05 +00005643 if (restarted)
5644 {
5645 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5646 // event here. But if I do, the best thing is to Halt and then get out of here.
5647 Halt();
5648 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005649
Jim Ingham35e1bda2012-10-16 21:41:58 +00005650 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5651 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005652 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005653 break;
5654 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005655
Sean Callanana46ec452012-07-11 21:31:24 +00005656 if (log)
5657 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5658 // We need to call the function synchronously, so spin waiting for it to return.
5659 // If we get interrupted while executing, we're going to lose our context, and
5660 // won't be able to gather the result at this point.
5661 // We set the timeout AFTER the resume, since the resume takes some time and we
5662 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005663 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005664 else
5665 {
Sean Callanana46ec452012-07-11 21:31:24 +00005666 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005667 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005668 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005669
Jim Ingham0161b492013-02-09 01:29:05 +00005670 if (before_first_timeout)
5671 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005672 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005673 {
5674 one_thread_timeout = TimeValue::Now();
5675 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005676 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005677 }
Jim Ingham0161b492013-02-09 01:29:05 +00005678 else
5679 {
5680 if (timeout_usec == 0)
5681 timeout_ptr = NULL;
5682 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005683 {
5684 final_timeout = TimeValue::Now();
5685 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005686 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005687 }
Jim Ingham0161b492013-02-09 01:29:05 +00005688 }
5689 }
5690 else
5691 {
5692 if (timeout_usec == 0)
5693 timeout_ptr = NULL;
5694 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005695 {
5696 final_timeout = TimeValue::Now();
5697 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005698 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005699 }
Jim Ingham0161b492013-02-09 01:29:05 +00005700 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005701
Jim Ingham0161b492013-02-09 01:29:05 +00005702 do_resume = true;
5703 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005704
Sean Callanana46ec452012-07-11 21:31:24 +00005705 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005706 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005707
Jim Ingham0f16e732011-02-08 05:20:59 +00005708 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005709 {
Sean Callanana46ec452012-07-11 21:31:24 +00005710 if (timeout_ptr)
5711 {
Matt Kopec676a4872013-02-21 23:55:31 +00005712 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005713 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5714 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005715 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005716 else
Sean Callanana46ec452012-07-11 21:31:24 +00005717 {
5718 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5719 }
5720 }
Jim Ingham35878c42014-04-08 21:33:21 +00005721
5722#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5723 // See comment above...
5724 if (miss_first_event)
5725 {
5726 usleep(1000);
5727 miss_first_event = false;
5728 got_event = false;
5729 }
5730 else
5731#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005732 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005733
Sean Callanana46ec452012-07-11 21:31:24 +00005734 if (got_event)
5735 {
5736 if (event_sp.get())
5737 {
5738 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005739 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005740 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005741 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005742 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005743 errors.Printf ("Execution halted by user interrupt.");
5744 if (log)
5745 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005746 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005747 }
5748 else
5749 {
5750 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5751 if (log)
5752 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005753
Jim Inghamcfc09352012-07-27 23:57:19 +00005754 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005755 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005756 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005757 {
Jim Ingham0161b492013-02-09 01:29:05 +00005758 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005759 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5760 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005761 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005762 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005763 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005764 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005765 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005766 }
5767 else
5768 {
Jim Ingham0161b492013-02-09 01:29:05 +00005769 // If we were restarted, we just need to go back up to fetch another event.
5770 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005771 {
5772 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005773 {
5774 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5775 }
5776 keep_going = true;
5777 do_resume = false;
5778 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005779
Jim Inghamcfc09352012-07-27 23:57:19 +00005780 }
5781 else
5782 {
Jim Ingham0161b492013-02-09 01:29:05 +00005783 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5784 StopReason stop_reason = eStopReasonInvalid;
5785 if (stop_info_sp)
5786 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005787
Jim Ingham0161b492013-02-09 01:29:05 +00005788 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5789 // it is OUR plan that is complete?
5790 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005791 {
5792 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005793 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5794 // Now mark this plan as private so it doesn't get reported as the stop reason
5795 // after this point.
5796 if (thread_plan_sp)
5797 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005798 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005799 }
5800 else
5801 {
Jim Ingham0161b492013-02-09 01:29:05 +00005802 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005803 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005804 {
5805 if (log)
5806 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005807 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005808 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005809 {
5810 event_to_broadcast_sp = event_sp;
5811 }
Jim Ingham0161b492013-02-09 01:29:05 +00005812 }
Jim Ingham184e9812013-01-15 02:47:48 +00005813 else
Jim Ingham0161b492013-02-09 01:29:05 +00005814 {
5815 if (log)
5816 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005817 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005818 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005819 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005820 }
Jim Ingham184e9812013-01-15 02:47:48 +00005821 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005822 }
Sean Callanana46ec452012-07-11 21:31:24 +00005823 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005824 }
5825 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005826
Jim Inghamcfc09352012-07-27 23:57:19 +00005827 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005828 // This shouldn't really happen, but sometimes we do get two running events without an
5829 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005830 do_resume = false;
5831 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005832 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005833 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005834
Jim Inghamcfc09352012-07-27 23:57:19 +00005835 default:
5836 if (log)
5837 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005838
Jim Inghamcfc09352012-07-27 23:57:19 +00005839 if (stop_state == eStateExited)
5840 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005841
Sean Callananbf154da2012-08-08 17:35:10 +00005842 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005843 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005844 break;
5845 }
Sean Callanana46ec452012-07-11 21:31:24 +00005846 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005847
Sean Callanana46ec452012-07-11 21:31:24 +00005848 if (keep_going)
5849 continue;
5850 else
5851 break;
5852 }
5853 else
5854 {
5855 if (log)
5856 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005857 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005858 break;
5859 }
5860 }
5861 else
5862 {
5863 // If we didn't get an event that means we've timed out...
5864 // We will interrupt the process here. Depending on what we were asked to do we will
5865 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005866
Sean Callanana46ec452012-07-11 21:31:24 +00005867 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005868 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005869 {
Jim Ingham0161b492013-02-09 01:29:05 +00005870 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005871 {
5872 if (timeout_usec != 0)
5873 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005874 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005875 "running for %" PRIu32 " usec with all threads enabled.",
5876 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005877 }
5878 else
5879 {
5880 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005881 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005882 }
5883 }
Sean Callanana46ec452012-07-11 21:31:24 +00005884 else
5885 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005886 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005887 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005888 }
5889 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005890 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005891 "abandoning execution.",
5892 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005893 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005894
Jim Ingham0161b492013-02-09 01:29:05 +00005895 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5896 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5897 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5898 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5899 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005900
Jim Ingham0161b492013-02-09 01:29:05 +00005901 bool back_to_top = true;
5902 uint32_t try_halt_again = 0;
5903 bool do_halt = true;
5904 const uint32_t num_retries = 5;
5905 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005906 {
Jim Ingham0161b492013-02-09 01:29:05 +00005907 Error halt_error;
5908 if (do_halt)
5909 {
5910 if (log)
5911 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5912 halt_error = Halt();
5913 }
5914 if (halt_error.Success())
5915 {
5916 if (log)
5917 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005918
Jim Ingham0161b492013-02-09 01:29:05 +00005919 real_timeout = TimeValue::Now();
5920 real_timeout.OffsetWithMicroSeconds(500000);
5921
5922 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005923
Jim Ingham0161b492013-02-09 01:29:05 +00005924 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005925 {
Jim Ingham0161b492013-02-09 01:29:05 +00005926 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5927 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005928 {
Jim Ingham0161b492013-02-09 01:29:05 +00005929 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5930 if (stop_state == lldb::eStateStopped
5931 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5932 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005933 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005934
Jim Ingham0161b492013-02-09 01:29:05 +00005935 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005936 {
Jim Ingham0161b492013-02-09 01:29:05 +00005937 // Between the time we initiated the Halt and the time we delivered it, the process could have
5938 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005939
Jim Ingham0161b492013-02-09 01:29:05 +00005940 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5941 {
5942 if (log)
5943 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5944 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005945 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005946 back_to_top = false;
5947 break;
5948 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005949
Jim Ingham0161b492013-02-09 01:29:05 +00005950 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5951 {
5952 if (log)
5953 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5954 "Exiting wait loop.");
5955 try_halt_again++;
5956 do_halt = false;
5957 continue;
5958 }
Sean Callanana46ec452012-07-11 21:31:24 +00005959
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005960 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005961 {
5962 if (log)
5963 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005964 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005965 back_to_top = false;
5966 break;
5967 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005968
Jim Ingham0161b492013-02-09 01:29:05 +00005969 if (before_first_timeout)
5970 {
5971 // Set all the other threads to run, and return to the top of the loop, which will continue;
5972 before_first_timeout = false;
5973 thread_plan_sp->SetStopOthers (false);
5974 if (log)
5975 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005976
Jim Ingham0161b492013-02-09 01:29:05 +00005977 back_to_top = true;
5978 break;
5979 }
5980 else
5981 {
5982 // Running all threads failed, so return Interrupted.
5983 if (log)
5984 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005985 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005986 back_to_top = false;
5987 break;
5988 }
Sean Callanana46ec452012-07-11 21:31:24 +00005989 }
5990 }
5991 else
Jim Ingham0161b492013-02-09 01:29:05 +00005992 { if (log)
5993 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5994 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005995 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005996 back_to_top = false;
5997 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005998 }
5999 }
Jim Ingham0161b492013-02-09 01:29:05 +00006000 else
6001 {
6002 try_halt_again++;
6003 continue;
6004 }
Sean Callanana46ec452012-07-11 21:31:24 +00006005 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006006
Jim Ingham0161b492013-02-09 01:29:05 +00006007 if (!back_to_top || try_halt_again > num_retries)
6008 break;
6009 else
6010 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006011 }
Sean Callanana46ec452012-07-11 21:31:24 +00006012 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006013
Sean Callanana46ec452012-07-11 21:31:24 +00006014 // 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 +00006015 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006016 {
6017 StopPrivateStateThread();
6018 Error error;
6019 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006020 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006021 {
6022 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6023 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006024 if (old_state != eStateInvalid)
6025 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006026 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006027
Jim Ingham184e9812013-01-15 02:47:48 +00006028 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6029 // could happen:
6030 // 1) The execution successfully completed
6031 // 2) We hit a breakpoint, and ignore_breakpoints was true
6032 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006033 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6034 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006035
Jim Ingham8646d3c2014-05-05 02:47:44 +00006036 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006037 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006038 {
6039 thread_plan_sp->RestoreThreadState();
6040 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006041
Sean Callanana46ec452012-07-11 21:31:24 +00006042 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006043 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006044 {
6045 if (log)
6046 {
6047 StreamString s;
6048 if (event_sp)
6049 event_sp->Dump (&s);
6050 else
6051 {
6052 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6053 }
6054
6055 StreamString ts;
6056
6057 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006058
Sean Callanana46ec452012-07-11 21:31:24 +00006059 do
6060 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006061 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006062 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006063 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006064 break;
6065 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006066 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006067 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006068 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006069 break;
6070 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006071 else
Sean Callanana46ec452012-07-11 21:31:24 +00006072 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006073 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6074
6075 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006076 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006077 event_explanation = "<no event data>";
6078 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006079 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006080
Jim Inghamcfc09352012-07-27 23:57:19 +00006081 Process *process = event_data->GetProcessSP().get();
6082
6083 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006084 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006085 event_explanation = "<no process>";
6086 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006087 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006088
Jim Inghamcfc09352012-07-27 23:57:19 +00006089 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006090
Jim Inghamcfc09352012-07-27 23:57:19 +00006091 uint32_t num_threads = thread_list.GetSize();
6092 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006093
Jim Inghamcfc09352012-07-27 23:57:19 +00006094 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006095
Jim Inghamcfc09352012-07-27 23:57:19 +00006096 for (thread_index = 0;
6097 thread_index < num_threads;
6098 ++thread_index)
6099 {
6100 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006101
Jim Inghamcfc09352012-07-27 23:57:19 +00006102 if (!thread)
6103 {
6104 ts.Printf("<?> ");
6105 continue;
6106 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006107
Daniel Malead01b2952012-11-29 21:49:15 +00006108 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006109 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006110
Jim Inghamcfc09352012-07-27 23:57:19 +00006111 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006112 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006113 else
6114 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006115
Jim Inghamcfc09352012-07-27 23:57:19 +00006116 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6117 if (stop_info_sp)
6118 {
6119 const char *stop_desc = stop_info_sp->GetDescription();
6120 if (stop_desc)
6121 ts.PutCString (stop_desc);
6122 }
6123 ts.Printf(">");
6124 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006125
Jim Inghamcfc09352012-07-27 23:57:19 +00006126 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006127 }
Sean Callanana46ec452012-07-11 21:31:24 +00006128 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006129
Jim Inghamcfc09352012-07-27 23:57:19 +00006130 if (event_explanation)
6131 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006132 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006133 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6134 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006135
Jim Inghame4483cf2013-09-27 01:13:01 +00006136 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006137 {
6138 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006139 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6140 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006141 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6142 thread_plan_sp->SetPrivate (orig_plan_private);
6143 }
6144 else
6145 {
6146 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006147 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6148 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006149 }
6150 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006151 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006152 {
6153 if (log)
6154 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006155
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006156 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006157 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006158 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006159 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006160 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006161 }
6162 else
6163 {
Sean Callanana46ec452012-07-11 21:31:24 +00006164 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006165 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006166 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006167 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006168 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006169 }
6170 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6171 {
6172 if (log)
6173 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006174 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006175 }
6176 else
6177 {
6178 if (log)
6179 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006180 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006181 {
6182 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006183 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006184 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6185 thread_plan_sp->SetPrivate (orig_plan_private);
6186 }
6187 }
6188 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006189
Sean Callanana46ec452012-07-11 21:31:24 +00006190 // Thread we ran the function in may have gone away because we ran the target
6191 // Check that it's still there, and if it is put it back in the context. Also restore the
6192 // frame in the context if it is still present.
6193 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6194 if (thread)
6195 {
6196 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6197 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006198
Sean Callanana46ec452012-07-11 21:31:24 +00006199 // Also restore the current process'es selected frame & thread, since this function calling may
6200 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006201
Sean Callanana46ec452012-07-11 21:31:24 +00006202 if (selected_tid != LLDB_INVALID_THREAD_ID)
6203 {
6204 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6205 {
6206 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006207 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006208 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006209 if (old_frame_sp)
6210 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006211 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006212 }
6213 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006214
Sean Callanana46ec452012-07-11 21:31:24 +00006215 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006216
Sean Callanana46ec452012-07-11 21:31:24 +00006217 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006218 {
Sean Callanana46ec452012-07-11 21:31:24 +00006219 if (log)
6220 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6221 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006222 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006223
Jim Inghamf48169b2010-11-30 02:22:11 +00006224 return return_value;
6225}
6226
6227const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006228Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006229{
6230 const char *result_name;
6231
6232 switch (result)
6233 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006234 case eExpressionCompleted:
6235 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006236 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006237 case eExpressionDiscarded:
6238 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006239 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006240 case eExpressionInterrupted:
6241 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006242 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006243 case eExpressionHitBreakpoint:
6244 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006245 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006246 case eExpressionSetupError:
6247 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006248 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006249 case eExpressionParseError:
6250 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006251 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006252 case eExpressionResultUnavailable:
6253 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006254 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006255 case eExpressionTimedOut:
6256 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006257 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006258 case eExpressionStoppedForDebug:
6259 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006260 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006261 }
6262 return result_name;
6263}
6264
Greg Clayton7260f622011-04-18 08:33:37 +00006265void
6266Process::GetStatus (Stream &strm)
6267{
6268 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006269 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006270 {
6271 if (state == eStateExited)
6272 {
6273 int exit_status = GetExitStatus();
6274 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006275 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006276 GetID(),
6277 exit_status,
6278 exit_status,
6279 exit_description ? exit_description : "");
6280 }
6281 else
6282 {
6283 if (state == eStateConnected)
6284 strm.Printf ("Connected to remote target.\n");
6285 else
Daniel Malead01b2952012-11-29 21:49:15 +00006286 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006287 }
6288 }
6289 else
6290 {
Daniel Malead01b2952012-11-29 21:49:15 +00006291 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006292 }
6293}
6294
6295size_t
6296Process::GetThreadStatus (Stream &strm,
6297 bool only_threads_with_stop_reason,
6298 uint32_t start_frame,
6299 uint32_t num_frames,
6300 uint32_t num_frames_with_source)
6301{
6302 size_t num_thread_infos_dumped = 0;
6303
Jim Ingham4a65fb12014-03-07 11:20:03 +00006304 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6305 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6306 // ID's, and look them up one by one:
6307
6308 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006309 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006310 //Scope for thread list locker;
6311 {
6312 Mutex::Locker locker (GetThreadList().GetMutex());
6313 ThreadList &curr_thread_list = GetThreadList();
6314 num_threads = curr_thread_list.GetSize();
6315 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006316 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006317 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006318 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006319 }
6320
Greg Clayton7260f622011-04-18 08:33:37 +00006321 for (uint32_t i = 0; i < num_threads; i++)
6322 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006323 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006324 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006325 {
6326 if (only_threads_with_stop_reason)
6327 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006328 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006329 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006330 continue;
6331 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006332 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006333 start_frame,
6334 num_frames,
6335 num_frames_with_source);
6336 ++num_thread_infos_dumped;
6337 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006338 else
6339 {
6340 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6341 if (log)
6342 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6343
6344 }
Greg Clayton7260f622011-04-18 08:33:37 +00006345 }
6346 return num_thread_infos_dumped;
6347}
6348
Greg Claytona9f40ad2012-02-22 04:37:26 +00006349void
6350Process::AddInvalidMemoryRegion (const LoadRange &region)
6351{
6352 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6353}
6354
6355bool
6356Process::RemoveInvalidMemoryRange (const LoadRange &region)
6357{
6358 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6359}
6360
Jim Ingham372787f2012-04-07 00:00:41 +00006361void
6362Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6363{
6364 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6365}
6366
6367bool
6368Process::RunPreResumeActions ()
6369{
6370 bool result = true;
6371 while (!m_pre_resume_actions.empty())
6372 {
6373 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6374 m_pre_resume_actions.pop_back();
6375 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006376 if (result == true)
6377 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006378 }
6379 return result;
6380}
6381
6382void
6383Process::ClearPreResumeActions ()
6384{
6385 m_pre_resume_actions.clear();
6386}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006387
Zachary Turner93749ab2015-03-03 21:51:25 +00006388ProcessRunLock &
6389Process::GetRunLock()
6390{
6391 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6392 return m_private_run_lock;
6393 else
6394 return m_public_run_lock;
6395}
6396
Greg Claytonfa559e52012-05-18 02:38:05 +00006397void
6398Process::Flush ()
6399{
6400 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006401 m_extended_thread_list.Flush();
6402 m_extended_thread_stop_id = 0;
6403 m_queue_list.Clear();
6404 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006405}
Greg Clayton90ba8112012-12-05 00:16:59 +00006406
6407void
6408Process::DidExec ()
6409{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006410 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6411 if (log)
6412 log->Printf ("Process::%s()", __FUNCTION__);
6413
Greg Clayton90ba8112012-12-05 00:16:59 +00006414 Target &target = GetTarget();
6415 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006416 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006417 m_dynamic_checkers_ap.reset();
6418 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006419 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006420 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006421 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006422 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006423 m_image_tokens.clear();
6424 m_allocated_memory_cache.Clear();
6425 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006426 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006427 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006428 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006429 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006430 DoDidExec();
6431 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006432 // Flush the process (threads and all stack frames) after running CompleteAttach()
6433 // in case the dynamic loader loaded things in new locations.
6434 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006435
6436 // After we figure out what was loaded/unloaded in CompleteAttach,
6437 // we need to let the target know so it can do any cleanup it needs to.
6438 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006439}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006440
Jim Ingham1460e4b2014-01-10 23:46:59 +00006441addr_t
6442Process::ResolveIndirectFunction(const Address *address, Error &error)
6443{
6444 if (address == nullptr)
6445 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006446 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006447 return LLDB_INVALID_ADDRESS;
6448 }
6449
6450 addr_t function_addr = LLDB_INVALID_ADDRESS;
6451
6452 addr_t addr = address->GetLoadAddress(&GetTarget());
6453 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6454 if (iter != m_resolved_indirect_addresses.end())
6455 {
6456 function_addr = (*iter).second;
6457 }
6458 else
6459 {
6460 if (!InferiorCall(this, address, function_addr))
6461 {
6462 Symbol *symbol = address->CalculateSymbolContextSymbol();
6463 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6464 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6465 function_addr = LLDB_INVALID_ADDRESS;
6466 }
6467 else
6468 {
6469 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6470 }
6471 }
6472 return function_addr;
6473}
6474
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006475void
6476Process::ModulesDidLoad (ModuleList &module_list)
6477{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006478 SystemRuntime *sys_runtime = GetSystemRuntime();
6479 if (sys_runtime)
6480 {
6481 sys_runtime->ModulesDidLoad (module_list);
6482 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006483
Kuba Breckaafdf8422014-10-10 23:43:03 +00006484 GetJITLoaders().ModulesDidLoad (module_list);
6485
6486 // Give runtimes a chance to be created.
6487 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6488
6489 // Tell runtimes about new modules.
6490 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6491 {
6492 InstrumentationRuntimeSP runtime = pos->second;
6493 runtime->ModulesDidLoad(module_list);
6494 }
6495
Greg Clayton35ca64b2015-04-16 17:13:34 +00006496 // Let any language runtimes we have already created know
6497 // about the modules that loaded.
6498
6499 // Iterate over a copy of this language runtime list in case
6500 // the language runtime ModulesDidLoad somehow causes the language
6501 // riuntime to be unloaded.
6502 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6503 for (const auto &pair: language_runtimes)
6504 {
6505 // We must check language_runtime_sp to make sure it is not
6506 // NULL as we might cache the fact that we didn't have a
6507 // language runtime for a language.
6508 LanguageRuntimeSP language_runtime_sp = pair.second;
6509 if (language_runtime_sp)
6510 language_runtime_sp->ModulesDidLoad(module_list);
6511 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006512}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006513
6514ThreadCollectionSP
6515Process::GetHistoryThreads(lldb::addr_t addr)
6516{
6517 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006518
Kuba Breckaa51ea382014-09-06 01:33:13 +00006519 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6520
6521 if (! memory_history.get()) {
6522 return threads;
6523 }
6524
6525 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6526
6527 return threads;
6528}
Kuba Brecka63927542014-10-11 01:59:32 +00006529
6530InstrumentationRuntimeSP
6531Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6532{
6533 InstrumentationRuntimeCollection::iterator pos;
6534 pos = m_instrumentation_runtimes.find (type);
6535 if (pos == m_instrumentation_runtimes.end())
6536 {
6537 return InstrumentationRuntimeSP();
6538 }
6539 else
6540 return (*pos).second;
6541}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006542
6543bool
6544Process::GetModuleSpec(const FileSpec& module_file_spec,
6545 const ArchSpec& arch,
6546 ModuleSpec& module_spec)
6547{
6548 module_spec.Clear();
6549 return false;
6550}