blob: e2bb2e48c41ed73f5bc5f77392e596a1bded7bca [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
10#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include "lldb/Breakpoint/StoppointCallbackContext.h"
12#include "lldb/Breakpoint/BreakpointLocation.h"
13#include "lldb/Core/Event.h"
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000016#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000017#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000020#include "lldb/Core/StreamFile.h"
Jim Ingham151c0322015-09-15 21:13:50 +000021#include "lldb/Expression/UserExpression.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000022#include "lldb/Expression/IRDynamicChecks.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000023#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000025#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000026#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000027#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000029#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000030#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000031#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000034#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000035#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000036#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000037#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000038#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000039#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000040#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000041#include "lldb/Target/LanguageRuntime.h"
42#include "lldb/Target/CPPLanguageRuntime.h"
43#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000044#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000046#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000047#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Target/Target.h"
49#include "lldb/Target/TargetList.h"
50#include "lldb/Target/Thread.h"
51#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000052#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000053#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000054#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000055#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056
57using namespace lldb;
58using namespace lldb_private;
59
Greg Clayton67cc0632012-08-22 17:17:09 +000060
61// Comment out line below to disable memory caching, overriding the process setting
62// target.process.disable-memory-cache
63#define ENABLE_MEMORY_CACHING
64
65#ifdef ENABLE_MEMORY_CACHING
66#define DISABLE_MEM_CACHE_DEFAULT false
67#else
68#define DISABLE_MEM_CACHE_DEFAULT true
69#endif
70
71class ProcessOptionValueProperties : public OptionValueProperties
72{
73public:
74 ProcessOptionValueProperties (const ConstString &name) :
75 OptionValueProperties (name)
76 {
77 }
78
79 // This constructor is used when creating ProcessOptionValueProperties when it
80 // is part of a new lldb_private::Process instance. It will copy all current
81 // global property values as needed
82 ProcessOptionValueProperties (ProcessProperties *global_properties) :
83 OptionValueProperties(*global_properties->GetValueProperties())
84 {
85 }
86
87 virtual const Property *
88 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
89 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000090 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000091 // try and grab the setting from the current process if there is one. Else we just
92 // use the one from this instance.
93 if (exe_ctx)
94 {
95 Process *process = exe_ctx->GetProcessPtr();
96 if (process)
97 {
98 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
99 if (this != instance_properties)
100 return instance_properties->ProtectedGetPropertyAtIndex (idx);
101 }
102 }
103 return ProtectedGetPropertyAtIndex (idx);
104 }
105};
106
107static PropertyDefinition
108g_properties[] =
109{
110 { "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 +0000111 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
112 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000113 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
114 { "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 +0000115 { "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 +0000116 { "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 +0000117 { "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 +0000118 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Jason Molendaef7d6412015-08-06 03:27:10 +0000119 { "optimization-warnings" , OptionValue::eTypeBoolean, false, true, NULL, NULL, "If true, warn when stopped in code that is optimized where stepping and variable availability may not behave as expected." },
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,
Jason Molendaef7d6412015-08-06 03:27:10 +0000131 ePropertyMemCacheLineSize,
132 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000133};
134
Greg Clayton332e8b12015-01-13 21:13:08 +0000135ProcessProperties::ProcessProperties (lldb_private::Process *process) :
136 Properties (),
137 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000138{
Greg Clayton332e8b12015-01-13 21:13:08 +0000139 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000140 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000141 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000142 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
143 m_collection_sp->Initialize(g_properties);
144 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000145 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000146 true,
147 Thread::GetGlobalProperties()->GetValueProperties());
148 }
149 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000150 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000151 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000152 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
153 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000154}
155
156ProcessProperties::~ProcessProperties()
157{
158}
159
Greg Clayton332e8b12015-01-13 21:13:08 +0000160void
161ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
162{
163 ProcessProperties *properties = (ProcessProperties *)baton;
164 if (properties->m_process)
165 properties->m_process->LoadOperatingSystemPlugin(true);
166}
167
Greg Clayton67cc0632012-08-22 17:17:09 +0000168bool
169ProcessProperties::GetDisableMemoryCache() const
170{
171 const uint32_t idx = ePropertyDisableMemCache;
172 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
173}
174
Jason Molendaf0340c92014-09-03 22:30:54 +0000175uint64_t
176ProcessProperties::GetMemoryCacheLineSize() const
177{
178 const uint32_t idx = ePropertyMemCacheLineSize;
179 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
180}
181
Greg Clayton67cc0632012-08-22 17:17:09 +0000182Args
183ProcessProperties::GetExtraStartupCommands () const
184{
185 Args args;
186 const uint32_t idx = ePropertyExtraStartCommand;
187 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
188 return args;
189}
190
191void
192ProcessProperties::SetExtraStartupCommands (const Args &args)
193{
194 const uint32_t idx = ePropertyExtraStartCommand;
195 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
196}
197
Greg Claytonc9d645d2012-10-18 22:40:37 +0000198FileSpec
199ProcessProperties::GetPythonOSPluginPath () const
200{
201 const uint32_t idx = ePropertyPythonOSPluginPath;
202 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
203}
204
205void
206ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
207{
208 const uint32_t idx = ePropertyPythonOSPluginPath;
209 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
210}
211
Jim Ingham184e9812013-01-15 02:47:48 +0000212
213bool
214ProcessProperties::GetIgnoreBreakpointsInExpressions () const
215{
216 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
217 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
218}
219
220void
221ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
222{
223 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
224 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
225}
226
227bool
228ProcessProperties::GetUnwindOnErrorInExpressions () const
229{
230 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
231 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
232}
233
234void
235ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
236{
237 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
238 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
239}
240
Jim Ingham29950772013-01-26 02:19:28 +0000241bool
242ProcessProperties::GetStopOnSharedLibraryEvents () const
243{
244 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
245 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
246}
247
248void
249ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
250{
251 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
252 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
253}
254
Jim Inghamacff8952013-05-02 00:27:30 +0000255bool
256ProcessProperties::GetDetachKeepsStopped () const
257{
258 const uint32_t idx = ePropertyDetachKeepsStopped;
259 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
260}
261
262void
263ProcessProperties::SetDetachKeepsStopped (bool stop)
264{
265 const uint32_t idx = ePropertyDetachKeepsStopped;
266 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
267}
268
Jason Molendaef7d6412015-08-06 03:27:10 +0000269bool
270ProcessProperties::GetWarningsOptimization () const
271{
272 const uint32_t idx = ePropertyWarningOptimization;
273 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
274}
275
Greg Clayton32e0a752011-03-30 18:16:51 +0000276void
Greg Clayton8b82f082011-04-12 05:54:46 +0000277ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000278{
279 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000280 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000281 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000282
283 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000284 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000285
286 if (m_executable)
287 {
288 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
289 s.PutCString (" file = ");
290 m_executable.Dump(&s);
291 s.EOL();
292 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000294 if (argc > 0)
295 {
296 for (uint32_t i=0; i<argc; i++)
297 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000299 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000301 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000302 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000303 }
304 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000305
306 const uint32_t envc = m_environment.GetArgumentCount();
307 if (envc > 0)
308 {
309 for (uint32_t i=0; i<envc; i++)
310 {
311 const char *env = m_environment.GetArgumentAtIndex(i);
312 if (i < 10)
313 s.Printf (" env[%u] = %s\n", i, env);
314 else
315 s.Printf ("env[%u] = %s\n", i, env);
316 }
317 }
318
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000319 if (m_arch.IsValid())
320 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
321
Greg Clayton8b82f082011-04-12 05:54:46 +0000322 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000323 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000324 cstr = platform->GetUserName (m_uid);
325 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000326 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000327 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000328 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000329 cstr = platform->GetGroupName (m_gid);
330 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000331 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000332 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000333 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000334 cstr = platform->GetUserName (m_euid);
335 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000336 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000338 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000339 cstr = platform->GetGroupName (m_egid);
340 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000341 }
342}
343
344void
Greg Clayton8b82f082011-04-12 05:54:46 +0000345ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000346{
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 const char *label;
348 if (show_args || verbose)
349 label = "ARGUMENTS";
350 else
351 label = "NAME";
352
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000353 if (verbose)
354 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000355 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000356 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
357 }
358 else
359 {
Jim Ingham368ac222014-08-15 17:05:27 +0000360 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
361 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000362 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000363}
364
365void
Greg Clayton8b82f082011-04-12 05:54:46 +0000366ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000367{
368 if (m_pid != LLDB_INVALID_PROCESS_ID)
369 {
370 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000371 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000372
Greg Clayton32e0a752011-03-30 18:16:51 +0000373
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000374 if (verbose)
375 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000376 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000377 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
378 s.Printf ("%-10s ", cstr);
379 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000380 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000381
Greg Clayton8b82f082011-04-12 05:54:46 +0000382 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
384 s.Printf ("%-10s ", cstr);
385 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000386 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000387
Greg Clayton8b82f082011-04-12 05:54:46 +0000388 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000389 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
390 s.Printf ("%-10s ", cstr);
391 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000392 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000393
Greg Clayton8b82f082011-04-12 05:54:46 +0000394 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000395 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
396 s.Printf ("%-10s ", cstr);
397 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000398 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000399 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
400 }
401 else
402 {
Jim Ingham368ac222014-08-15 17:05:27 +0000403 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000404 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000405 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000406 }
407
Greg Clayton8b82f082011-04-12 05:54:46 +0000408 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000409 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000410 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000411 if (argc > 0)
412 {
413 for (uint32_t i=0; i<argc; i++)
414 {
415 if (i > 0)
416 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000417 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000418 }
419 }
420 }
421 else
422 {
423 s.PutCString (GetName());
424 }
425
426 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000427 }
428}
429
Greg Clayton8b82f082011-04-12 05:54:46 +0000430Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000431ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000432{
433 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000434 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000435
436 switch (short_option)
437 {
438 case 's': // Stop at program entry point
439 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
440 break;
441
Greg Clayton8b82f082011-04-12 05:54:46 +0000442 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000443 {
444 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000445 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000446 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000447 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000448 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000449
450 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000451 {
452 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000453 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000454 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000455 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000456 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000457
458 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000459 {
460 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000461 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000462 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000463 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000464 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000465
Greg Clayton8b82f082011-04-12 05:54:46 +0000466 case 'p': // Process plug-in name
467 launch_info.SetProcessPluginName (option_arg);
468 break;
469
470 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000471 {
472 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000473 const FileSpec dev_null{"/dev/null", false};
474 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000475 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000476 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000477 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000478 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000479 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000480 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000481 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000482
483 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000484 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000485 break;
486
487 case 't': // Open process in new terminal window
488 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
489 break;
490
491 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000492 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
493 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 break;
495
Todd Fiala51637922014-08-19 17:40:43 +0000496 case 'A': // Disable ASLR.
497 {
498 bool success;
499 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
500 if (success)
501 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
502 else
503 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000504 break;
Todd Fiala51637922014-08-19 17:40:43 +0000505 }
506
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000507 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000508 {
509 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000510 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000511 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000512 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000513 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000514 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000515 break;
516 }
517
Todd Fiala51637922014-08-19 17:40:43 +0000518 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000519 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000520 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000521 else
Zachary Turner10687b02014-10-20 17:46:43 +0000522 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000523 break;
524
Greg Clayton8b82f082011-04-12 05:54:46 +0000525 case 'v':
526 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
527 break;
528
529 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000530 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000531 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000532 }
533 return error;
534}
535
536OptionDefinition
537ProcessLaunchCommandOptions::g_option_table[] =
538{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000539{ 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 +0000540{ 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 +0000541{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
542{ 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."},
543{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
544{ 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 +0000545{ 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 +0000546
Zachary Turnerd37221d2014-07-09 16:31:49 +0000547{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
548{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
549{ 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 +0000550
Zachary Turnerd37221d2014-07-09 16:31:49 +0000551{ 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 +0000552
Zachary Turnerd37221d2014-07-09 16:31:49 +0000553{ 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 +0000554{ 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 +0000555{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000556};
557
558
559
560bool
561ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000562{
563 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
564 return true;
565 const char *match_name = m_match_info.GetName();
566 if (!match_name)
567 return true;
568
569 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
570}
571
572bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000573ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000574{
575 if (!NameMatches (proc_info.GetName()))
576 return false;
577
578 if (m_match_info.ProcessIDIsValid() &&
579 m_match_info.GetProcessID() != proc_info.GetProcessID())
580 return false;
581
582 if (m_match_info.ParentProcessIDIsValid() &&
583 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
584 return false;
585
Greg Clayton8b82f082011-04-12 05:54:46 +0000586 if (m_match_info.UserIDIsValid () &&
587 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000588 return false;
589
Greg Clayton8b82f082011-04-12 05:54:46 +0000590 if (m_match_info.GroupIDIsValid () &&
591 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000592 return false;
593
594 if (m_match_info.EffectiveUserIDIsValid () &&
595 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
596 return false;
597
598 if (m_match_info.EffectiveGroupIDIsValid () &&
599 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
600 return false;
601
602 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000603 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000604 return false;
605 return true;
606}
607
608bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000609ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000610{
611 if (m_name_match_type != eNameMatchIgnore)
612 return false;
613
614 if (m_match_info.ProcessIDIsValid())
615 return false;
616
617 if (m_match_info.ParentProcessIDIsValid())
618 return false;
619
Greg Clayton8b82f082011-04-12 05:54:46 +0000620 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000621 return false;
622
Greg Clayton8b82f082011-04-12 05:54:46 +0000623 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000624 return false;
625
626 if (m_match_info.EffectiveUserIDIsValid ())
627 return false;
628
629 if (m_match_info.EffectiveGroupIDIsValid ())
630 return false;
631
632 if (m_match_info.GetArchitecture().IsValid())
633 return false;
634
635 if (m_match_all_users)
636 return false;
637
638 return true;
639
640}
641
642void
Greg Clayton8b82f082011-04-12 05:54:46 +0000643ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000644{
645 m_match_info.Clear();
646 m_name_match_type = eNameMatchIgnore;
647 m_match_all_users = false;
648}
Greg Clayton58be07b2011-01-07 06:08:19 +0000649
Greg Claytonc3776bf2012-02-09 06:16:32 +0000650ProcessSP
Zachary Turner7529df92015-09-01 20:02:29 +0000651Process::FindPlugin (lldb::TargetSP target_sp, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652{
Greg Clayton949e8222013-01-16 17:29:04 +0000653 static uint32_t g_process_unique_id = 0;
654
Greg Claytonc3776bf2012-02-09 06:16:32 +0000655 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000656 ProcessCreateInstance create_callback = NULL;
657 if (plugin_name)
658 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000659 ConstString const_plugin_name(plugin_name);
660 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661 if (create_callback)
662 {
Zachary Turner7529df92015-09-01 20:02:29 +0000663 process_sp = create_callback(target_sp, listener, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000664 if (process_sp)
665 {
Zachary Turner7529df92015-09-01 20:02:29 +0000666 if (process_sp->CanDebug(target_sp, true))
Greg Clayton949e8222013-01-16 17:29:04 +0000667 {
668 process_sp->m_process_unique_id = ++g_process_unique_id;
669 }
670 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000671 process_sp.reset();
672 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673 }
674 }
675 else
676 {
Greg Claytonc982c762010-07-09 20:39:50 +0000677 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678 {
Zachary Turner7529df92015-09-01 20:02:29 +0000679 process_sp = create_callback(target_sp, listener, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000680 if (process_sp)
681 {
Zachary Turner7529df92015-09-01 20:02:29 +0000682 if (process_sp->CanDebug(target_sp, false))
Greg Clayton949e8222013-01-16 17:29:04 +0000683 {
684 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000685 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000686 }
687 else
688 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000689 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000690 }
691 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000692 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000693}
694
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000695ConstString &
696Process::GetStaticBroadcasterClass ()
697{
698 static ConstString class_name ("lldb.process");
699 return class_name;
700}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701
702//----------------------------------------------------------------------
703// Process constructor
704//----------------------------------------------------------------------
Zachary Turner7529df92015-09-01 20:02:29 +0000705Process::Process(lldb::TargetSP target_sp, Listener &listener) :
706 Process(target_sp, listener, UnixSignals::Create(HostInfo::GetArchitecture()))
Todd Fiala4ceced32014-08-29 17:35:57 +0000707{
708 // This constructor just delegates to the full Process constructor,
709 // defaulting to using the Host's UnixSignals.
710}
711
Zachary Turner7529df92015-09-01 20:02:29 +0000712Process::Process(lldb::TargetSP target_sp, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000713 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 UserID (LLDB_INVALID_PROCESS_ID),
Zachary Turner7529df92015-09-01 20:02:29 +0000715 Broadcaster (&(target_sp->GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
716 m_target_sp (target_sp),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717 m_public_state (eStateUnloaded),
718 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000719 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
720 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721 m_private_state_listener ("lldb.process.internal_state_listener"),
722 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000723 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000724 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000726 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727 m_exit_status (-1),
728 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000729 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000730 m_thread_mutex (Mutex::eMutexTypeRecursive),
731 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000733 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000734 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000735 m_queue_list (this),
736 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000737 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000738 m_image_tokens (),
739 m_listener (listener),
740 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000741 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000742 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000743 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000744 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000745 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000746 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000747 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000748 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000749 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000750 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
751 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32 +0000752 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42 +0000753 m_memory_cache (*this),
754 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000755 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000756 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000757 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000758 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000759 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000760 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58 +0000761 m_finalizing (false),
762 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000763 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000764 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000765 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000766 m_destroy_in_process (false),
Ewan Crawford90ff7912015-07-14 10:56:58 +0000767 m_can_interpret_function_calls(false),
Jason Molendaef7d6412015-08-06 03:27:10 +0000768 m_warnings_issued (),
Jason Molenda69b6b632013-03-05 03:33:59 +0000769 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000770{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000771 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000772
Greg Clayton5160ce52013-03-27 23:08:40 +0000773 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000775 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000776
Todd Fiala4ceced32014-08-29 17:35:57 +0000777 if (!m_unix_signals_sp)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000778 m_unix_signals_sp = std::make_shared<UnixSignals>();
Todd Fiala4ceced32014-08-29 17:35:57 +0000779
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000780 SetEventName (eBroadcastBitStateChanged, "state-changed");
781 SetEventName (eBroadcastBitInterrupt, "interrupt");
782 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
783 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000784 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000785
Greg Clayton35a4cc52012-10-29 20:52:08 +0000786 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
787 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
788 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
789
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790 listener.StartListeningForEvents (this,
791 eBroadcastBitStateChanged |
792 eBroadcastBitInterrupt |
793 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000794 eBroadcastBitSTDERR |
795 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000796
797 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000798 eBroadcastBitStateChanged |
799 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800
801 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
802 eBroadcastInternalStateControlStop |
803 eBroadcastInternalStateControlPause |
804 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000805 // We need something valid here, even if just the default UnixSignalsSP.
806 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807}
808
809//----------------------------------------------------------------------
810// Destructor
811//----------------------------------------------------------------------
812Process::~Process()
813{
Greg Clayton5160ce52013-03-27 23:08:40 +0000814 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000816 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000817 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000818
819 // ThreadList::Clear() will try to acquire this process's mutex, so
820 // explicitly clear the thread list here to ensure that the mutex
821 // is not destroyed before the thread list.
822 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823}
824
Greg Clayton67cc0632012-08-22 17:17:09 +0000825const ProcessPropertiesSP &
826Process::GetGlobalProperties()
827{
828 static ProcessPropertiesSP g_settings_sp;
829 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000830 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000831 return g_settings_sp;
832}
833
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834void
835Process::Finalize()
836{
Greg Claytonc00ca312015-04-02 18:44:58 +0000837 m_finalizing = true;
838
Ilia Kc7efd562015-03-26 07:40:40 +0000839 // Destroy this process if needed
840 switch (GetPrivateState())
841 {
842 case eStateConnected:
843 case eStateAttaching:
844 case eStateLaunching:
845 case eStateStopped:
846 case eStateRunning:
847 case eStateStepping:
848 case eStateCrashed:
849 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000850 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000851 break;
852
853 case eStateInvalid:
854 case eStateUnloaded:
855 case eStateDetached:
856 case eStateExited:
857 break;
858 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000859
Greg Clayton1ed54f52011-10-01 00:45:15 +0000860 // Clear our broadcaster before we proceed with destroying
861 Broadcaster::Clear();
862
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000863 // Do any cleanup needed prior to being destructed... Subclasses
864 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000865
866 // We need to destroy the loader before the derived Process class gets destroyed
867 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000868 m_dynamic_checkers_ap.reset();
869 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000870 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000871 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000872 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000873 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000874 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000875 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000876 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000877 m_queue_list.Clear();
878 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000879 std::vector<Notifications> empty_notifications;
880 m_notifications.swap(empty_notifications);
881 m_image_tokens.clear();
882 m_memory_cache.Clear();
883 m_allocated_memory_cache.Clear();
884 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000885 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000886 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000887 m_stop_info_override_callback = NULL;
Greg Clayton08765fa2015-05-28 03:24:30 +0000888 // Clear the last natural stop ID since it has a strong
889 // reference to this process
890 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000891//#ifdef LLDB_CONFIGURATION_DEBUG
892// StreamFile s(stdout, false);
893// EventSP event_sp;
894// while (m_private_state_listener.GetNextEvent(event_sp))
895// {
896// event_sp->Dump (&s);
897// s.EOL();
898// }
899//#endif
900 // We have to be very careful here as the m_private_state_listener might
901 // contain events that have ProcessSP values in them which can keep this
902 // process around forever. These events need to be cleared out.
903 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000904 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
905 m_public_run_lock.SetStopped();
906 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
907 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000908 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000909}
910
911void
912Process::RegisterNotificationCallbacks (const Notifications& callbacks)
913{
914 m_notifications.push_back(callbacks);
915 if (callbacks.initialize != NULL)
916 callbacks.initialize (callbacks.baton, this);
917}
918
919bool
920Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
921{
922 std::vector<Notifications>::iterator pos, end = m_notifications.end();
923 for (pos = m_notifications.begin(); pos != end; ++pos)
924 {
925 if (pos->baton == callbacks.baton &&
926 pos->initialize == callbacks.initialize &&
927 pos->process_state_changed == callbacks.process_state_changed)
928 {
929 m_notifications.erase(pos);
930 return true;
931 }
932 }
933 return false;
934}
935
936void
937Process::SynchronouslyNotifyStateChanged (StateType state)
938{
939 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
940 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
941 {
942 if (notification_pos->process_state_changed)
943 notification_pos->process_state_changed (notification_pos->baton, this, state);
944 }
945}
946
947// FIXME: We need to do some work on events before the general Listener sees them.
948// For instance if we are continuing from a breakpoint, we need to ensure that we do
949// the little "insert real insn, step & stop" trick. But we can't do that when the
950// event is delivered by the broadcaster - since that is done on the thread that is
951// waiting for new events, so if we needed more than one event for our handling, we would
952// stall. So instead we do it when we fetch the event off of the queue.
953//
954
955StateType
956Process::GetNextEvent (EventSP &event_sp)
957{
958 StateType state = eStateInvalid;
959
960 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
961 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
962
963 return state;
964}
965
Pavel Labath44464872015-05-27 12:40:32 +0000966void
967Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000968{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000969 // don't sync (potentially context switch) in case where there is no process IO
Pavel Labath44464872015-05-27 12:40:32 +0000970 if (! m_process_input_reader)
971 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000972
Pavel Labath44464872015-05-27 12:40:32 +0000973 TimeValue timeout = TimeValue::Now();
974 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
975 uint32_t new_iohandler_id = 0;
976 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000977
Pavel Labath44464872015-05-27 12:40:32 +0000978 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
979 if (log)
980 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, new value is %u", __FUNCTION__, iohandler_id, new_iohandler_id);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000981}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982
983StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000984Process::WaitForProcessToStop (const TimeValue *timeout,
985 EventSP *event_sp_ptr,
986 bool wait_always,
987 Listener *hijack_listener,
988 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989{
Jim Ingham4b536182011-08-09 02:12:22 +0000990 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
991 // We have to actually check each event, and in the case of a stopped event check the restarted flag
992 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000993 if (event_sp_ptr)
994 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000995 StateType state = GetState();
996 // If we are exited or detached, we won't ever get back to any
997 // other valid state...
998 if (state == eStateDetached || state == eStateExited)
999 return state;
1000
Daniel Malea9e9919f2013-10-09 16:56:28 +00001001 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1002 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001003 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
1004 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001005
1006 if (!wait_always &&
1007 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +00001008 StateIsStoppedState(GetPrivateState(), true))
1009 {
Daniel Malea9e9919f2013-10-09 16:56:28 +00001010 if (log)
1011 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1012 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001013 // We need to toggle the run lock as this won't get done in
1014 // SetPublicState() if the process is hijacked.
1015 if (hijack_listener)
1016 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001017 return state;
1018 }
1019
Jim Ingham4b536182011-08-09 02:12:22 +00001020 while (state != eStateInvalid)
1021 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001022 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001023 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001024 if (event_sp_ptr && event_sp)
1025 *event_sp_ptr = event_sp;
1026
Greg Claytondc6224e2014-10-21 01:00:42 +00001027 bool pop_process_io_handler = hijack_listener != NULL;
1028 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1029
Jim Ingham4b536182011-08-09 02:12:22 +00001030 switch (state)
1031 {
1032 case eStateCrashed:
1033 case eStateDetached:
1034 case eStateExited:
1035 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001036 // We need to toggle the run lock as this won't get done in
1037 // SetPublicState() if the process is hijacked.
1038 if (hijack_listener)
1039 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001040 return state;
1041 case eStateStopped:
1042 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1043 continue;
1044 else
Greg Clayton44d93782014-01-27 23:43:24 +00001045 {
1046 // We need to toggle the run lock as this won't get done in
1047 // SetPublicState() if the process is hijacked.
1048 if (hijack_listener)
1049 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001050 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001051 }
Jim Ingham4b536182011-08-09 02:12:22 +00001052 default:
1053 continue;
1054 }
1055 }
1056 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057}
1058
Greg Claytondc6224e2014-10-21 01:00:42 +00001059bool
1060Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1061 Stream *stream,
1062 bool &pop_process_io_handler)
1063{
1064 const bool handle_pop = pop_process_io_handler == true;
1065
1066 pop_process_io_handler = false;
1067 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1068
1069 if (!process_sp)
1070 return false;
1071
1072 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1073 if (event_state == eStateInvalid)
1074 return false;
1075
1076 switch (event_state)
1077 {
1078 case eStateInvalid:
1079 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001080 case eStateAttaching:
1081 case eStateLaunching:
1082 case eStateStepping:
1083 case eStateDetached:
1084 {
1085 if (stream)
1086 stream->Printf ("Process %" PRIu64 " %s\n",
1087 process_sp->GetID(),
1088 StateAsCString (event_state));
1089
1090 if (event_state == eStateDetached)
1091 pop_process_io_handler = true;
1092 }
1093 break;
1094
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001095 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001096 case eStateRunning:
1097 // Don't be chatty when we run...
1098 break;
1099
1100 case eStateExited:
1101 if (stream)
1102 process_sp->GetStatus(*stream);
1103 pop_process_io_handler = true;
1104 break;
1105
1106 case eStateStopped:
1107 case eStateCrashed:
1108 case eStateSuspended:
1109 // Make sure the program hasn't been auto-restarted:
1110 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1111 {
1112 if (stream)
1113 {
1114 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1115 if (num_reasons > 0)
1116 {
1117 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1118 if (num_reasons == 1)
1119 {
1120 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1121 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1122 process_sp->GetID(),
1123 reason ? reason : "<UNKNOWN REASON>");
1124 }
1125 else
1126 {
1127 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1128 process_sp->GetID());
1129
1130
1131 for (size_t i = 0; i < num_reasons; i++)
1132 {
1133 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1134 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1135 }
1136 }
1137 }
1138 }
1139 }
1140 else
1141 {
1142 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1143 {
1144 ThreadList &thread_list = process_sp->GetThreadList();
1145 Mutex::Locker locker (thread_list.GetMutex());
1146
1147 ThreadSP curr_thread (thread_list.GetSelectedThread());
1148 ThreadSP thread;
1149 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1150 if (curr_thread)
1151 curr_thread_stop_reason = curr_thread->GetStopReason();
1152 if (!curr_thread ||
1153 !curr_thread->IsValid() ||
1154 curr_thread_stop_reason == eStopReasonInvalid ||
1155 curr_thread_stop_reason == eStopReasonNone)
1156 {
1157 // Prefer a thread that has just completed its plan over another thread as current thread.
1158 ThreadSP plan_thread;
1159 ThreadSP other_thread;
Jim Inghamce400d92015-07-08 00:06:30 +00001160
Greg Claytondc6224e2014-10-21 01:00:42 +00001161 const size_t num_threads = thread_list.GetSize();
1162 size_t i;
1163 for (i = 0; i < num_threads; ++i)
1164 {
1165 thread = thread_list.GetThreadAtIndex(i);
1166 StopReason thread_stop_reason = thread->GetStopReason();
1167 switch (thread_stop_reason)
1168 {
1169 case eStopReasonInvalid:
1170 case eStopReasonNone:
1171 break;
1172
Jim Inghamce400d92015-07-08 00:06:30 +00001173 case eStopReasonSignal:
1174 {
1175 // Don't select a signal thread if we weren't going to stop at that
1176 // signal. We have to have had another reason for stopping here, and
1177 // the user doesn't want to see this thread.
1178 uint64_t signo = thread->GetStopInfo()->GetValue();
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001179 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
Jim Inghamce400d92015-07-08 00:06:30 +00001180 {
1181 if (!other_thread)
1182 other_thread = thread;
1183 }
1184 break;
1185 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001186 case eStopReasonTrace:
1187 case eStopReasonBreakpoint:
1188 case eStopReasonWatchpoint:
Greg Claytondc6224e2014-10-21 01:00:42 +00001189 case eStopReasonException:
1190 case eStopReasonExec:
1191 case eStopReasonThreadExiting:
1192 case eStopReasonInstrumentation:
1193 if (!other_thread)
1194 other_thread = thread;
1195 break;
1196 case eStopReasonPlanComplete:
1197 if (!plan_thread)
1198 plan_thread = thread;
1199 break;
1200 }
1201 }
1202 if (plan_thread)
1203 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1204 else if (other_thread)
1205 thread_list.SetSelectedThreadByID (other_thread->GetID());
1206 else
1207 {
1208 if (curr_thread && curr_thread->IsValid())
1209 thread = curr_thread;
1210 else
1211 thread = thread_list.GetThreadAtIndex(0);
1212
1213 if (thread)
1214 thread_list.SetSelectedThreadByID (thread->GetID());
1215 }
1216 }
1217 }
1218 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1219 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1220 // have a hard time restarting the process.
1221 if (stream)
1222 {
1223 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1224 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1225 {
1226 const bool only_threads_with_stop_reason = true;
1227 const uint32_t start_frame = 0;
1228 const uint32_t num_frames = 1;
1229 const uint32_t num_frames_with_source = 1;
1230 process_sp->GetStatus(*stream);
1231 process_sp->GetThreadStatus (*stream,
1232 only_threads_with_stop_reason,
1233 start_frame,
1234 num_frames,
1235 num_frames_with_source);
1236 }
1237 else
1238 {
1239 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1240 if (target_idx != UINT32_MAX)
1241 stream->Printf ("Target %d: (", target_idx);
1242 else
1243 stream->Printf ("Target <unknown index>: (");
1244 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1245 stream->Printf (") stopped.\n");
1246 }
1247 }
1248
1249 // Pop the process IO handler
1250 pop_process_io_handler = true;
1251 }
1252 break;
1253 }
1254
1255 if (handle_pop && pop_process_io_handler)
1256 process_sp->PopProcessIOHandler();
1257
1258 return true;
1259}
1260
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001261
1262StateType
1263Process::WaitForState
1264(
1265 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001266 const StateType *match_states,
1267 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268)
1269{
1270 EventSP event_sp;
1271 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001272 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001273 while (state != eStateInvalid)
1274 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001275 // If we are exited or detached, we won't ever get back to any
1276 // other valid state...
1277 if (state == eStateDetached || state == eStateExited)
1278 return state;
1279
Greg Clayton44d93782014-01-27 23:43:24 +00001280 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281
1282 for (i=0; i<num_match_states; ++i)
1283 {
1284 if (match_states[i] == state)
1285 return state;
1286 }
1287 }
1288 return state;
1289}
1290
Jim Ingham30f9b212010-10-11 23:53:14 +00001291bool
1292Process::HijackProcessEvents (Listener *listener)
1293{
1294 if (listener != NULL)
1295 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001296 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001297 }
1298 else
1299 return false;
1300}
1301
1302void
1303Process::RestoreProcessEvents ()
1304{
1305 RestoreBroadcaster();
1306}
1307
Jim Ingham0f16e732011-02-08 05:20:59 +00001308bool
1309Process::HijackPrivateProcessEvents (Listener *listener)
1310{
1311 if (listener != NULL)
1312 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001313 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001314 }
1315 else
1316 return false;
1317}
1318
1319void
1320Process::RestorePrivateProcessEvents ()
1321{
1322 m_private_state_broadcaster.RestoreBroadcaster();
1323}
1324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001326Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001327{
Greg Clayton5160ce52013-03-27 23:08:40 +00001328 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329
1330 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001331 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1332 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333
Greg Clayton44d93782014-01-27 23:43:24 +00001334 Listener *listener = hijack_listener;
1335 if (listener == NULL)
1336 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001337
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001339 if (listener->WaitForEventForBroadcasterWithType (timeout,
1340 this,
1341 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1342 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001343 {
1344 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1345 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1346 else if (log)
1347 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1348 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001349
1350 if (log)
1351 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001352 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 StateAsCString(state));
1354 return state;
1355}
1356
1357Event *
1358Process::PeekAtStateChangedEvents ()
1359{
Greg Clayton5160ce52013-03-27 23:08:40 +00001360 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361
1362 if (log)
1363 log->Printf ("Process::%s...", __FUNCTION__);
1364
1365 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001366 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1367 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368 if (log)
1369 {
1370 if (event_ptr)
1371 {
1372 log->Printf ("Process::%s (event_ptr) => %s",
1373 __FUNCTION__,
1374 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1375 }
1376 else
1377 {
1378 log->Printf ("Process::%s no events found",
1379 __FUNCTION__);
1380 }
1381 }
1382 return event_ptr;
1383}
1384
1385StateType
1386Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1387{
Greg Clayton5160ce52013-03-27 23:08:40 +00001388 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001389
1390 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001391 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1392 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001393
1394 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001395 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1396 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001397 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001398 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001399 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1400 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401
1402 // This is a bit of a hack, but when we wait here we could very well return
1403 // to the command-line, and that could disable the log, which would render the
1404 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001406 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1407 __FUNCTION__, static_cast<const void *>(timeout),
1408 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409 return state;
1410}
1411
1412bool
1413Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1414{
Greg Clayton5160ce52013-03-27 23:08:40 +00001415 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416
1417 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001418 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1419 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001420
1421 if (control_only)
1422 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1423 else
1424 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1425}
1426
1427bool
1428Process::IsRunning () const
1429{
1430 return StateIsRunningState (m_public_state.GetValue());
1431}
1432
1433int
1434Process::GetExitStatus ()
1435{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001436 Mutex::Locker locker (m_exit_status_mutex);
1437
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001438 if (m_public_state.GetValue() == eStateExited)
1439 return m_exit_status;
1440 return -1;
1441}
1442
Greg Clayton85851dd2010-12-04 00:10:17 +00001443
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444const char *
1445Process::GetExitDescription ()
1446{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001447 Mutex::Locker locker (m_exit_status_mutex);
1448
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001449 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1450 return m_exit_string.c_str();
1451 return NULL;
1452}
1453
Greg Clayton6779606a2011-01-22 23:43:18 +00001454bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001455Process::SetExitStatus (int status, const char *cstr)
1456{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001457 // Use a mutex to protect setting the exit status.
1458 Mutex::Locker locker (m_exit_status_mutex);
1459
Greg Clayton5160ce52013-03-27 23:08:40 +00001460 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001461 if (log)
1462 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1463 status, status,
1464 cstr ? "\"" : "",
1465 cstr ? cstr : "NULL",
1466 cstr ? "\"" : "");
1467
Greg Clayton6779606a2011-01-22 23:43:18 +00001468 // We were already in the exited state
1469 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001470 {
Greg Clayton385d6032011-01-26 23:47:29 +00001471 if (log)
1472 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001473 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001474 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001475
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001476 m_exit_status = status;
1477 if (cstr)
1478 m_exit_string = cstr;
1479 else
1480 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481
Pavel Labatha9a43372015-09-03 09:30:17 +00001482 // When we exit, we don't need the input reader anymore
Greg Clayton5df78fa2015-05-23 03:54:53 +00001483 if (m_process_input_reader)
1484 {
1485 m_process_input_reader->SetIsDone(true);
1486 m_process_input_reader->Cancel();
1487 m_process_input_reader.reset();
1488 }
Greg Clayton10177aa2010-12-08 05:08:21 +00001489
Greg Clayton08765fa2015-05-28 03:24:30 +00001490 // Clear the last natural stop ID since it has a strong
1491 // reference to this process
1492 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1493
Greg Clayton6779606a2011-01-22 23:43:18 +00001494 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001495
1496 // Allow subclasses to do some cleanup
1497 DidExit ();
1498
Greg Clayton6779606a2011-01-22 23:43:18 +00001499 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500}
1501
1502// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001503// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504// found in the global target list (we want to be completely sure that the
1505// lldb_private::Process doesn't go away before we can deliver the signal.
1506bool
Greg Claytone4e45922011-11-16 05:37:56 +00001507Process::SetProcessExitStatus (void *callback_baton,
1508 lldb::pid_t pid,
1509 bool exited,
1510 int signo, // Zero for no signal
1511 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512)
1513{
Greg Clayton5160ce52013-03-27 23:08:40 +00001514 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001515 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001516 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001517 callback_baton,
1518 pid,
1519 exited,
1520 signo,
1521 exit_status);
1522
1523 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001524 {
Greg Clayton66111032010-06-23 01:19:29 +00001525 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526 if (target_sp)
1527 {
1528 ProcessSP process_sp (target_sp->GetProcessSP());
1529 if (process_sp)
1530 {
1531 const char *signal_cstr = NULL;
1532 if (signo)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001533 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001534
1535 process_sp->SetExitStatus (exit_status, signal_cstr);
1536 }
1537 }
1538 return true;
1539 }
1540 return false;
1541}
1542
1543
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001544void
1545Process::UpdateThreadListIfNeeded ()
1546{
1547 const uint32_t stop_id = GetStopID();
1548 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1549 {
Greg Clayton2637f822011-11-17 01:23:07 +00001550 const StateType state = GetPrivateState();
1551 if (StateIsStoppedState (state, true))
1552 {
1553 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001554 // m_thread_list does have its own mutex, but we need to
1555 // hold onto the mutex between the call to UpdateThreadList(...)
1556 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001557 ThreadList &old_thread_list = m_thread_list;
1558 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001559 ThreadList new_thread_list(this);
1560 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001561 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001562 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001563 {
Jim Ingham09437922013-03-01 20:04:25 +00001564 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1565 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1566 // shutting us down, causing a deadlock.
1567 if (!m_destroy_in_process)
1568 {
1569 OperatingSystem *os = GetOperatingSystem ();
1570 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001571 {
1572 // Clear any old backing threads where memory threads might have been
1573 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001574 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001575 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001576 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001577
Greg Clayton15484402015-05-15 18:40:24 +00001578 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1579 // can run an expression to determine if a SBValue is a dynamic type or not
1580 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1581 // that require running code...
1582
1583 Target &target = GetTarget();
1584 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1585 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1586 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1587
Greg Claytonb3ae8762013-04-12 20:07:46 +00001588 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001589
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001590 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1591 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1592 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 +00001593
1594 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1595 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001596 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001597 else
1598 {
1599 // No OS plug-in, the new thread list is the same as the real thread list
1600 new_thread_list = real_thread_list;
1601 }
Jim Ingham09437922013-03-01 20:04:25 +00001602 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001603
1604 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001605 m_thread_list.Update (new_thread_list);
1606 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001607
Jason Molenda4ff13262013-11-20 00:31:38 +00001608 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1609 {
1610 // Clear any extended threads that we may have accumulated previously
1611 m_extended_thread_list.Clear();
1612 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001613
1614 m_queue_list.Clear();
1615 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001616 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001617 }
Greg Clayton2637f822011-11-17 01:23:07 +00001618 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001619 }
1620}
1621
Jason Molenda5e8dce42013-12-13 00:29:16 +00001622void
1623Process::UpdateQueueListIfNeeded ()
1624{
1625 if (m_system_runtime_ap.get())
1626 {
1627 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1628 {
1629 const StateType state = GetPrivateState();
1630 if (StateIsStoppedState (state, true))
1631 {
1632 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1633 m_queue_list_stop_id = GetLastNaturalStopID();
1634 }
1635 }
1636 }
1637}
1638
Greg Claytona4d87472013-01-18 23:41:08 +00001639ThreadSP
1640Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1641{
1642 OperatingSystem *os = GetOperatingSystem ();
1643 if (os)
1644 return os->CreateThread(tid, context);
1645 return ThreadSP();
1646}
1647
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001648uint32_t
1649Process::GetNextThreadIndexID (uint64_t thread_id)
1650{
1651 return AssignIndexIDToThread(thread_id);
1652}
1653
1654bool
1655Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1656{
1657 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1658 if (iterator == m_thread_id_to_index_id_map.end())
1659 {
1660 return false;
1661 }
1662 else
1663 {
1664 return true;
1665 }
1666}
1667
1668uint32_t
1669Process::AssignIndexIDToThread(uint64_t thread_id)
1670{
1671 uint32_t result = 0;
1672 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1673 if (iterator == m_thread_id_to_index_id_map.end())
1674 {
1675 result = ++m_thread_index_id;
1676 m_thread_id_to_index_id_map[thread_id] = result;
1677 }
1678 else
1679 {
1680 result = iterator->second;
1681 }
1682
1683 return result;
1684}
1685
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686StateType
1687Process::GetState()
1688{
1689 // If any other threads access this we will need a mutex for it
1690 return m_public_state.GetValue ();
1691}
1692
Greg Claytondc6224e2014-10-21 01:00:42 +00001693bool
1694Process::StateChangedIsExternallyHijacked()
1695{
1696 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1697 {
1698 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1699 return true;
1700 }
1701 return false;
1702}
1703
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001704void
Jim Ingham221d51c2013-05-08 00:35:16 +00001705Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001706{
Greg Clayton5160ce52013-03-27 23:08:40 +00001707 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001708 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001709 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001710 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001711 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001712
1713 // On the transition from Run to Stopped, we unlock the writer end of the
1714 // run lock. The lock gets locked in Resume, which is the public API
1715 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001716 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001717 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001718 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001719 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001720 if (log)
1721 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001722 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001723 }
1724 else
1725 {
1726 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1727 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001728 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001729 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001730 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001731 {
1732 if (log)
1733 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001734 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001735 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001736 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001737 }
1738 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001739}
1740
Jim Ingham3b8285d2012-04-19 01:40:33 +00001741Error
1742Process::Resume ()
1743{
Greg Clayton5160ce52013-03-27 23:08:40 +00001744 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001745 if (log)
1746 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001747 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001748 {
1749 Error error("Resume request failed - process still running.");
1750 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001751 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001752 return error;
1753 }
1754 return PrivateResume();
1755}
1756
Greg Claytondc6224e2014-10-21 01:00:42 +00001757Error
1758Process::ResumeSynchronous (Stream *stream)
1759{
1760 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1761 if (log)
1762 log->Printf("Process::ResumeSynchronous -- locking run lock");
1763 if (!m_public_run_lock.TrySetRunning())
1764 {
1765 Error error("Resume request failed - process still running.");
1766 if (log)
1767 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1768 return error;
1769 }
1770
1771 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1772 HijackProcessEvents(listener_sp.get());
1773
1774 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001775 if (error.Success())
1776 {
1777 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1778 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1779 if (!StateIsStoppedState(state, must_be_alive))
1780 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1781 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001782
1783 // Undo the hijacking of process events...
1784 RestoreProcessEvents();
1785
Greg Claytondc6224e2014-10-21 01:00:42 +00001786 return error;
1787}
1788
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001789StateType
1790Process::GetPrivateState ()
1791{
1792 return m_private_state.GetValue();
1793}
1794
1795void
1796Process::SetPrivateState (StateType new_state)
1797{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001798 if (m_finalize_called)
1799 return;
1800
Greg Clayton5160ce52013-03-27 23:08:40 +00001801 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802 bool state_changed = false;
1803
1804 if (log)
1805 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1806
Andrew Kaylor29d65742013-05-10 17:19:04 +00001807 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 Mutex::Locker locker(m_private_state.GetMutex());
1809
1810 const StateType old_state = m_private_state.GetValueNoLock ();
1811 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001812
Greg Claytonaa49c832013-05-03 22:25:56 +00001813 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1814 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1815 if (old_state_is_stopped != new_state_is_stopped)
1816 {
1817 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001818 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001819 else
Ed Maste64fad602013-07-29 20:58:06 +00001820 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001821 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001822
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 if (state_changed)
1824 {
1825 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001826 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001827 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001829 // Note, this currently assumes that all threads in the list
1830 // stop when the process stops. In the future we will want to
1831 // support a debugging model where some threads continue to run
1832 // while others are stopped. When that happens we will either need
1833 // a way for the thread list to identify which threads are stopping
1834 // or create a special thread list containing only threads which
1835 // actually stopped.
1836 //
1837 // The process plugin is responsible for managing the actual
1838 // behavior of the threads and should have stopped any threads
1839 // that are going to stop before we get here.
1840 m_thread_list.DidStop();
1841
Jim Ingham4b536182011-08-09 02:12:22 +00001842 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001843 if (!m_mod_id.IsLastResumeForUserExpression())
1844 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001845 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001846 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001847 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001848 }
Ilia K38810f42015-05-20 10:15:47 +00001849
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001851 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:47 +00001852 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001853 else
Ilia K38810f42015-05-20 10:15:47 +00001854 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855 }
1856 else
1857 {
1858 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001859 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001860 }
1861}
1862
Jim Ingham0faa43f2011-11-08 03:00:11 +00001863void
1864Process::SetRunningUserExpression (bool on)
1865{
1866 m_mod_id.SetRunningUserExpression (on);
1867}
1868
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869addr_t
1870Process::GetImageInfoAddress()
1871{
1872 return LLDB_INVALID_ADDRESS;
1873}
1874
Greg Clayton8f343b02010-11-04 01:54:29 +00001875//----------------------------------------------------------------------
1876// LoadImage
1877//
1878// This function provides a default implementation that works for most
1879// unix variants. Any Process subclasses that need to do shared library
1880// loading differently should override LoadImage and UnloadImage and
1881// do what is needed.
1882//----------------------------------------------------------------------
1883uint32_t
1884Process::LoadImage (const FileSpec &image_spec, Error &error)
1885{
Greg Claytonc00ca312015-04-02 18:44:58 +00001886 if (m_finalizing)
1887 {
1888 error.SetErrorString("process is tearing itself down");
1889 return LLDB_INVALID_IMAGE_TOKEN;
1890 }
1891
Greg Claytonac7a3db2012-04-18 00:05:19 +00001892 char path[PATH_MAX];
1893 image_spec.GetPath(path, sizeof(path));
1894
Greg Clayton8f343b02010-11-04 01:54:29 +00001895 DynamicLoader *loader = GetDynamicLoader();
1896 if (loader)
1897 {
1898 error = loader->CanLoadImage();
1899 if (error.Fail())
1900 return LLDB_INVALID_IMAGE_TOKEN;
1901 }
1902
1903 if (error.Success())
1904 {
1905 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001906
1907 if (thread_sp)
1908 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001909 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001910
1911 if (frame_sp)
1912 {
1913 ExecutionContext exe_ctx;
1914 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001915 EvaluateExpressionOptions expr_options;
1916 expr_options.SetUnwindOnError(true);
1917 expr_options.SetIgnoreBreakpoints(true);
1918 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001919 expr_options.SetResultIsInternal(true);
Jim Ingham151c0322015-09-15 21:13:50 +00001920 expr_options.SetLanguage(eLanguageTypeC_plus_plus);
Jim Ingham4ac04432014-07-19 01:09:16 +00001921
Greg Clayton8f343b02010-11-04 01:54:29 +00001922 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001923 expr.Printf(R"(
1924 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1925 the_result.image_ptr = dlopen ("%s", 2);
1926 if (the_result.image_ptr == (void *) 0x0)
1927 {
1928 the_result.error_str = dlerror();
1929 }
1930 else
1931 {
1932 the_result.error_str = (const char *) 0x0;
1933 }
1934 the_result;
1935 )",
1936 path);
1937 const char *prefix = R"(
1938 extern "C" void* dlopen (const char *path, int mode);
1939 extern "C" const char *dlerror (void);
1940 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001941 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001942 Error expr_error;
Jim Ingham151c0322015-09-15 21:13:50 +00001943 UserExpression::Evaluate (exe_ctx,
1944 expr_options,
1945 expr.GetData(),
1946 prefix,
1947 result_valobj_sp,
1948 expr_error);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001949 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001950 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001951 error = result_valobj_sp->GetError();
1952 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001953 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001954 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001955 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1956 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001957 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001958 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1959 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1960 {
1961 uint32_t image_token = m_image_tokens.size();
1962 m_image_tokens.push_back (image_ptr);
1963 return image_token;
1964 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001965 else if (image_ptr == 0)
1966 {
Jim Ingham6971b862014-07-19 00:37:06 +00001967 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1968 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001969 {
Jim Ingham6971b862014-07-19 00:37:06 +00001970 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001971 {
Enrico Granata2206b482014-10-30 18:27:31 +00001972 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1973 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001974 if (error.Success() && num_chars > 0)
1975 {
1976 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001977 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1978 }
1979 else
1980 {
1981 error.Clear();
1982 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001983 }
1984 }
1985 }
1986 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001987 }
1988 }
1989 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001990 else
1991 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001992 }
1993 }
1994 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001995 if (!error.AsCString())
1996 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001997 return LLDB_INVALID_IMAGE_TOKEN;
1998}
1999
2000//----------------------------------------------------------------------
2001// UnloadImage
2002//
2003// This function provides a default implementation that works for most
2004// unix variants. Any Process subclasses that need to do shared library
2005// loading differently should override LoadImage and UnloadImage and
2006// do what is needed.
2007//----------------------------------------------------------------------
2008Error
2009Process::UnloadImage (uint32_t image_token)
2010{
2011 Error error;
Greg Claytonc00ca312015-04-02 18:44:58 +00002012
2013 if (m_finalizing)
2014 {
2015 error.SetErrorString("process is tearing itself down");
2016 return error;
2017 }
2018
Greg Clayton8f343b02010-11-04 01:54:29 +00002019 if (image_token < m_image_tokens.size())
2020 {
2021 const addr_t image_addr = m_image_tokens[image_token];
2022 if (image_addr == LLDB_INVALID_ADDRESS)
2023 {
2024 error.SetErrorString("image already unloaded");
2025 }
2026 else
2027 {
2028 DynamicLoader *loader = GetDynamicLoader();
2029 if (loader)
2030 error = loader->CanLoadImage();
2031
2032 if (error.Success())
2033 {
2034 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00002035
2036 if (thread_sp)
2037 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002038 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00002039
2040 if (frame_sp)
2041 {
2042 ExecutionContext exe_ctx;
2043 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00002044 EvaluateExpressionOptions expr_options;
2045 expr_options.SetUnwindOnError(true);
2046 expr_options.SetIgnoreBreakpoints(true);
2047 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham151c0322015-09-15 21:13:50 +00002048 expr_options.SetLanguage(eLanguageTypeC_plus_plus);
2049
Greg Clayton8f343b02010-11-04 01:54:29 +00002050 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00002051 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00002052 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00002053 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00002054 Error expr_error;
Jim Ingham151c0322015-09-15 21:13:50 +00002055 UserExpression::Evaluate (exe_ctx,
2056 expr_options,
2057 expr.GetData(),
2058 prefix,
2059 result_valobj_sp,
2060 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002061 if (result_valobj_sp->GetError().Success())
2062 {
2063 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002064 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002065 {
2066 if (scalar.UInt(1))
2067 {
2068 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2069 }
2070 else
2071 {
2072 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2073 }
2074 }
2075 }
2076 else
2077 {
2078 error = result_valobj_sp->GetError();
2079 }
2080 }
2081 }
2082 }
2083 }
2084 }
2085 else
2086 {
2087 error.SetErrorString("invalid image token");
2088 }
2089 return error;
2090}
2091
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002092const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002093Process::GetABI()
2094{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002095 if (!m_abi_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00002096 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002097 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098}
2099
Jim Ingham22777012010-09-23 02:01:19 +00002100LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002101Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002102{
Greg Claytonc00ca312015-04-02 18:44:58 +00002103 if (m_finalizing)
2104 return nullptr;
2105
Jim Ingham22777012010-09-23 02:01:19 +00002106 LanguageRuntimeCollection::iterator pos;
2107 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002108 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002109 {
Jim Inghamab175242012-03-10 00:22:19 +00002110 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002111
Jim Inghamab175242012-03-10 00:22:19 +00002112 m_language_runtimes[language] = runtime_sp;
2113 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002114 }
2115 else
2116 return (*pos).second.get();
2117}
2118
2119CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002120Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002121{
Jim Inghamab175242012-03-10 00:22:19 +00002122 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002123 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2124 return static_cast<CPPLanguageRuntime *> (runtime);
2125 return NULL;
2126}
2127
2128ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002129Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002130{
Jim Inghamab175242012-03-10 00:22:19 +00002131 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002132 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2133 return static_cast<ObjCLanguageRuntime *> (runtime);
2134 return NULL;
2135}
2136
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002137bool
2138Process::IsPossibleDynamicValue (ValueObject& in_value)
2139{
Greg Claytonc00ca312015-04-02 18:44:58 +00002140 if (m_finalizing)
2141 return false;
2142
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002143 if (in_value.IsDynamic())
2144 return false;
2145 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2146
2147 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2148 {
2149 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2150 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2151 }
2152
2153 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2154 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2155 return true;
2156
2157 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2158 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2159}
2160
Zachary Turner93749ab2015-03-03 21:51:25 +00002161void
2162Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2163{
2164 m_dynamic_checkers_ap.reset(dynamic_checkers);
2165}
2166
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167BreakpointSiteList &
2168Process::GetBreakpointSiteList()
2169{
2170 return m_breakpoint_site_list;
2171}
2172
2173const BreakpointSiteList &
2174Process::GetBreakpointSiteList() const
2175{
2176 return m_breakpoint_site_list;
2177}
2178
2179
2180void
2181Process::DisableAllBreakpointSites ()
2182{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002183 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2184// bp_site->SetEnabled(true);
2185 DisableBreakpointSite(bp_site);
2186 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002187}
2188
2189Error
2190Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2191{
2192 Error error (DisableBreakpointSiteByID (break_id));
2193
2194 if (error.Success())
2195 m_breakpoint_site_list.Remove(break_id);
2196
2197 return error;
2198}
2199
2200Error
2201Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2202{
2203 Error error;
2204 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2205 if (bp_site_sp)
2206 {
2207 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002208 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209 }
2210 else
2211 {
Daniel Malead01b2952012-11-29 21:49:15 +00002212 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002213 }
2214
2215 return error;
2216}
2217
2218Error
2219Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2220{
2221 Error error;
2222 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2223 if (bp_site_sp)
2224 {
2225 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002226 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002227 }
2228 else
2229 {
Daniel Malead01b2952012-11-29 21:49:15 +00002230 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 }
2232 return error;
2233}
2234
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002235lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002236Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002238 addr_t load_addr = LLDB_INVALID_ADDRESS;
2239
2240 bool show_error = true;
2241 switch (GetState())
2242 {
2243 case eStateInvalid:
2244 case eStateUnloaded:
2245 case eStateConnected:
2246 case eStateAttaching:
2247 case eStateLaunching:
2248 case eStateDetached:
2249 case eStateExited:
2250 show_error = false;
2251 break;
2252
2253 case eStateStopped:
2254 case eStateRunning:
2255 case eStateStepping:
2256 case eStateCrashed:
2257 case eStateSuspended:
2258 show_error = IsAlive();
2259 break;
2260 }
2261
2262 // Reset the IsIndirect flag here, in case the location changes from
2263 // pointing to a indirect symbol to a regular symbol.
2264 owner->SetIsIndirect (false);
2265
2266 if (owner->ShouldResolveIndirectFunctions())
2267 {
2268 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2269 if (symbol && symbol->IsIndirect())
2270 {
2271 Error error;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002272 Address symbol_address = symbol->GetAddress();
2273 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:59 +00002274 if (!error.Success() && show_error)
2275 {
Zachary Turner7529df92015-09-01 20:02:29 +00002276 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2277 symbol->GetLoadAddress(&GetTarget()),
2278 owner->GetBreakpoint().GetID(),
2279 owner->GetID(),
2280 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002281 return LLDB_INVALID_BREAK_ID;
2282 }
2283 Address resolved_address(load_addr);
Zachary Turner7529df92015-09-01 20:02:29 +00002284 load_addr = resolved_address.GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002285 owner->SetIsIndirect(true);
2286 }
2287 else
Zachary Turner7529df92015-09-01 20:02:29 +00002288 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002289 }
2290 else
Zachary Turner7529df92015-09-01 20:02:29 +00002291 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002292
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 if (load_addr != LLDB_INVALID_ADDRESS)
2294 {
2295 BreakpointSiteSP bp_site_sp;
2296
2297 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2298 // create a new breakpoint site and add it.
2299
2300 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2301
2302 if (bp_site_sp)
2303 {
2304 bp_site_sp->AddOwner (owner);
2305 owner->SetBreakpointSite (bp_site_sp);
2306 return bp_site_sp->GetID();
2307 }
2308 else
2309 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002310 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311 if (bp_site_sp)
2312 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002313 Error error = EnableBreakpointSite (bp_site_sp.get());
2314 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315 {
2316 owner->SetBreakpointSite (bp_site_sp);
2317 return m_breakpoint_site_list.Add (bp_site_sp);
2318 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002319 else
2320 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002321 if (show_error)
2322 {
2323 // Report error for setting breakpoint...
Zachary Turner7529df92015-09-01 20:02:29 +00002324 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2325 load_addr,
2326 owner->GetBreakpoint().GetID(),
2327 owner->GetID(),
2328 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002329 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002330 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 }
2332 }
2333 }
2334 // We failed to enable the breakpoint
2335 return LLDB_INVALID_BREAK_ID;
2336
2337}
2338
2339void
2340Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2341{
2342 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2343 if (num_owners == 0)
2344 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002345 // Don't try to disable the site if we don't have a live process anymore.
2346 if (IsAlive())
2347 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2349 }
2350}
2351
2352
2353size_t
2354Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2355{
2356 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002357 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002358
Jim Ingham20c77192011-06-29 19:42:28 +00002359 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002360 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002361 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2362 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002363 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002364 addr_t intersect_addr;
2365 size_t intersect_size;
2366 size_t opcode_offset;
2367 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002368 {
2369 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2370 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002371 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002372 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002373 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002374 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002376 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 }
2378 return bytes_removed;
2379}
2380
2381
Greg Claytonded470d2011-03-19 01:12:21 +00002382
2383size_t
2384Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2385{
Zachary Turner7529df92015-09-01 20:02:29 +00002386 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Claytonded470d2011-03-19 01:12:21 +00002387 if (platform_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00002388 return platform_sp->GetSoftwareBreakpointTrapOpcode (GetTarget(), bp_site);
Greg Claytonded470d2011-03-19 01:12:21 +00002389 return 0;
2390}
2391
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392Error
2393Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2394{
2395 Error error;
2396 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002397 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398 const addr_t bp_addr = bp_site->GetLoadAddress();
2399 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002400 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401 if (bp_site->IsEnabled())
2402 {
2403 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002404 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 +00002405 return error;
2406 }
2407
2408 if (bp_addr == LLDB_INVALID_ADDRESS)
2409 {
2410 error.SetErrorString("BreakpointSite contains an invalid load address.");
2411 return error;
2412 }
2413 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2414 // trap for the breakpoint site
2415 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2416
2417 if (bp_opcode_size == 0)
2418 {
Daniel Malead01b2952012-11-29 21:49:15 +00002419 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420 }
2421 else
2422 {
2423 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2424
2425 if (bp_opcode_bytes == NULL)
2426 {
2427 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2428 return error;
2429 }
2430
2431 // Save the original opcode by reading it
2432 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2433 {
2434 // Write a software breakpoint in place of the original opcode
2435 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2436 {
2437 uint8_t verify_bp_opcode_bytes[64];
2438 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2439 {
2440 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2441 {
2442 bp_site->SetEnabled(true);
2443 bp_site->SetType (BreakpointSite::eSoftware);
2444 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002445 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446 bp_site->GetID(),
2447 (uint64_t)bp_addr);
2448 }
2449 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002450 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 }
2452 else
2453 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2454 }
2455 else
2456 error.SetErrorString("Unable to write breakpoint trap to memory.");
2457 }
2458 else
2459 error.SetErrorString("Unable to read memory at breakpoint address.");
2460 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002461 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002462 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002463 bp_site->GetID(),
2464 (uint64_t)bp_addr,
2465 error.AsCString());
2466 return error;
2467}
2468
2469Error
2470Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2471{
2472 Error error;
2473 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002474 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475 addr_t bp_addr = bp_site->GetLoadAddress();
2476 lldb::user_id_t breakID = bp_site->GetID();
2477 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002478 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002479
2480 if (bp_site->IsHardware())
2481 {
2482 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2483 }
2484 else if (bp_site->IsEnabled())
2485 {
2486 const size_t break_op_size = bp_site->GetByteSize();
2487 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2488 if (break_op_size > 0)
2489 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002490 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002491 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002492 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493 bool break_op_found = false;
2494
2495 // Read the breakpoint opcode
2496 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2497 {
2498 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002499 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2501 {
2502 break_op_found = true;
2503 // We found a valid breakpoint opcode at this address, now restore
2504 // the saved opcode.
2505 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2506 {
2507 verify = true;
2508 }
2509 else
2510 error.SetErrorString("Memory write failed when restoring original opcode.");
2511 }
2512 else
2513 {
2514 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2515 // Set verify to true and so we can check if the original opcode has already been restored
2516 verify = true;
2517 }
2518
2519 if (verify)
2520 {
Greg Claytonc982c762010-07-09 20:39:50 +00002521 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002522 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002523 // Verify that our original opcode made it back to the inferior
2524 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2525 {
2526 // compare the memory we just read with the original opcode
2527 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2528 {
2529 // SUCCESS
2530 bp_site->SetEnabled(false);
2531 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002532 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 +00002533 return error;
2534 }
2535 else
2536 {
2537 if (break_op_found)
2538 error.SetErrorString("Failed to restore original opcode.");
2539 }
2540 }
2541 else
2542 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2543 }
2544 }
2545 else
2546 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2547 }
2548 }
2549 else
2550 {
2551 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002552 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 +00002553 return error;
2554 }
2555
2556 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002557 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558 bp_site->GetID(),
2559 (uint64_t)bp_addr,
2560 error.AsCString());
2561 return error;
2562
2563}
2564
Greg Clayton58be07b2011-01-07 06:08:19 +00002565// Uncomment to verify memory caching works after making changes to caching code
2566//#define VERIFY_MEMORY_READS
2567
Sean Callanan64c0cf22012-06-07 22:26:42 +00002568size_t
2569Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2570{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002571 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002572 if (!GetDisableMemoryCache())
2573 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002574#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002575 // Memory caching is enabled, with debug verification
2576
2577 if (buf && size)
2578 {
2579 // Uncomment the line below to make sure memory caching is working.
2580 // I ran this through the test suite and got no assertions, so I am
2581 // pretty confident this is working well. If any changes are made to
2582 // memory caching, uncomment the line below and test your changes!
2583
2584 // Verify all memory reads by using the cache first, then redundantly
2585 // reading the same memory from the inferior and comparing to make sure
2586 // everything is exactly the same.
2587 std::string verify_buf (size, '\0');
2588 assert (verify_buf.size() == size);
2589 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2590 Error verify_error;
2591 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2592 assert (cache_bytes_read == verify_bytes_read);
2593 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2594 assert (verify_error.Success() == error.Success());
2595 return cache_bytes_read;
2596 }
2597 return 0;
2598#else // !defined(VERIFY_MEMORY_READS)
2599 // Memory caching is enabled, without debug verification
2600
2601 return m_memory_cache.Read (addr, buf, size, error);
2602#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002603 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002604 else
2605 {
2606 // Memory caching is disabled
2607
2608 return ReadMemoryFromInferior (addr, buf, size, error);
2609 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002610}
Greg Clayton58be07b2011-01-07 06:08:19 +00002611
Greg Clayton4c82d422012-05-18 23:20:01 +00002612size_t
2613Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2614{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002615 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002616 out_str.clear();
2617 addr_t curr_addr = addr;
2618 while (1)
2619 {
2620 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2621 if (length == 0)
2622 break;
2623 out_str.append(buf, length);
2624 // If we got "length - 1" bytes, we didn't get the whole C string, we
2625 // need to read some more characters
2626 if (length == sizeof(buf) - 1)
2627 curr_addr += length;
2628 else
2629 break;
2630 }
2631 return out_str.size();
2632}
2633
Greg Clayton58be07b2011-01-07 06:08:19 +00002634
2635size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002636Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2637 size_t type_width)
2638{
2639 size_t total_bytes_read = 0;
2640 if (dst && max_bytes && type_width && max_bytes >= type_width)
2641 {
2642 // Ensure a null terminator independent of the number of bytes that is read.
2643 memset (dst, 0, max_bytes);
2644 size_t bytes_left = max_bytes - type_width;
2645
2646 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2647 assert(sizeof(terminator) >= type_width &&
2648 "Attempting to validate a string with more than 4 bytes per character!");
2649
2650 addr_t curr_addr = addr;
2651 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2652 char *curr_dst = dst;
2653
2654 error.Clear();
2655 while (bytes_left > 0 && error.Success())
2656 {
2657 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2658 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2659 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2660
2661 if (bytes_read == 0)
2662 break;
2663
2664 // Search for a null terminator of correct size and alignment in bytes_read
2665 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2666 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2667 if (::strncmp(&dst[i], terminator, type_width) == 0)
2668 {
2669 error.Clear();
2670 return i;
2671 }
2672
2673 total_bytes_read += bytes_read;
2674 curr_dst += bytes_read;
2675 curr_addr += bytes_read;
2676 bytes_left -= bytes_read;
2677 }
2678 }
2679 else
2680 {
2681 if (max_bytes)
2682 error.SetErrorString("invalid arguments");
2683 }
2684 return total_bytes_read;
2685}
2686
2687// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2688// null terminators.
2689size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002690Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002691{
2692 size_t total_cstr_len = 0;
2693 if (dst && dst_max_len)
2694 {
Greg Claytone91b7952011-12-15 03:14:23 +00002695 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002696 // NULL out everything just to be safe
2697 memset (dst, 0, dst_max_len);
2698 Error error;
2699 addr_t curr_addr = addr;
2700 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2701 size_t bytes_left = dst_max_len - 1;
2702 char *curr_dst = dst;
2703
2704 while (bytes_left > 0)
2705 {
2706 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2707 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2708 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2709
2710 if (bytes_read == 0)
2711 {
Greg Claytone91b7952011-12-15 03:14:23 +00002712 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002713 dst[total_cstr_len] = '\0';
2714 break;
2715 }
2716 const size_t len = strlen(curr_dst);
2717
2718 total_cstr_len += len;
2719
2720 if (len < bytes_to_read)
2721 break;
2722
2723 curr_dst += bytes_read;
2724 curr_addr += bytes_read;
2725 bytes_left -= bytes_read;
2726 }
2727 }
Greg Claytone91b7952011-12-15 03:14:23 +00002728 else
2729 {
2730 if (dst == NULL)
2731 result_error.SetErrorString("invalid arguments");
2732 else
2733 result_error.Clear();
2734 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002735 return total_cstr_len;
2736}
2737
2738size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002739Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2740{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741 if (buf == NULL || size == 0)
2742 return 0;
2743
2744 size_t bytes_read = 0;
2745 uint8_t *bytes = (uint8_t *)buf;
2746
2747 while (bytes_read < size)
2748 {
2749 const size_t curr_size = size - bytes_read;
2750 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2751 bytes + bytes_read,
2752 curr_size,
2753 error);
2754 bytes_read += curr_bytes_read;
2755 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2756 break;
2757 }
2758
2759 // Replace any software breakpoint opcodes that fall into this range back
2760 // into "buf" before we return
2761 if (bytes_read > 0)
2762 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2763 return bytes_read;
2764}
2765
Greg Clayton58a4c462010-12-16 20:01:20 +00002766uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002767Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002768{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002769 Scalar scalar;
2770 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2771 return scalar.ULongLong(fail_value);
2772 return fail_value;
2773}
2774
2775addr_t
2776Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2777{
2778 Scalar scalar;
2779 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2780 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2781 return LLDB_INVALID_ADDRESS;
2782}
2783
2784
2785bool
2786Process::WritePointerToMemory (lldb::addr_t vm_addr,
2787 lldb::addr_t ptr_value,
2788 Error &error)
2789{
2790 Scalar scalar;
2791 const uint32_t addr_byte_size = GetAddressByteSize();
2792 if (addr_byte_size <= 4)
2793 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002794 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002795 scalar = ptr_value;
2796 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002797}
2798
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002799size_t
2800Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2801{
2802 size_t bytes_written = 0;
2803 const uint8_t *bytes = (const uint8_t *)buf;
2804
2805 while (bytes_written < size)
2806 {
2807 const size_t curr_size = size - bytes_written;
2808 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2809 bytes + bytes_written,
2810 curr_size,
2811 error);
2812 bytes_written += curr_bytes_written;
2813 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2814 break;
2815 }
2816 return bytes_written;
2817}
2818
2819size_t
2820Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2821{
Greg Clayton58be07b2011-01-07 06:08:19 +00002822#if defined (ENABLE_MEMORY_CACHING)
2823 m_memory_cache.Flush (addr, size);
2824#endif
2825
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 if (buf == NULL || size == 0)
2827 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002828
Jim Ingham4b536182011-08-09 02:12:22 +00002829 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002830
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002831 // We need to write any data that would go where any current software traps
2832 // (enabled software breakpoints) any software traps (breakpoints) that we
2833 // may have placed in our tasks memory.
2834
Greg Claytond8cf1a12013-06-12 00:46:38 +00002835 BreakpointSiteList bp_sites_in_range;
2836
2837 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002838 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002839 // No breakpoint sites overlap
2840 if (bp_sites_in_range.IsEmpty())
2841 return WriteMemoryPrivate (addr, buf, size, error);
2842 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002843 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002844 const uint8_t *ubuf = (const uint8_t *)buf;
2845 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002846
Greg Claytond8cf1a12013-06-12 00:46:38 +00002847 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2848
2849 if (error.Success())
2850 {
2851 addr_t intersect_addr;
2852 size_t intersect_size;
2853 size_t opcode_offset;
2854 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
Bruce Mitchener8a67bf72015-07-24 00:23:29 +00002855 UNUSED_IF_ASSERT_DISABLED(intersects);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002856 assert(intersects);
2857 assert(addr <= intersect_addr && intersect_addr < addr + size);
2858 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2859 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2860
2861 // Check for bytes before this breakpoint
2862 const addr_t curr_addr = addr + bytes_written;
2863 if (intersect_addr > curr_addr)
2864 {
2865 // There are some bytes before this breakpoint that we need to
2866 // just write to memory
2867 size_t curr_size = intersect_addr - curr_addr;
2868 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2869 ubuf + bytes_written,
2870 curr_size,
2871 error);
2872 bytes_written += curr_bytes_written;
2873 if (curr_bytes_written != curr_size)
2874 {
2875 // We weren't able to write all of the requested bytes, we
2876 // are done looping and will return the number of bytes that
2877 // we have written so far.
2878 if (error.Success())
2879 error.SetErrorToGenericError();
2880 }
2881 }
2882 // Now write any bytes that would cover up any software breakpoints
2883 // directly into the breakpoint opcode buffer
2884 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2885 bytes_written += intersect_size;
2886 }
2887 });
2888
2889 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002890 WriteMemoryPrivate (addr + bytes_written,
2891 ubuf + bytes_written,
2892 size - bytes_written,
2893 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002894 }
2895 }
2896 else
2897 {
2898 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002899 }
2900
2901 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002902 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002904
2905size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002906Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002907{
2908 if (byte_size == UINT32_MAX)
2909 byte_size = scalar.GetByteSize();
2910 if (byte_size > 0)
2911 {
2912 uint8_t buf[32];
2913 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2914 if (mem_size > 0)
2915 return WriteMemory(addr, buf, mem_size, error);
2916 else
2917 error.SetErrorString ("failed to get scalar as memory data");
2918 }
2919 else
2920 {
2921 error.SetErrorString ("invalid scalar value");
2922 }
2923 return 0;
2924}
2925
2926size_t
2927Process::ReadScalarIntegerFromMemory (addr_t addr,
2928 uint32_t byte_size,
2929 bool is_signed,
2930 Scalar &scalar,
2931 Error &error)
2932{
Greg Clayton7060f892013-05-01 23:41:30 +00002933 uint64_t uval = 0;
2934 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002935 {
Greg Clayton7060f892013-05-01 23:41:30 +00002936 error.SetErrorString ("byte size is zero");
2937 }
2938 else if (byte_size & (byte_size - 1))
2939 {
2940 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2941 }
2942 else if (byte_size <= sizeof(uval))
2943 {
2944 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002945 if (bytes_read == byte_size)
2946 {
2947 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002948 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002949 if (byte_size <= 4)
2950 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002951 else
Greg Clayton7060f892013-05-01 23:41:30 +00002952 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002953 if (is_signed)
2954 scalar.SignExtend(byte_size * 8);
2955 return bytes_read;
2956 }
2957 }
2958 else
2959 {
2960 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2961 }
2962 return 0;
2963}
2964
Greg Claytond495c532011-05-17 03:37:42 +00002965#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966addr_t
2967Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2968{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002969 if (GetPrivateState() != eStateStopped)
2970 return LLDB_INVALID_ADDRESS;
2971
Greg Claytond495c532011-05-17 03:37:42 +00002972#if defined (USE_ALLOCATE_MEMORY_CACHE)
2973 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2974#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002975 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002976 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002977 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002978 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 +00002979 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002980 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002981 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002982 m_mod_id.GetStopID(),
2983 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002984 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002985#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002986}
2987
Sean Callanan90539452011-09-20 23:01:51 +00002988bool
2989Process::CanJIT ()
2990{
Sean Callanana7b443a2012-02-14 22:50:38 +00002991 if (m_can_jit == eCanJITDontKnow)
2992 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002993 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002994 Error err;
2995
2996 uint64_t allocated_memory = AllocateMemory(8,
2997 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2998 err);
2999
3000 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00003001 {
Sean Callanana7b443a2012-02-14 22:50:38 +00003002 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00003003 if (log)
3004 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
3005 }
Sean Callanana7b443a2012-02-14 22:50:38 +00003006 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003007 {
Sean Callanana7b443a2012-02-14 22:50:38 +00003008 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00003009 if (log)
3010 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
3011 }
Sean Callanana7b443a2012-02-14 22:50:38 +00003012
3013 DeallocateMemory (allocated_memory);
3014 }
3015
Sean Callanan90539452011-09-20 23:01:51 +00003016 return m_can_jit == eCanJITYes;
3017}
3018
3019void
3020Process::SetCanJIT (bool can_jit)
3021{
3022 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
3023}
3024
Ewan Crawford90ff7912015-07-14 10:56:58 +00003025void
3026Process::SetCanRunCode (bool can_run_code)
3027{
3028 SetCanJIT(can_run_code);
3029 m_can_interpret_function_calls = can_run_code;
3030}
3031
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032Error
3033Process::DeallocateMemory (addr_t ptr)
3034{
Greg Claytond495c532011-05-17 03:37:42 +00003035 Error error;
3036#if defined (USE_ALLOCATE_MEMORY_CACHE)
3037 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
3038 {
Daniel Malead01b2952012-11-29 21:49:15 +00003039 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00003040 }
3041#else
3042 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00003043
Greg Clayton5160ce52013-03-27 23:08:40 +00003044 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00003045 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003046 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 +00003047 ptr,
3048 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00003049 m_mod_id.GetStopID(),
3050 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00003051#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00003052 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003053}
3054
Han Ming Ongc811d382012-11-17 00:33:14 +00003055
Greg Claytonc9660542012-02-05 02:38:54 +00003056ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00003057Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00003058 lldb::addr_t header_addr,
3059 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00003060{
Jason Molenda08a32582015-07-25 02:39:42 +00003061 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
3062 if (log)
3063 {
3064 log->Printf ("Process::ReadModuleFromMemory reading %s binary from memory", file_spec.GetPath().c_str());
3065 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003066 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00003067 if (module_sp)
3068 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003069 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00003070 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003071 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003072 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00003073 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003074 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00003075}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003076
Zachary Turner93749ab2015-03-03 21:51:25 +00003077bool
3078Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3079{
3080 MemoryRegionInfo range_info;
3081 permissions = 0;
3082 Error error (GetMemoryRegionInfo (load_addr, range_info));
3083 if (!error.Success())
3084 return false;
3085 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3086 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3087 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3088 {
3089 return false;
3090 }
3091
3092 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3093 permissions |= lldb::ePermissionsReadable;
3094
3095 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3096 permissions |= lldb::ePermissionsWritable;
3097
3098 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3099 permissions |= lldb::ePermissionsExecutable;
3100
3101 return true;
3102}
3103
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003104Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003105Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003106{
3107 Error error;
3108 error.SetErrorString("watchpoints are not supported");
3109 return error;
3110}
3111
3112Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003113Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003114{
3115 Error error;
3116 error.SetErrorString("watchpoints are not supported");
3117 return error;
3118}
3119
3120StateType
3121Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3122{
3123 StateType state;
3124 // Now wait for the process to launch and return control to us, and then
3125 // call DidLaunch:
3126 while (1)
3127 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003128 event_sp.reset();
3129 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3130
Greg Clayton2637f822011-11-17 01:23:07 +00003131 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003133
3134 // If state is invalid, then we timed out
3135 if (state == eStateInvalid)
3136 break;
3137
3138 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139 HandlePrivateEvent (event_sp);
3140 }
3141 return state;
3142}
3143
Greg Clayton332e8b12015-01-13 21:13:08 +00003144void
3145Process::LoadOperatingSystemPlugin(bool flush)
3146{
3147 if (flush)
3148 m_thread_list.Clear();
3149 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3150 if (flush)
3151 Flush();
3152}
3153
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003155Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156{
3157 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003159 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003160 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003161 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003162 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003163 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003164 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165
Zachary Turner7529df92015-09-01 20:02:29 +00003166 Module *exe_module = GetTarget().GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003167 if (exe_module)
3168 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003169 char local_exec_file_path[PATH_MAX];
3170 char platform_exec_file_path[PATH_MAX];
3171 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3172 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003173 if (exe_module->GetFileSpec().Exists())
3174 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003175 // Install anything that might need to be installed prior to launching.
3176 // For host systems, this will do nothing, but if we are connected to a
3177 // remote platform it will install any needed binaries
3178 error = GetTarget().Install(&launch_info);
3179 if (error.Fail())
3180 return error;
3181
Greg Clayton71337622011-02-24 22:24:29 +00003182 if (PrivateStateThreadIsValid ())
3183 PausePrivateStateThread ();
3184
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003185 error = WillLaunch (exe_module);
3186 if (error.Success())
3187 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003188 const bool restarted = false;
3189 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003190 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003191
Ed Maste64fad602013-07-29 20:58:06 +00003192 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003193 {
3194 // Now launch using these arguments.
3195 error = DoLaunch (exe_module, launch_info);
3196 }
3197 else
3198 {
3199 // This shouldn't happen
3200 error.SetErrorString("failed to acquire process run lock");
3201 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202
3203 if (error.Fail())
3204 {
3205 if (GetID() != LLDB_INVALID_PROCESS_ID)
3206 {
3207 SetID (LLDB_INVALID_PROCESS_ID);
3208 const char *error_string = error.AsCString();
3209 if (error_string == NULL)
3210 error_string = "launch failed";
3211 SetExitStatus (-1, error_string);
3212 }
3213 }
3214 else
3215 {
3216 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003217 TimeValue timeout_time;
3218 timeout_time = TimeValue::Now();
3219 timeout_time.OffsetWithSeconds(10);
3220 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003221
Greg Clayton1a38ea72011-06-22 01:42:17 +00003222 if (state == eStateInvalid || event_sp.get() == NULL)
3223 {
3224 // We were able to launch the process, but we failed to
3225 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003226 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003227 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003228 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003229 }
3230 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003232
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 DidLaunch ();
3234
Greg Claytonc859e2d2012-02-13 23:10:39 +00003235 DynamicLoader *dyld = GetDynamicLoader ();
3236 if (dyld)
3237 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003238
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003239 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003240
Jason Molendaeef51062013-11-05 03:57:19 +00003241 SystemRuntime *system_runtime = GetSystemRuntime ();
3242 if (system_runtime)
3243 system_runtime->DidLaunch();
3244
Greg Clayton332e8b12015-01-13 21:13:08 +00003245 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003246
3247 // Note, the stop event was consumed above, but not handled. This was done
3248 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3249 // Directly set the state. This is done to prevent a stop message with a bunch
3250 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3251 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003252
3253 if (PrivateStateThreadIsValid ())
3254 ResumePrivateStateThread ();
3255 else
3256 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003257
3258 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003259
3260 // Target was stopped at entry as was intended. Need to notify the listeners
3261 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003262 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003263 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264 }
3265 else if (state == eStateExited)
3266 {
3267 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3268 // not likely to work, and return an invalid pid.
3269 HandlePrivateEvent (event_sp);
3270 }
3271 }
3272 }
3273 }
3274 else
3275 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003276 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003277 }
3278 }
3279 return error;
3280}
3281
Greg Claytonc3776bf2012-02-09 06:16:32 +00003282
3283Error
3284Process::LoadCore ()
3285{
3286 Error error = DoLoadCore();
3287 if (error.Success())
3288 {
Greg Clayton35824e32015-02-20 20:59:47 +00003289 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003290 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003291
Greg Claytonc3776bf2012-02-09 06:16:32 +00003292 if (PrivateStateThreadIsValid ())
3293 ResumePrivateStateThread ();
3294 else
3295 StartPrivateStateThread ();
3296
Greg Claytonc859e2d2012-02-13 23:10:39 +00003297 DynamicLoader *dyld = GetDynamicLoader ();
3298 if (dyld)
3299 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003300
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003301 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003302
Jason Molendaeef51062013-11-05 03:57:19 +00003303 SystemRuntime *system_runtime = GetSystemRuntime ();
3304 if (system_runtime)
3305 system_runtime->DidAttach();
3306
Greg Claytonc859e2d2012-02-13 23:10:39 +00003307 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003308 // We successfully loaded a core file, now pretend we stopped so we can
3309 // show all of the threads in the core file and explore the crashed
3310 // state.
3311 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003312
3313 // Wait indefinitely for a stopped event since we just posted one above...
3314 lldb::EventSP event_sp;
3315 listener.WaitForEvent (NULL, event_sp);
3316 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3317
3318 if (!StateIsStoppedState (state, false))
3319 {
3320 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3321 if (log)
3322 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3323 error.SetErrorString ("Did not get stopped event after loading the core file.");
3324 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003325 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003326 }
3327 return error;
3328}
3329
Greg Claytonc859e2d2012-02-13 23:10:39 +00003330DynamicLoader *
3331Process::GetDynamicLoader ()
3332{
3333 if (m_dyld_ap.get() == NULL)
3334 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3335 return m_dyld_ap.get();
3336}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003337
Todd Fialaaf245d12014-06-30 21:05:18 +00003338const lldb::DataBufferSP
3339Process::GetAuxvData()
3340{
3341 return DataBufferSP ();
3342}
3343
Andrew MacPherson17220c12014-03-05 10:12:43 +00003344JITLoaderList &
3345Process::GetJITLoaders ()
3346{
3347 if (!m_jit_loaders_ap)
3348 {
3349 m_jit_loaders_ap.reset(new JITLoaderList());
3350 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3351 }
3352 return *m_jit_loaders_ap;
3353}
3354
Jason Molendaeef51062013-11-05 03:57:19 +00003355SystemRuntime *
3356Process::GetSystemRuntime ()
3357{
3358 if (m_system_runtime_ap.get() == NULL)
3359 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3360 return m_system_runtime_ap.get();
3361}
3362
Todd Fiala76e0fc92014-08-27 22:58:26 +00003363Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3364 NextEventAction (process),
3365 m_exec_count (exec_count)
3366{
3367 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3368 if (log)
3369 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3370}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003371
Jim Inghambb3a2832011-01-29 01:49:25 +00003372Process::NextEventAction::EventActionResult
3373Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003374{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003375 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3376
Jim Inghambb3a2832011-01-29 01:49:25 +00003377 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003378 if (log)
3379 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3380
3381 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003382 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003383 case eStateAttaching:
3384 return eEventActionSuccess;
3385
Greg Clayton513c26c2011-01-29 07:10:55 +00003386 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003387 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003388 return eEventActionRetry;
3389
3390 case eStateStopped:
3391 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003392 {
3393 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003394 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003395 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003396 // We don't want these events to be reported, so go set the ShouldReportStop here:
3397 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3398
Greg Claytonc9ed4782011-11-12 02:10:56 +00003399 if (m_exec_count > 0)
3400 {
3401 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003402
3403 if (log)
3404 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3405
Jim Ingham221d51c2013-05-08 00:35:16 +00003406 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003407 return eEventActionRetry;
3408 }
3409 else
3410 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003411 if (log)
3412 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3413
Greg Claytonc9ed4782011-11-12 02:10:56 +00003414 m_process->CompleteAttach ();
3415 return eEventActionSuccess;
3416 }
3417 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003418 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003419
Greg Clayton513c26c2011-01-29 07:10:55 +00003420 default:
3421 case eStateExited:
3422 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003423 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003424 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003425
3426 m_exit_string.assign ("No valid Process");
3427 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003428}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003429
Jim Inghambb3a2832011-01-29 01:49:25 +00003430Process::NextEventAction::EventActionResult
3431Process::AttachCompletionHandler::HandleBeingInterrupted()
3432{
3433 return eEventActionSuccess;
3434}
3435
3436const char *
3437Process::AttachCompletionHandler::GetExitString ()
3438{
3439 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003440}
3441
Greg Clayton8012cad2014-11-17 19:39:20 +00003442Listener &
3443ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3444{
3445 if (m_listener_sp)
3446 return *m_listener_sp;
3447 else
3448 return debugger.GetListener();
3449}
3450
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003451Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003452Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003453{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003455 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003456 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003457 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003458 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003459 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003460 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003461
Greg Clayton144f3a92011-11-15 03:53:30 +00003462 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003463 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003464 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003465 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003466 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003467
Greg Clayton144f3a92011-11-15 03:53:30 +00003468 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003469 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003470 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3471
3472 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003473 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003474 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3475 if (error.Success())
3476 {
Ed Maste64fad602013-07-29 20:58:06 +00003477 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003478 {
3479 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003480 const bool restarted = false;
3481 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003482 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003483 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003484 }
3485 else
3486 {
3487 // This shouldn't happen
3488 error.SetErrorString("failed to acquire process run lock");
3489 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003490
Greg Clayton144f3a92011-11-15 03:53:30 +00003491 if (error.Fail())
3492 {
3493 if (GetID() != LLDB_INVALID_PROCESS_ID)
3494 {
3495 SetID (LLDB_INVALID_PROCESS_ID);
3496 if (error.AsCString() == NULL)
3497 error.SetErrorString("attach failed");
3498
3499 SetExitStatus(-1, error.AsCString());
3500 }
3501 }
3502 else
3503 {
3504 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3505 StartPrivateStateThread();
3506 }
3507 return error;
3508 }
Greg Claytone996fd32011-03-08 22:40:15 +00003509 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003510 else
Greg Claytone996fd32011-03-08 22:40:15 +00003511 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003512 ProcessInstanceInfoList process_infos;
Zachary Turner7529df92015-09-01 20:02:29 +00003513 PlatformSP platform_sp (GetTarget().GetPlatform ());
Greg Clayton144f3a92011-11-15 03:53:30 +00003514
3515 if (platform_sp)
3516 {
3517 ProcessInstanceInfoMatch match_info;
3518 match_info.GetProcessInfo() = attach_info;
3519 match_info.SetNameMatchType (eNameMatchEquals);
3520 platform_sp->FindProcesses (match_info, process_infos);
3521 const uint32_t num_matches = process_infos.GetSize();
3522 if (num_matches == 1)
3523 {
3524 attach_pid = process_infos.GetProcessIDAtIndex(0);
3525 // Fall through and attach using the above process ID
3526 }
3527 else
3528 {
3529 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3530 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003531 {
3532 StreamString s;
3533 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3534 for (size_t i = 0; i < num_matches; i++)
3535 {
3536 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3537 }
3538 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3539 process_name,
3540 s.GetData());
3541 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003542 else
3543 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3544 }
3545 }
3546 else
3547 {
3548 error.SetErrorString ("invalid platform, can't find processes by name");
3549 return error;
3550 }
Greg Claytone996fd32011-03-08 22:40:15 +00003551 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003552 }
3553 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003554 {
3555 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003556 }
3557 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003558
3559 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003560 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003561 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003562 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003563 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003564
Ed Maste64fad602013-07-29 20:58:06 +00003565 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003566 {
3567 // Now attach using these arguments.
3568 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003569 const bool restarted = false;
3570 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003571 error = DoAttachToProcessWithID (attach_pid, attach_info);
3572 }
3573 else
3574 {
3575 // This shouldn't happen
3576 error.SetErrorString("failed to acquire process run lock");
3577 }
3578
Greg Clayton144f3a92011-11-15 03:53:30 +00003579 if (error.Success())
3580 {
3581
3582 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3583 StartPrivateStateThread();
3584 }
3585 else
Greg Claytone996fd32011-03-08 22:40:15 +00003586 {
3587 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003588 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003589
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003590 const char *error_string = error.AsCString();
3591 if (error_string == NULL)
3592 error_string = "attach failed";
3593
3594 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003595 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003596 }
3597 }
3598 return error;
3599}
3600
Greg Clayton93d3c8332011-02-16 04:46:07 +00003601void
3602Process::CompleteAttach ()
3603{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003604 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3605 if (log)
3606 log->Printf ("Process::%s()", __FUNCTION__);
3607
Greg Clayton93d3c8332011-02-16 04:46:07 +00003608 // Let the process subclass figure out at much as it can about the process
3609 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003610 ArchSpec process_arch;
3611 DidAttach(process_arch);
3612
3613 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003614 {
Zachary Turner7529df92015-09-01 20:02:29 +00003615 GetTarget().SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003616 if (log)
3617 {
3618 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3619 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3620 __FUNCTION__,
3621 triple_str ? triple_str : "<null>");
3622 }
3623 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003624
Jim Ingham4299fdb2011-09-15 01:10:17 +00003625 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3626 // the same as the one we've already set, switch architectures.
Zachary Turner7529df92015-09-01 20:02:29 +00003627 PlatformSP platform_sp (GetTarget().GetPlatform ());
Jim Ingham4299fdb2011-09-15 01:10:17 +00003628 assert (platform_sp.get());
3629 if (platform_sp)
3630 {
Zachary Turner7529df92015-09-01 20:02:29 +00003631 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003632 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003633 {
3634 ArchSpec platform_arch;
3635 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3636 if (platform_sp)
3637 {
Zachary Turner7529df92015-09-01 20:02:29 +00003638 GetTarget().SetPlatform (platform_sp);
3639 GetTarget().SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003640 if (log)
3641 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 +00003642 }
3643 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003644 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003645 {
3646 ProcessInstanceInfo process_info;
3647 platform_sp->GetProcessInfo (GetID(), process_info);
3648 const ArchSpec &process_arch = process_info.GetArchitecture();
Zachary Turner7529df92015-09-01 20:02:29 +00003649 if (process_arch.IsValid() && !GetTarget().GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003650 {
Zachary Turner7529df92015-09-01 20:02:29 +00003651 GetTarget().SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003652 if (log)
3653 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 ());
3654 }
Greg Clayton70512312012-05-08 01:45:38 +00003655 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003656 }
3657
3658 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003659 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003660 DynamicLoader *dyld = GetDynamicLoader ();
3661 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003662 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003663 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003664 if (log)
3665 {
Zachary Turner7529df92015-09-01 20:02:29 +00003666 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003667 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3668 __FUNCTION__,
3669 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3670 dyld->GetPluginName().AsCString ("<unnamed>"));
3671 }
3672 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003673
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003674 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003675
Jason Molendaeef51062013-11-05 03:57:19 +00003676 SystemRuntime *system_runtime = GetSystemRuntime ();
3677 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003678 {
Jason Molendaeef51062013-11-05 03:57:19 +00003679 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003680 if (log)
3681 {
Zachary Turner7529df92015-09-01 20:02:29 +00003682 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003683 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3684 __FUNCTION__,
3685 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3686 system_runtime->GetPluginName().AsCString("<unnamed>"));
3687 }
3688 }
Jason Molendaeef51062013-11-05 03:57:19 +00003689
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003690 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003691 // Figure out which one is the executable, and set that in our target:
Zachary Turner7529df92015-09-01 20:02:29 +00003692 const ModuleList &target_modules = GetTarget().GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003693 Mutex::Locker modules_locker(target_modules.GetMutex());
3694 size_t num_modules = target_modules.GetSize();
3695 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003696
Andy Gibbsa297a972013-06-19 19:04:53 +00003697 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003698 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003699 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003700 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003701 {
Zachary Turner7529df92015-09-01 20:02:29 +00003702 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003703 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003704 break;
3705 }
3706 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003707 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003708 {
Zachary Turner7529df92015-09-01 20:02:29 +00003709 GetTarget().SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003710 if (log)
3711 {
Zachary Turner7529df92015-09-01 20:02:29 +00003712 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003713 log->Printf ("Process::%s after looping through modules, target executable is %s",
3714 __FUNCTION__,
3715 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3716 }
3717 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003718
3719 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003720}
3721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003723Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003724{
Greg Claytonb766a732011-02-04 01:58:07 +00003725 m_abi_sp.reset();
3726 m_process_input_reader.reset();
3727
3728 // Find the process and its architecture. Make sure it matches the architecture
3729 // of the current Target, and if not adjust it.
3730
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003731 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003732 if (error.Success())
3733 {
Greg Clayton71337622011-02-24 22:24:29 +00003734 if (GetID() != LLDB_INVALID_PROCESS_ID)
3735 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003736 EventSP event_sp;
3737 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3738
3739 if (state == eStateStopped || state == eStateCrashed)
3740 {
3741 // If we attached and actually have a process on the other end, then
3742 // this ended up being the equivalent of an attach.
3743 CompleteAttach ();
3744
3745 // This delays passing the stopped event to listeners till
3746 // CompleteAttach gets a chance to complete...
3747 HandlePrivateEvent (event_sp);
3748
3749 }
Greg Clayton71337622011-02-24 22:24:29 +00003750 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003751
3752 if (PrivateStateThreadIsValid ())
3753 ResumePrivateStateThread ();
3754 else
3755 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003756 }
3757 return error;
3758}
3759
3760
3761Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003762Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003763{
Greg Clayton5160ce52013-03-27 23:08:40 +00003764 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003766 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003767 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003768 StateAsCString(m_public_state.GetValue()),
3769 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770
3771 Error error (WillResume());
3772 // Tell the process it is about to resume before the thread list
3773 if (error.Success())
3774 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003775 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003776 // can let all of our threads know that they are about to be
3777 // resumed. Threads will each be called with
3778 // Thread::WillResume(StateType) where StateType contains the state
3779 // that they are supposed to have when the process is resumed
3780 // (suspended/running/stepping). Threads should also check
3781 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003782 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003783 if (m_thread_list.WillResume())
3784 {
Jim Ingham372787f2012-04-07 00:00:41 +00003785 // Last thing, do the PreResumeActions.
3786 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003787 {
Jim Ingham0161b492013-02-09 01:29:05 +00003788 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003789 }
3790 else
3791 {
3792 m_mod_id.BumpResumeID();
3793 error = DoResume();
3794 if (error.Success())
3795 {
3796 DidResume();
3797 m_thread_list.DidResume();
3798 if (log)
3799 log->Printf ("Process thinks the process has resumed.");
3800 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003801 }
3802 }
3803 else
3804 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003805 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3806 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003807 // and let the world handle them.
3808 if (log)
3809 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3810
3811 SetPrivateState(eStateRunning);
3812 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003813 }
3814 }
Jim Ingham444586b2011-01-24 06:34:17 +00003815 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003816 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817 return error;
3818}
3819
3820Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003821Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003822{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003823 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3824 // in case it was already set and some thread plan logic calls halt on its
3825 // own.
3826 m_clear_thread_plans_on_stop |= clear_thread_plans;
3827
Jim Inghamaacc3182012-06-06 00:29:30 +00003828 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3829 // we could just straightaway get another event. It just narrows the window...
3830 m_currently_handling_event.WaitForValueEqualTo(false);
3831
3832
Jim Inghambb3a2832011-01-29 01:49:25 +00003833 // Pause our private state thread so we can ensure no one else eats
3834 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003835 Listener halt_listener ("lldb.process.halt_listener");
3836 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003837
Jim Inghambb3a2832011-01-29 01:49:25 +00003838 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003839 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003840
Greg Clayton06357c92014-07-30 17:38:47 +00003841 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003842 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003843 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003844
Greg Clayton513c26c2011-01-29 07:10:55 +00003845 bool caused_stop = false;
3846
3847 // Ask the process subclass to actually halt our process
3848 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003849 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003850 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003851 if (m_public_state.GetValue() == eStateAttaching)
3852 {
Greg Clayton06357c92014-07-30 17:38:47 +00003853 // Don't hijack and eat the eStateExited as the code that was doing
3854 // the attach will be waiting for this event...
3855 RestorePrivateProcessEvents();
3856 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003857 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:58 +00003858 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:55 +00003859 }
3860 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003861 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003862 // If "caused_stop" is true, then DoHalt stopped the process. If
3863 // "caused_stop" is false, the process was already stopped.
3864 // If the DoHalt caused the process to stop, then we want to catch
3865 // this event and set the interrupted bool to true before we pass
3866 // this along so clients know that the process was interrupted by
3867 // a halt command.
3868 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003869 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003870 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003871 TimeValue timeout_time;
3872 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003873 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003874 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3875 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003876
Jim Ingham0f16e732011-02-08 05:20:59 +00003877 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003878 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003879 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003880 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003881 }
3882 else
3883 {
Greg Clayton2637f822011-11-17 01:23:07 +00003884 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003885 {
3886 // We caused the process to interrupt itself, so mark this
3887 // as such in the stop event so clients can tell an interrupted
3888 // process from a natural stop
3889 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3890 }
3891 else
3892 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003893 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003894 if (log)
3895 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3896 error.SetErrorString ("Did not get stopped event after halt.");
3897 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003898 }
3899 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003900 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003901 }
3902 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003903 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003904 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003905 if (!restored_process_events)
3906 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003907
3908 // Post any event we might have consumed. If all goes well, we will have
3909 // stopped the process, intercepted the event and set the interrupted
3910 // bool in the event. Post it to the private event queue and that will end up
3911 // correctly setting the state.
3912 if (event_sp)
3913 m_private_state_broadcaster.BroadcastEvent(event_sp);
3914
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003915 return error;
3916}
3917
3918Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003919Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3920{
3921 Error error;
3922 if (m_public_state.GetValue() == eStateRunning)
3923 {
3924 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3925 if (log)
Pavel Labathea3fb8e2015-09-03 15:44:14 +00003926 log->Printf("Process::%s() About to halt.", __FUNCTION__);
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003927 error = Halt();
3928 if (error.Success())
3929 {
3930 // Consume the halt event.
3931 TimeValue timeout (TimeValue::Now());
3932 timeout.OffsetWithSeconds(1);
3933 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3934
3935 // If the process exited while we were waiting for it to stop, put the exited event into
3936 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3937 // they don't have a process anymore...
3938
3939 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3940 {
3941 if (log)
3942 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3943 return error;
3944 }
3945 else
3946 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3947
3948 if (state != eStateStopped)
3949 {
3950 if (log)
3951 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3952 // If we really couldn't stop the process then we should just error out here, but if the
3953 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3954 StateType private_state = m_private_state.GetValue();
3955 if (private_state != eStateStopped)
3956 {
3957 return error;
3958 }
3959 }
3960 }
3961 else
3962 {
3963 if (log)
3964 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3965 }
3966 }
3967 return error;
3968}
3969
3970Error
Jim Inghamacff8952013-05-02 00:27:30 +00003971Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003972{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003973 EventSP exit_event_sp;
3974 Error error;
3975 m_destroy_in_process = true;
3976
3977 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978
3979 if (error.Success())
3980 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003981 if (DetachRequiresHalt())
3982 {
3983 error = HaltForDestroyOrDetach (exit_event_sp);
3984 if (!error.Success())
3985 {
3986 m_destroy_in_process = false;
3987 return error;
3988 }
3989 else if (exit_event_sp)
3990 {
3991 // We shouldn't need to do anything else here. There's no process left to detach from...
3992 StopPrivateStateThread();
3993 m_destroy_in_process = false;
3994 return error;
3995 }
3996 }
3997
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003998 m_thread_list.DiscardThreadPlans();
3999 DisableAllBreakpointSites();
4000
Jim Inghamacff8952013-05-02 00:27:30 +00004001 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004002 if (error.Success())
4003 {
4004 DidDetach();
4005 StopPrivateStateThread();
4006 }
Jim Inghamacff8952013-05-02 00:27:30 +00004007 else
4008 {
4009 return error;
4010 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004012 m_destroy_in_process = false;
4013
4014 // If we exited when we were waiting for a process to stop, then
4015 // forward the event here so we don't lose the event
4016 if (exit_event_sp)
4017 {
4018 // Directly broadcast our exited event because we shut down our
4019 // private state thread above
4020 BroadcastEvent(exit_event_sp);
4021 }
4022
4023 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4024 // the last events through the event system, in which case we might strand the write lock. Unlock
4025 // it here so when we do to tear down the process we don't get an error destroying the lock.
4026
Ed Maste64fad602013-07-29 20:58:06 +00004027 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004028 return error;
4029}
4030
4031Error
Jason Molendaede31932015-04-17 05:01:58 +00004032Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004033{
Jim Ingham09437922013-03-01 20:04:25 +00004034
4035 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
4036 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
4037 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00004038
4039 if (force_kill)
4040 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00004041
Ilia Kfcc89a02015-03-26 07:08:47 +00004042 if (GetShouldDetach())
4043 {
4044 // FIXME: This will have to be a process setting:
4045 bool keep_stopped = false;
4046 Detach(keep_stopped);
4047 }
4048
Jim Ingham09437922013-03-01 20:04:25 +00004049 m_destroy_in_process = true;
4050
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051 Error error (WillDestroy());
4052 if (error.Success())
4053 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00004054 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004055 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00004056 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004057 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00004058 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004059
Jim Inghamaacc3182012-06-06 00:29:30 +00004060 if (m_public_state.GetValue() != eStateRunning)
4061 {
4062 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4063 // kill it, we don't want it hitting a breakpoint...
4064 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4065 // we're not going to have much luck doing this now.
4066 m_thread_list.DiscardThreadPlans();
4067 DisableAllBreakpointSites();
4068 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004069
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004070 error = DoDestroy();
4071 if (error.Success())
4072 {
4073 DidDestroy();
4074 StopPrivateStateThread();
4075 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004076 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00004077 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:04 +00004078 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00004079
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004080 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00004081 {
4082 m_process_input_reader->SetIsDone(true);
4083 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004084 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00004085 }
4086
Greg Clayton85fb1b92012-09-11 02:33:37 +00004087 // If we exited when we were waiting for a process to stop, then
4088 // forward the event here so we don't lose the event
4089 if (exit_event_sp)
4090 {
4091 // Directly broadcast our exited event because we shut down our
4092 // private state thread above
4093 BroadcastEvent(exit_event_sp);
4094 }
4095
Jim Inghamb1e2e842012-04-12 18:49:31 +00004096 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4097 // the last events through the event system, in which case we might strand the write lock. Unlock
4098 // 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 +00004099 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100 }
Jim Ingham09437922013-03-01 20:04:25 +00004101
4102 m_destroy_in_process = false;
4103
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104 return error;
4105}
4106
4107Error
4108Process::Signal (int signal)
4109{
4110 Error error (WillSignal());
4111 if (error.Success())
4112 {
4113 error = DoSignal(signal);
4114 if (error.Success())
4115 DidSignal();
4116 }
4117 return error;
4118}
4119
Zachary Turner93749ab2015-03-03 21:51:25 +00004120void
Chaoren Linc963a222015-09-01 16:58:45 +00004121Process::SetUnixSignals(UnixSignalsSP &&signals_sp)
Zachary Turner93749ab2015-03-03 21:51:25 +00004122{
4123 assert (signals_sp && "null signals_sp");
4124 m_unix_signals_sp = signals_sp;
4125}
4126
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00004127const lldb::UnixSignalsSP &
Zachary Turner93749ab2015-03-03 21:51:25 +00004128Process::GetUnixSignals ()
4129{
4130 assert (m_unix_signals_sp && "null m_unix_signals_sp");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00004131 return m_unix_signals_sp;
Zachary Turner93749ab2015-03-03 21:51:25 +00004132}
4133
Greg Clayton514487e2011-02-15 21:59:32 +00004134lldb::ByteOrder
4135Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004136{
Zachary Turner7529df92015-09-01 20:02:29 +00004137 return GetTarget().GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004138}
4139
4140uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00004141Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004142{
Zachary Turner7529df92015-09-01 20:02:29 +00004143 return GetTarget().GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004144}
4145
Greg Clayton514487e2011-02-15 21:59:32 +00004146
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147bool
4148Process::ShouldBroadcastEvent (Event *event_ptr)
4149{
4150 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4151 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00004152 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00004153
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004154 switch (state)
4155 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156 case eStateDetached:
4157 case eStateExited:
4158 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00004159 m_stdio_communication.SynchronizeWithReadThread();
Pavel Labatha9a43372015-09-03 09:30:17 +00004160 m_stdio_communication.Disconnect();
4161 m_stdio_communication.StopReadThread();
4162 m_stdin_forward = false;
4163
Pavel Labath3f5df532015-03-12 10:12:41 +00004164 // fall-through
4165 case eStateConnected:
4166 case eStateAttaching:
4167 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004168 // These events indicate changes in the state of the debugging session, always report them.
4169 return_value = true;
4170 break;
4171 case eStateInvalid:
4172 // We stopped for no apparent reason, don't report it.
4173 return_value = false;
4174 break;
4175 case eStateRunning:
4176 case eStateStepping:
4177 // If we've started the target running, we handle the cases where we
4178 // are already running and where there is a transition from stopped to
4179 // running differently.
4180 // running -> running: Automatically suppress extra running events
4181 // stopped -> running: Report except when there is one or more no votes
4182 // and no yes votes.
4183 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004184 if (m_force_next_event_delivery)
4185 return_value = true;
4186 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004188 switch (m_last_broadcast_state)
4189 {
4190 case eStateRunning:
4191 case eStateStepping:
4192 // We always suppress multiple runnings with no PUBLIC stop in between.
4193 return_value = false;
4194 break;
4195 default:
4196 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004197 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004198 // events. If I run the lldb/test/thread/a.out file and
4199 // break at main.cpp:58, run and hit the breakpoints on
4200 // multiple threads, then somehow during the stepping over
4201 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004202
Jim Ingham1460e4b2014-01-10 23:46:59 +00004203 // This is a transition from stop to run.
4204 switch (m_thread_list.ShouldReportRun (event_ptr))
4205 {
4206 case eVoteYes:
4207 case eVoteNoOpinion:
4208 return_value = true;
4209 break;
4210 case eVoteNo:
4211 return_value = false;
4212 break;
4213 }
4214 break;
4215 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004216 }
4217 break;
4218 case eStateStopped:
4219 case eStateCrashed:
4220 case eStateSuspended:
4221 {
4222 // We've stopped. First see if we're going to restart the target.
4223 // If we are going to stop, then we always broadcast the event.
4224 // 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 +00004225 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004226
Pavel Labath3f5df532015-03-12 10:12:41 +00004227 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00004228 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004229 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004230 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004231 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004232 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004233 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004234 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004235 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4236 // so they can properly set their state.
4237 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004238 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004239 }
4240 else
4241 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004242 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4243 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004244
Jim Ingham0161b492013-02-09 01:29:05 +00004245 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4246 // Asking the thread list is also not likely to go well, since we are running again.
4247 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004248
Jim Ingham0161b492013-02-09 01:29:05 +00004249 if (!was_restarted)
4250 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004251
Jim Ingham221d51c2013-05-08 00:35:16 +00004252 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004253 {
Jim Ingham0161b492013-02-09 01:29:05 +00004254 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4255 if (log)
4256 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004257 should_resume, StateAsCString(state),
4258 was_restarted, stop_vote);
4259
Jim Ingham0161b492013-02-09 01:29:05 +00004260 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004261 {
4262 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004263 return_value = true;
4264 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004265 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004266 case eVoteNo:
4267 return_value = false;
4268 break;
4269 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004270
Jim Inghamcb95f342012-09-05 21:13:56 +00004271 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004272 {
4273 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004274 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4275 static_cast<void*>(event_ptr),
4276 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004277 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004278 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004279 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004280
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004281 }
4282 else
4283 {
4284 return_value = true;
4285 SynchronouslyNotifyStateChanged (state);
4286 }
4287 }
4288 }
Jim Ingham0161b492013-02-09 01:29:05 +00004289 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004290 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004291
Jim Ingham1460e4b2014-01-10 23:46:59 +00004292 // Forcing the next event delivery is a one shot deal. So reset it here.
4293 m_force_next_event_delivery = false;
4294
Jim Ingham0161b492013-02-09 01:29:05 +00004295 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4296 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4297 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4298 // because the PublicState reflects the last event pulled off the queue, and there may be several
4299 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4300 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004301
Jim Ingham0161b492013-02-09 01:29:05 +00004302 if (return_value)
4303 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004304
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004305 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004306 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004307 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004308 StateAsCString(m_last_broadcast_state),
4309 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004310 return return_value;
4311}
4312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004313
4314bool
Jim Ingham60c915e2015-06-23 21:02:45 +00004315Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004316{
Greg Clayton5160ce52013-03-27 23:08:40 +00004317 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004318
Greg Clayton8b82f082011-04-12 05:54:46 +00004319 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004320 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004321 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4322
Jim Ingham60c915e2015-06-23 21:02:45 +00004323 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004324 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004325
4326 // Create a thread that watches our internal state and controls which
4327 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004328 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004329
Zachary Turner39de3112014-09-09 20:54:56 +00004330 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004331 {
Zachary Turner39de3112014-09-09 20:54:56 +00004332 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4333 if (already_running)
4334 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4335 else
4336 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004337 }
Jim Ingham372787f2012-04-07 00:00:41 +00004338 else
Todd Fiala17096d72014-07-16 19:03:16 +00004339 {
4340 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004341 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004342 else
Zachary Turner39de3112014-09-09 20:54:56 +00004343 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004344 }
4345
Jim Ingham076b3042012-04-10 01:21:57 +00004346 // Create the private state thread, and start it running.
Jim Ingham60c915e2015-06-23 21:02:45 +00004347 PrivateStateThreadArgs args = {this, is_secondary_thread};
4348 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) &args, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004349 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004350 {
4351 ResumePrivateStateThread();
4352 return true;
4353 }
4354 else
4355 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004356}
4357
4358void
4359Process::PausePrivateStateThread ()
4360{
4361 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4362}
4363
4364void
4365Process::ResumePrivateStateThread ()
4366{
4367 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4368}
4369
4370void
4371Process::StopPrivateStateThread ()
4372{
Greg Clayton8b82f082011-04-12 05:54:46 +00004373 if (PrivateStateThreadIsValid ())
4374 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004375 else
4376 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004377 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004378 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004379 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004380 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004381}
4382
4383void
4384Process::ControlPrivateStateThread (uint32_t signal)
4385{
Greg Clayton5160ce52013-03-27 23:08:40 +00004386 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004387
4388 assert (signal == eBroadcastInternalStateControlStop ||
4389 signal == eBroadcastInternalStateControlPause ||
4390 signal == eBroadcastInternalStateControlResume);
4391
4392 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004393 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004394
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004395 // Signal the private state thread. First we should copy this is case the
4396 // thread starts exiting since the private state thread will NULL this out
4397 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004398 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004399 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004400 {
4401 TimeValue timeout_time;
4402 bool timed_out;
4403
4404 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4405
4406 timeout_time = TimeValue::Now();
4407 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004408 if (log)
4409 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004410 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4411 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4412
4413 if (signal == eBroadcastInternalStateControlStop)
4414 {
4415 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004416 {
Zachary Turner39de3112014-09-09 20:54:56 +00004417 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004418 if (log)
4419 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4420 }
4421 else
4422 {
4423 if (log)
4424 log->Printf ("The control event killed the private state thread without having to cancel.");
4425 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004426
4427 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004428 private_state_thread.Join(&result);
4429 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004430 }
4431 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004432 else
4433 {
4434 if (log)
4435 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4436 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004437}
4438
4439void
Jim Inghamcfc09352012-07-27 23:57:19 +00004440Process::SendAsyncInterrupt ()
4441{
4442 if (PrivateStateThreadIsValid())
4443 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4444 else
4445 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4446}
4447
4448void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004449Process::HandlePrivateEvent (EventSP &event_sp)
4450{
Greg Clayton5160ce52013-03-27 23:08:40 +00004451 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004452 m_resume_requested = false;
4453
Jim Inghamaacc3182012-06-06 00:29:30 +00004454 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004455
Greg Clayton414f5d32011-01-25 02:58:48 +00004456 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004457
4458 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004459 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004460 {
Jim Ingham754ab982011-01-29 04:05:41 +00004461 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004462 if (log)
4463 log->Printf ("Ran next event action, result was %d.", action_result);
4464
Jim Inghambb3a2832011-01-29 01:49:25 +00004465 switch (action_result)
4466 {
4467 case NextEventAction::eEventActionSuccess:
4468 SetNextEventAction(NULL);
4469 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004470
Jim Inghambb3a2832011-01-29 01:49:25 +00004471 case NextEventAction::eEventActionRetry:
4472 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004473
Jim Inghambb3a2832011-01-29 01:49:25 +00004474 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004475 // Handle Exiting Here. If we already got an exited event,
4476 // we should just propagate it. Otherwise, swallow this event,
4477 // and set our state to exit so the next event will kill us.
4478 if (new_state != eStateExited)
4479 {
4480 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004481 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004482 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004483 SetNextEventAction(NULL);
4484 return;
4485 }
4486 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004487 break;
4488 }
4489 }
4490
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004491 // See if we should broadcast this state to external clients?
4492 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004493
4494 if (should_broadcast)
4495 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004496 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004497 if (log)
4498 {
Daniel Malead01b2952012-11-29 21:49:15 +00004499 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004500 __FUNCTION__,
4501 GetID(),
4502 StateAsCString(new_state),
4503 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004504 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004505 }
Jim Ingham9575d842011-03-11 03:53:59 +00004506 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004507 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004508 {
4509 // Only push the input handler if we aren't fowarding events,
4510 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004511 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004512 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4513 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004514 {
Greg Clayton44d93782014-01-27 23:43:24 +00004515 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004516 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4517 if (log)
4518 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4519 }
Greg Clayton44d93782014-01-27 23:43:24 +00004520 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004521 else if (StateIsStoppedState(new_state, false))
4522 {
4523 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4524 {
4525 // If the lldb_private::Debugger is handling the events, we don't
4526 // want to pop the process IOHandler here, we want to do it when
4527 // we receive the stopped event so we can carefully control when
4528 // the process IOHandler is popped because when we stop we want to
4529 // display some text stating how and why we stopped, then maybe some
4530 // process/thread/frame info, and then we want the "(lldb) " prompt
4531 // to show up. If we pop the process IOHandler here, then we will
4532 // cause the command interpreter to become the top IOHandler after
4533 // the process pops off and it will update its prompt right away...
4534 // See the Debugger.cpp file where it calls the function as
4535 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4536 // Otherwise we end up getting overlapping "(lldb) " prompts and
4537 // garbled output.
4538 //
4539 // If we aren't handling the events in the debugger (which is indicated
4540 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4541 // are hijacked, then we always pop the process IO handler manually.
4542 // Hijacking happens when the internal process state thread is running
4543 // thread plans, or when commands want to run in synchronous mode
4544 // and they call "process->WaitForProcessToStop()". An example of something
4545 // that will hijack the events is a simple expression:
4546 //
4547 // (lldb) expr (int)puts("hello")
4548 //
4549 // This will cause the internal process state thread to resume and halt
4550 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4551 // events) and we do need the IO handler to be pushed and popped
4552 // correctly.
4553
Zachary Turner7529df92015-09-01 20:02:29 +00004554 if (is_hijacked || GetTarget().GetDebugger().IsHandlingEvents() == false)
Greg Claytonb4874f12014-02-28 18:22:24 +00004555 PopProcessIOHandler ();
4556 }
4557 }
Jim Ingham9575d842011-03-11 03:53:59 +00004558
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004559 BroadcastEvent (event_sp);
4560 }
4561 else
4562 {
4563 if (log)
4564 {
Daniel Malead01b2952012-11-29 21:49:15 +00004565 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004566 __FUNCTION__,
4567 GetID(),
4568 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004569 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004570 }
4571 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004572 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004573}
4574
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004575thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004576Process::PrivateStateThread (void *arg)
4577{
Jim Ingham60c915e2015-06-23 21:02:45 +00004578 PrivateStateThreadArgs *real_args = static_cast<PrivateStateThreadArgs *> (arg);
4579 thread_result_t result = real_args->process->RunPrivateStateThread(real_args->is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004580 return result;
4581}
4582
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004583thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004584Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004585{
Jim Ingham076b3042012-04-10 01:21:57 +00004586 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004587 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004588
Greg Clayton5160ce52013-03-27 23:08:40 +00004589 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004590 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004591 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4592 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004593
4594 bool exit_now = false;
4595 while (!exit_now)
4596 {
4597 EventSP event_sp;
4598 WaitForEventsPrivate (NULL, event_sp, control_only);
4599 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4600 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004601 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004602 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4603 __FUNCTION__, static_cast<void*>(this), GetID(),
4604 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004605
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004606 switch (event_sp->GetType())
4607 {
4608 case eBroadcastInternalStateControlStop:
4609 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004610 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004611
4612 case eBroadcastInternalStateControlPause:
4613 control_only = true;
4614 break;
4615
4616 case eBroadcastInternalStateControlResume:
4617 control_only = false;
4618 break;
4619 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004620
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004621 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004622 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004623 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004624 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4625 {
4626 if (m_public_state.GetValue() == eStateAttaching)
4627 {
4628 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004629 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4630 __FUNCTION__, static_cast<void*>(this),
4631 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004632 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4633 }
4634 else
4635 {
4636 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004637 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4638 __FUNCTION__, static_cast<void*>(this),
4639 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004640 Halt();
4641 }
4642 continue;
4643 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004644
4645 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4646
4647 if (internal_state != eStateInvalid)
4648 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004649 if (m_clear_thread_plans_on_stop &&
4650 StateIsStoppedState(internal_state, true))
4651 {
4652 m_clear_thread_plans_on_stop = false;
4653 m_thread_list.DiscardThreadPlans();
4654 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004655 HandlePrivateEvent (event_sp);
4656 }
4657
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004658 if (internal_state == eStateInvalid ||
4659 internal_state == eStateExited ||
4660 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004661 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004662 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004663 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4664 __FUNCTION__, static_cast<void*>(this), GetID(),
4665 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004666
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004667 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004668 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004669 }
4670
Caroline Tice20ad3c42010-10-29 21:48:37 +00004671 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004672 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004673 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4674 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004675
Jim Ingham60c915e2015-06-23 21:02:45 +00004676 // If we are a secondary thread, then the primary thread we are working for will have already
4677 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4678 // try to change it on the way out.
4679 if (!is_secondary_thread)
4680 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004681 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004682 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004683 return NULL;
4684}
4685
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004686//------------------------------------------------------------------
4687// Process Event Data
4688//------------------------------------------------------------------
4689
4690Process::ProcessEventData::ProcessEventData () :
4691 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004692 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004693 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004694 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004695 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004696 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004697{
4698}
4699
4700Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4701 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004702 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004703 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004704 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004705 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004706 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004707{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004708 if (process_sp)
4709 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004710}
4711
4712Process::ProcessEventData::~ProcessEventData()
4713{
4714}
4715
4716const ConstString &
4717Process::ProcessEventData::GetFlavorString ()
4718{
4719 static ConstString g_flavor ("Process::ProcessEventData");
4720 return g_flavor;
4721}
4722
4723const ConstString &
4724Process::ProcessEventData::GetFlavor () const
4725{
4726 return ProcessEventData::GetFlavorString ();
4727}
4728
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004729void
4730Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4731{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004732 ProcessSP process_sp(m_process_wp.lock());
4733
4734 if (!process_sp)
4735 return;
4736
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004737 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004738 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4739 // the public event queue, then other times when we're pretending that this is where we stopped at the
4740 // end of expression evaluation. m_update_state is used to distinguish these
4741 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004742 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004743 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004744 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004745
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004746 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004747
4748 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4749 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4750 // end up restarting the process.
4751 if (m_interrupted)
4752 return;
4753
4754 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004755 if (m_state == eStateStopped && ! m_restarted)
Greg Clayton2e309072015-07-17 23:42:28 +00004756 {
4757 // Let process subclasses know we are about to do a public stop and
4758 // do anything they might need to in order to speed up register and
4759 // memory accesses.
4760 process_sp->WillPublicStop();
4761
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004762 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004763 uint32_t num_threads = curr_thread_list.GetSize();
4764 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004765
Jim Ingham4b536182011-08-09 02:12:22 +00004766 // The actions might change one of the thread's stop_info's opinions about whether we should
4767 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004768
4769 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4770 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4771 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4772 // 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
4773 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004774 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004775 for (idx = 0; idx < num_threads; ++idx)
4776 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4777
Jim Inghamc7078c22012-12-13 22:24:15 +00004778 // Use this to track whether we should continue from here. We will only continue the target running if
4779 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4780 // then it doesn't matter what the other threads say...
4781
4782 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004783
Jim Ingham0ad7e052013-04-25 02:04:59 +00004784 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4785 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4786 // thing to do is, and it's better to let the user decide than continue behind their backs.
4787
4788 bool does_anybody_have_an_opinion = false;
4789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004790 for (idx = 0; idx < num_threads; ++idx)
4791 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004792 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004793 if (curr_thread_list.GetSize() != num_threads)
4794 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004795 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004796 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004797 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 +00004798 break;
4799 }
4800
4801 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4802
4803 if (thread_sp->GetIndexID() != thread_index_array[idx])
4804 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004805 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004806 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004807 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004808 idx,
4809 thread_index_array[idx],
4810 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004811 break;
4812 }
4813
Jim Inghamb15bfc72010-10-20 00:39:53 +00004814 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004815 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004816 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004817 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004818 bool this_thread_wants_to_stop;
4819 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004820 {
Jim Ingham0161b492013-02-09 01:29:05 +00004821 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4822 }
4823 else
4824 {
4825 stop_info_sp->PerformAction(event_ptr);
4826 // The stop action might restart the target. If it does, then we want to mark that in the
4827 // event so that whoever is receiving it will know to wait for the running event and reflect
4828 // that state appropriately.
4829 // We also need to stop processing actions, since they aren't expecting the target to be running.
4830
4831 // FIXME: we might have run.
4832 if (stop_info_sp->HasTargetRunSinceMe())
4833 {
4834 SetRestarted (true);
4835 break;
4836 }
4837
4838 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004839 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004840
Jim Inghamc7078c22012-12-13 22:24:15 +00004841 if (still_should_stop == false)
4842 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004843 }
4844 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004845
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004846
Jim Inghama8ca6e22013-05-03 23:04:37 +00004847 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004848 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004849 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004850 {
4851 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004852 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004853 // Use the public resume method here, since this is just
4854 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004855 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004856 }
4857 else
4858 {
4859 // If we didn't restart, run the Stop Hooks here:
4860 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004861 process_sp->GetTarget().RunStopHooks();
4862 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004863 SetRestarted(true);
4864 }
Jim Ingham9575d842011-03-11 03:53:59 +00004865 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004866 }
4867}
4868
4869void
4870Process::ProcessEventData::Dump (Stream *s) const
4871{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004872 ProcessSP process_sp(m_process_wp.lock());
4873
4874 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004875 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004876 static_cast<void*>(process_sp.get()), process_sp->GetID());
4877 else
4878 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004879
Greg Clayton8b82f082011-04-12 05:54:46 +00004880 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004881}
4882
4883const Process::ProcessEventData *
4884Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4885{
4886 if (event_ptr)
4887 {
4888 const EventData *event_data = event_ptr->GetData();
4889 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4890 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4891 }
4892 return NULL;
4893}
4894
4895ProcessSP
4896Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4897{
4898 ProcessSP process_sp;
4899 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4900 if (data)
4901 process_sp = data->GetProcessSP();
4902 return process_sp;
4903}
4904
4905StateType
4906Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4907{
4908 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4909 if (data == NULL)
4910 return eStateInvalid;
4911 else
4912 return data->GetState();
4913}
4914
4915bool
4916Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4917{
4918 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4919 if (data == NULL)
4920 return false;
4921 else
4922 return data->GetRestarted();
4923}
4924
4925void
4926Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4927{
4928 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4929 if (data != NULL)
4930 data->SetRestarted(new_value);
4931}
4932
Jim Ingham0161b492013-02-09 01:29:05 +00004933size_t
4934Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4935{
4936 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4937 if (data != NULL)
4938 return data->GetNumRestartedReasons();
4939 else
4940 return 0;
4941}
4942
4943const char *
4944Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4945{
4946 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4947 if (data != NULL)
4948 return data->GetRestartedReasonAtIndex(idx);
4949 else
4950 return NULL;
4951}
4952
4953void
4954Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4955{
4956 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4957 if (data != NULL)
4958 data->AddRestartedReason(reason);
4959}
4960
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004961bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004962Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4963{
4964 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4965 if (data == NULL)
4966 return false;
4967 else
4968 return data->GetInterrupted ();
4969}
4970
4971void
4972Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4973{
4974 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4975 if (data != NULL)
4976 data->SetInterrupted(new_value);
4977}
4978
4979bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004980Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4981{
4982 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4983 if (data)
4984 {
4985 data->SetUpdateStateOnRemoval();
4986 return true;
4987 }
4988 return false;
4989}
4990
Greg Claytond9e416c2012-02-18 05:35:26 +00004991lldb::TargetSP
4992Process::CalculateTarget ()
4993{
Zachary Turner7529df92015-09-01 20:02:29 +00004994 return m_target_sp.lock();
Greg Claytond9e416c2012-02-18 05:35:26 +00004995}
4996
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004997void
Greg Clayton0603aa92010-10-04 01:05:56 +00004998Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004999{
Zachary Turner7529df92015-09-01 20:02:29 +00005000 exe_ctx.SetTargetPtr (&GetTarget());
Greg Claytonc14ee322011-09-22 04:58:26 +00005001 exe_ctx.SetProcessPtr (this);
5002 exe_ctx.SetThreadPtr(NULL);
5003 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005004}
5005
Greg Claytone996fd32011-03-08 22:40:15 +00005006//uint32_t
5007//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
5008//{
5009// return 0;
5010//}
5011//
5012//ArchSpec
5013//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
5014//{
5015// return Host::GetArchSpecForExistingProcess (pid);
5016//}
5017//
5018//ArchSpec
5019//Process::GetArchSpecForExistingProcess (const char *process_name)
5020//{
5021// return Host::GetArchSpecForExistingProcess (process_name);
5022//}
5023//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005024void
5025Process::AppendSTDOUT (const char * s, size_t len)
5026{
Greg Clayton3af9ea52010-11-18 05:57:03 +00005027 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005028 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00005029 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005030}
5031
5032void
Greg Clayton93e86192011-11-13 04:45:22 +00005033Process::AppendSTDERR (const char * s, size_t len)
5034{
5035 Mutex::Locker locker (m_stdio_communication_mutex);
5036 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00005037 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00005038}
5039
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005040void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005041Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005042{
5043 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005044 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005045 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
5046}
5047
5048size_t
5049Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
5050{
5051 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005052 if (m_profile_data.empty())
5053 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005054
5055 std::string &one_profile_data = m_profile_data.front();
5056 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005057 if (bytes_available > 0)
5058 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005059 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005060 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005061 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5062 static_cast<void*>(buf),
5063 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005064 if (bytes_available > buf_size)
5065 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005066 memcpy(buf, one_profile_data.c_str(), buf_size);
5067 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005068 bytes_available = buf_size;
5069 }
5070 else
5071 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005072 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005073 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005074 }
5075 }
5076 return bytes_available;
5077}
5078
5079
Greg Clayton93e86192011-11-13 04:45:22 +00005080//------------------------------------------------------------------
5081// Process STDIO
5082//------------------------------------------------------------------
5083
5084size_t
5085Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5086{
5087 Mutex::Locker locker(m_stdio_communication_mutex);
5088 size_t bytes_available = m_stdout_data.size();
5089 if (bytes_available > 0)
5090 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005091 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005092 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005093 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5094 static_cast<void*>(buf),
5095 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005096 if (bytes_available > buf_size)
5097 {
5098 memcpy(buf, m_stdout_data.c_str(), buf_size);
5099 m_stdout_data.erase(0, buf_size);
5100 bytes_available = buf_size;
5101 }
5102 else
5103 {
5104 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5105 m_stdout_data.clear();
5106 }
5107 }
5108 return bytes_available;
5109}
5110
5111
5112size_t
5113Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5114{
5115 Mutex::Locker locker(m_stdio_communication_mutex);
5116 size_t bytes_available = m_stderr_data.size();
5117 if (bytes_available > 0)
5118 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005119 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005120 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005121 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5122 static_cast<void*>(buf),
5123 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005124 if (bytes_available > buf_size)
5125 {
5126 memcpy(buf, m_stderr_data.c_str(), buf_size);
5127 m_stderr_data.erase(0, buf_size);
5128 bytes_available = buf_size;
5129 }
5130 else
5131 {
5132 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5133 m_stderr_data.clear();
5134 }
5135 }
5136 return bytes_available;
5137}
5138
5139void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005140Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5141{
5142 Process *process = (Process *) baton;
5143 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5144}
5145
Greg Clayton44d93782014-01-27 23:43:24 +00005146class IOHandlerProcessSTDIO :
5147 public IOHandler
5148{
5149public:
5150 IOHandlerProcessSTDIO (Process *process,
5151 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005152 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005153 m_process (process),
5154 m_read_file (),
5155 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005156 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005157 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005158 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00005159 m_read_file.SetDescriptor(GetInputFD(), false);
5160 }
5161
5162 virtual
5163 ~IOHandlerProcessSTDIO ()
5164 {
5165
5166 }
5167
Greg Clayton44d93782014-01-27 23:43:24 +00005168 // Each IOHandler gets to run until it is done. It should read data
5169 // from the "in" and place output into "out" and "err and return
5170 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00005171 void
5172 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00005173 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005174 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005175 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005176 SetIsDone(true);
5177 return;
5178 }
5179
5180 SetIsDone(false);
5181 const int read_fd = m_read_file.GetDescriptor();
5182 TerminalState terminal_state;
5183 terminal_state.Save (read_fd, false);
5184 Terminal terminal(read_fd);
5185 terminal.SetCanonical(false);
5186 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005187// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005188#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005189 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5190 while (!GetIsDone())
5191 {
5192 fd_set read_fdset;
5193 FD_ZERO (&read_fdset);
5194 FD_SET (read_fd, &read_fdset);
5195 FD_SET (pipe_read_fd, &read_fdset);
5196 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5197 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5198 if (num_set_fds < 0)
5199 {
5200 const int select_errno = errno;
5201
5202 if (select_errno != EINTR)
5203 SetIsDone(true);
5204 }
5205 else if (num_set_fds > 0)
5206 {
5207 char ch = 0;
5208 size_t n;
5209 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00005210 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005211 n = 1;
5212 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005213 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005214 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005215 SetIsDone(true);
5216 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005217 else
5218 SetIsDone(true);
5219 }
5220 if (FD_ISSET (pipe_read_fd, &read_fdset))
5221 {
5222 size_t bytes_read;
5223 // Consume the interrupt byte
5224 Error error = m_pipe.Read(&ch, 1, bytes_read);
5225 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00005226 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005227 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00005228 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005229 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00005230 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005231 break;
5232 case 'i':
5233 if (StateIsRunningState(m_process->GetState()))
5234 m_process->Halt();
5235 break;
Greg Clayton44d93782014-01-27 23:43:24 +00005236 }
5237 }
5238 }
Greg Clayton44d93782014-01-27 23:43:24 +00005239 }
Greg Clayton44d93782014-01-27 23:43:24 +00005240 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005241#endif
5242 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005243 }
5244
Pavel Labath44464872015-05-27 12:40:32 +00005245 void
5246 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005247 {
Greg Clayton19e11352014-02-26 22:47:33 +00005248 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005249 size_t bytes_written = 0;
5250 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005251 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005252
Pavel Labath44464872015-05-27 12:40:32 +00005253 bool
5254 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005255 {
Greg Clayton19e11352014-02-26 22:47:33 +00005256 // Do only things that are safe to do in an interrupt context (like in
5257 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5258 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5259 // that was written to the pipe and then call m_process->Halt() from a
5260 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005261 if (m_active)
5262 {
5263 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005264 size_t bytes_written = 0;
5265 Error result = m_pipe.Write(&ch, 1, bytes_written);
5266 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005267 }
5268 else
5269 {
5270 // This IOHandler might be pushed on the stack, but not being run currently
5271 // so do the right thing if we aren't actively watching for STDIN by sending
5272 // the interrupt to the process. Otherwise the write to the pipe above would
5273 // do nothing. This can happen when the command interpreter is running and
5274 // gets a "expression ...". It will be on the IOHandler thread and sending
5275 // the input is complete to the delegate which will cause the expression to
5276 // run, which will push the process IO handler, but not run it.
5277
5278 if (StateIsRunningState(m_process->GetState()))
5279 {
5280 m_process->SendAsyncInterrupt();
5281 return true;
5282 }
5283 }
5284 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005285 }
Greg Clayton44d93782014-01-27 23:43:24 +00005286
Pavel Labath44464872015-05-27 12:40:32 +00005287 void
5288 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005289 {
5290
5291 }
5292
5293protected:
5294 Process *m_process;
5295 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5296 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005297 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005298};
5299
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005300void
Greg Clayton44d93782014-01-27 23:43:24 +00005301Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005302{
5303 // First set up the Read Thread for reading/handling process I/O
5304
Greg Clayton44d93782014-01-27 23:43:24 +00005305 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005306
5307 if (conn_ap.get())
5308 {
5309 m_stdio_communication.SetConnection (conn_ap.release());
5310 if (m_stdio_communication.IsConnected())
5311 {
5312 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5313 m_stdio_communication.StartReadThread();
5314
5315 // Now read thread is set up, set up input reader.
5316
5317 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005318 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005319 }
5320 }
5321}
5322
Greg Claytonb4874f12014-02-28 18:22:24 +00005323bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005324Process::ProcessIOHandlerIsActive ()
5325{
5326 IOHandlerSP io_handler_sp (m_process_input_reader);
5327 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005328 return GetTarget().GetDebugger().IsTopIOHandler (io_handler_sp);
Greg Clayton6fea17e2014-03-03 19:15:20 +00005329 return false;
5330}
5331bool
Greg Clayton44d93782014-01-27 23:43:24 +00005332Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005333{
Greg Clayton44d93782014-01-27 23:43:24 +00005334 IOHandlerSP io_handler_sp (m_process_input_reader);
5335 if (io_handler_sp)
5336 {
Pavel Labath44464872015-05-27 12:40:32 +00005337 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5338 if (log)
5339 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5340
Greg Clayton44d93782014-01-27 23:43:24 +00005341 io_handler_sp->SetIsDone(false);
Zachary Turner7529df92015-09-01 20:02:29 +00005342 GetTarget().GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005343 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005344 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005345 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005346}
5347
Greg Claytonb4874f12014-02-28 18:22:24 +00005348bool
Greg Clayton44d93782014-01-27 23:43:24 +00005349Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005350{
Greg Clayton44d93782014-01-27 23:43:24 +00005351 IOHandlerSP io_handler_sp (m_process_input_reader);
5352 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005353 return GetTarget().GetDebugger().PopIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005354 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005355}
5356
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005357// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005358void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005359Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005360{
Greg Clayton6920b522012-08-22 18:39:03 +00005361 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005362}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005363
Greg Clayton99d0faf2010-11-18 23:32:35 +00005364void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005365Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005366{
Greg Clayton6920b522012-08-22 18:39:03 +00005367 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005368}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005369
Jim Ingham1624a2d2014-05-05 02:26:40 +00005370ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005371Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005372 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005373 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005374 Stream &errors)
5375{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005376 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005377
Jim Ingham77787032011-01-20 02:03:18 +00005378 if (thread_plan_sp.get() == NULL)
5379 {
5380 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005381 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005382 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005383
Jim Ingham7d7931d2013-03-28 00:05:34 +00005384 if (!thread_plan_sp->ValidatePlan(NULL))
5385 {
5386 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005387 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005388 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005389
Greg Claytonc14ee322011-09-22 04:58:26 +00005390 if (exe_ctx.GetProcessPtr() != this)
5391 {
5392 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005393 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005394 }
5395
5396 Thread *thread = exe_ctx.GetThreadPtr();
5397 if (thread == NULL)
5398 {
5399 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005400 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005401 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005402
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005403 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5404 // For that to be true the plan can't be private - since private plans suppress themselves in the
5405 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005406
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005407 bool orig_plan_private = thread_plan_sp->GetPrivate();
5408 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005409
Jim Ingham444586b2011-01-24 06:34:17 +00005410 if (m_private_state.GetValue() != eStateStopped)
5411 {
5412 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005413 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005414 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005415
Jim Ingham66243842011-08-13 00:56:10 +00005416 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005417 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005418 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005419 if (!selected_frame_sp)
5420 {
5421 thread->SetSelectedFrame(0);
5422 selected_frame_sp = thread->GetSelectedFrame();
5423 if (!selected_frame_sp)
5424 {
5425 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005426 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005427 }
5428 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005429
Jim Ingham11b0e052013-02-19 23:22:45 +00005430 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005431
5432 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5433 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005434
Greg Claytonc14ee322011-09-22 04:58:26 +00005435 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005436
Jim Ingham66243842011-08-13 00:56:10 +00005437 uint32_t selected_tid;
5438 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005439 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005440 {
5441 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005442 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005443 }
5444 else
5445 {
5446 selected_tid = LLDB_INVALID_THREAD_ID;
5447 }
5448
Zachary Turner39de3112014-09-09 20:54:56 +00005449 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005450 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005451 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005452
Greg Clayton5160ce52013-03-27 23:08:40 +00005453 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005454 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005455 {
Jim Ingham076b3042012-04-10 01:21:57 +00005456 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5457 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005458 // 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 +00005459 // we are fielding public events here.
5460 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005461 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 +00005462
Jim Ingham372787f2012-04-07 00:00:41 +00005463 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005464
5465 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5466 // returning control here.
5467 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5468 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5469 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5470 // do just what we want.
5471 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5472 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5473 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5474 old_state = m_public_state.GetValue();
5475 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005476
Jim Ingham076b3042012-04-10 01:21:57 +00005477 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005478 StartPrivateStateThread(true);
5479 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005480
Jim Ingham372787f2012-04-07 00:00:41 +00005481 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005482
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005483 if (options.GetDebug())
5484 {
5485 // In this case, we aren't actually going to run, we just want to stop right away.
5486 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5487 // FIXME: To make this prettier we should invent some stop reason for this, but that
5488 // is only cosmetic, and this functionality is only of use to lldb developers who can
5489 // live with not pretty...
5490 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005491 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005492 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005493
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005494 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005495
Sean Callanana46ec452012-07-11 21:31:24 +00005496 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005497
Jim Ingham77787032011-01-20 02:03:18 +00005498 {
Sean Callanana46ec452012-07-11 21:31:24 +00005499 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5500 // restored on exit to the function.
5501 //
5502 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5503 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005504
Sean Callanana46ec452012-07-11 21:31:24 +00005505 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005506
Jim Inghamf48169b2010-11-30 02:22:11 +00005507 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005508 {
5509 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005510 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005511 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005512 thread->GetIndexID(),
5513 thread->GetID(),
5514 s.GetData());
5515 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005516
Sean Callanana46ec452012-07-11 21:31:24 +00005517 bool got_event;
5518 lldb::EventSP event_sp;
5519 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005520
Sean Callanana46ec452012-07-11 21:31:24 +00005521 TimeValue* timeout_ptr = NULL;
5522 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005523
Jim Ingham0161b492013-02-09 01:29:05 +00005524 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 +00005525 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005526 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005527 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005528
Jim Ingham0161b492013-02-09 01:29:05 +00005529 // This is just for accounting:
5530 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005531
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005532 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005533 uint32_t one_thread_timeout_usec;
5534 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005535
5536 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5537 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5538 // first timeout already.
5539
5540 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005541 {
5542 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005543 one_thread_timeout_usec = 0;
5544 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005545 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005546 else
Jim Ingham0161b492013-02-09 01:29:05 +00005547 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005548 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005549
Jim Ingham914f4e72014-03-28 21:58:28 +00005550 // If the overall wait is forever, then we only need to set the one thread timeout:
5551 if (timeout_usec == 0)
5552 {
Ed Maste801335c2014-03-31 19:28:14 +00005553 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005554 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005555 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005556 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005557 }
Jim Ingham0161b492013-02-09 01:29:05 +00005558 else
5559 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005560 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5561 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5562 uint64_t computed_one_thread_timeout;
5563 if (option_one_thread_timeout != 0)
5564 {
5565 if (timeout_usec < option_one_thread_timeout)
5566 {
5567 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005568 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005569 }
5570 computed_one_thread_timeout = option_one_thread_timeout;
5571 }
5572 else
5573 {
5574 computed_one_thread_timeout = timeout_usec / 2;
5575 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5576 computed_one_thread_timeout = default_one_thread_timeout_usec;
5577 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005578 one_thread_timeout_usec = computed_one_thread_timeout;
5579 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5580
Jim Ingham0161b492013-02-09 01:29:05 +00005581 }
Jim Ingham0161b492013-02-09 01:29:05 +00005582 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005583
5584 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005585 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 +00005586 options.GetStopOthers(),
5587 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005588 before_first_timeout,
5589 one_thread_timeout_usec,
5590 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005591
Jim Ingham1460e4b2014-01-10 23:46:59 +00005592 // This isn't going to work if there are unfetched events on the queue.
5593 // Are there cases where we might want to run the remaining events here, and then try to
5594 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005595
Jim Ingham1460e4b2014-01-10 23:46:59 +00005596 Event *other_events = listener.PeekAtNextEvent();
5597 if (other_events != NULL)
5598 {
5599 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005600 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005601 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005602
Jim Ingham1460e4b2014-01-10 23:46:59 +00005603 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5604 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5605 // event coalescing to cause us to lose OUR running event...
5606 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005607
Jim Ingham8559a352012-11-26 23:52:18 +00005608 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5609 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005610
5611#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5612 // It's pretty much impossible to write test cases for things like:
5613 // One thread timeout expires, I go to halt, but the process already stopped
5614 // on the function call stop breakpoint. Turning on this define will make us not
5615 // fetch the first event till after the halt. So if you run a quick function, it will have
5616 // completed, and the completion event will be waiting, when you interrupt for halt.
5617 // The expression evaluation should still succeed.
5618 bool miss_first_event = true;
5619#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005620 TimeValue one_thread_timeout;
5621 TimeValue final_timeout;
5622
Jim Ingham35878c42014-04-08 21:33:21 +00005623
Sean Callanana46ec452012-07-11 21:31:24 +00005624 while (1)
5625 {
5626 // We usually want to resume the process if we get to the top of the loop.
5627 // The only exception is if we get two running events with no intervening
5628 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005629 if (log)
5630 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5631 do_resume,
5632 handle_running_event,
5633 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005634
Jim Ingham184e9812013-01-15 02:47:48 +00005635 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005636 {
5637 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005638
Jim Ingham184e9812013-01-15 02:47:48 +00005639 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005640 {
Jim Ingham0161b492013-02-09 01:29:05 +00005641 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005642 Error resume_error = PrivateResume ();
5643 if (!resume_error.Success())
5644 {
Jim Ingham0161b492013-02-09 01:29:05 +00005645 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5646 num_resumes,
5647 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005648 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005649 break;
5650 }
Sean Callanana46ec452012-07-11 21:31:24 +00005651 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005652
Jim Ingham0161b492013-02-09 01:29:05 +00005653 TimeValue resume_timeout = TimeValue::Now();
5654 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005655
Jim Ingham0161b492013-02-09 01:29:05 +00005656 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005657 if (!got_event)
5658 {
5659 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005660 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5661 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005662
Jim Ingham0161b492013-02-09 01:29:05 +00005663 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005664 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005665 break;
5666 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005667
Sean Callanana46ec452012-07-11 21:31:24 +00005668 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005669
Sean Callanana46ec452012-07-11 21:31:24 +00005670 if (stop_state != eStateRunning)
5671 {
Jim Ingham0161b492013-02-09 01:29:05 +00005672 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005673
Jim Ingham0161b492013-02-09 01:29:05 +00005674 if (stop_state == eStateStopped)
5675 {
5676 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5677 if (log)
5678 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5679 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5680 num_resumes,
5681 StateAsCString(stop_state),
5682 restarted,
5683 do_resume,
5684 handle_running_event);
5685 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005686
Jim Ingham0161b492013-02-09 01:29:05 +00005687 if (restarted)
5688 {
5689 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5690 // event here. But if I do, the best thing is to Halt and then get out of here.
5691 Halt();
5692 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005693
Jim Ingham35e1bda2012-10-16 21:41:58 +00005694 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5695 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005696 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005697 break;
5698 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005699
Sean Callanana46ec452012-07-11 21:31:24 +00005700 if (log)
5701 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5702 // We need to call the function synchronously, so spin waiting for it to return.
5703 // If we get interrupted while executing, we're going to lose our context, and
5704 // won't be able to gather the result at this point.
5705 // We set the timeout AFTER the resume, since the resume takes some time and we
5706 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005707 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005708 else
5709 {
Sean Callanana46ec452012-07-11 21:31:24 +00005710 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005711 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005712 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005713
Jim Ingham0161b492013-02-09 01:29:05 +00005714 if (before_first_timeout)
5715 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005716 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005717 {
5718 one_thread_timeout = TimeValue::Now();
5719 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005720 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005721 }
Jim Ingham0161b492013-02-09 01:29:05 +00005722 else
5723 {
5724 if (timeout_usec == 0)
5725 timeout_ptr = NULL;
5726 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005727 {
5728 final_timeout = TimeValue::Now();
5729 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005730 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005731 }
Jim Ingham0161b492013-02-09 01:29:05 +00005732 }
5733 }
5734 else
5735 {
5736 if (timeout_usec == 0)
5737 timeout_ptr = NULL;
5738 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005739 {
5740 final_timeout = TimeValue::Now();
5741 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005742 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005743 }
Jim Ingham0161b492013-02-09 01:29:05 +00005744 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005745
Jim Ingham0161b492013-02-09 01:29:05 +00005746 do_resume = true;
5747 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005748
Sean Callanana46ec452012-07-11 21:31:24 +00005749 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005750 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005751
Jim Ingham0f16e732011-02-08 05:20:59 +00005752 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005753 {
Sean Callanana46ec452012-07-11 21:31:24 +00005754 if (timeout_ptr)
5755 {
Matt Kopec676a4872013-02-21 23:55:31 +00005756 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005757 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5758 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005759 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005760 else
Sean Callanana46ec452012-07-11 21:31:24 +00005761 {
5762 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5763 }
5764 }
Jim Ingham35878c42014-04-08 21:33:21 +00005765
5766#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5767 // See comment above...
5768 if (miss_first_event)
5769 {
5770 usleep(1000);
5771 miss_first_event = false;
5772 got_event = false;
5773 }
5774 else
5775#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005776 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005777
Sean Callanana46ec452012-07-11 21:31:24 +00005778 if (got_event)
5779 {
5780 if (event_sp.get())
5781 {
5782 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005783 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005784 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005785 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005786 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005787 errors.Printf ("Execution halted by user interrupt.");
5788 if (log)
5789 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005790 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005791 }
5792 else
5793 {
5794 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5795 if (log)
5796 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005797
Jim Inghamcfc09352012-07-27 23:57:19 +00005798 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005799 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005800 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005801 {
Jim Ingham0161b492013-02-09 01:29:05 +00005802 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005803 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5804 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005805 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005806 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005807 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005808 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005809 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005810 }
5811 else
5812 {
Jim Ingham0161b492013-02-09 01:29:05 +00005813 // If we were restarted, we just need to go back up to fetch another event.
5814 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005815 {
5816 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005817 {
5818 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5819 }
5820 keep_going = true;
5821 do_resume = false;
5822 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005823
Jim Inghamcfc09352012-07-27 23:57:19 +00005824 }
5825 else
5826 {
Jim Ingham0161b492013-02-09 01:29:05 +00005827 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5828 StopReason stop_reason = eStopReasonInvalid;
5829 if (stop_info_sp)
5830 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005831
Jim Ingham0161b492013-02-09 01:29:05 +00005832 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5833 // it is OUR plan that is complete?
5834 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005835 {
5836 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005837 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5838 // Now mark this plan as private so it doesn't get reported as the stop reason
5839 // after this point.
5840 if (thread_plan_sp)
5841 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005842 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005843 }
5844 else
5845 {
Jim Ingham0161b492013-02-09 01:29:05 +00005846 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005847 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005848 {
5849 if (log)
5850 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005851 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005852 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005853 {
5854 event_to_broadcast_sp = event_sp;
5855 }
Jim Ingham0161b492013-02-09 01:29:05 +00005856 }
Jim Ingham184e9812013-01-15 02:47:48 +00005857 else
Jim Ingham0161b492013-02-09 01:29:05 +00005858 {
5859 if (log)
5860 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005861 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005862 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005863 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005864 }
Jim Ingham184e9812013-01-15 02:47:48 +00005865 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005866 }
Sean Callanana46ec452012-07-11 21:31:24 +00005867 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005868 }
5869 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005870
Jim Inghamcfc09352012-07-27 23:57:19 +00005871 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005872 // This shouldn't really happen, but sometimes we do get two running events without an
5873 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005874 do_resume = false;
5875 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005876 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005877 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005878
Jim Inghamcfc09352012-07-27 23:57:19 +00005879 default:
5880 if (log)
5881 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005882
Jim Inghamcfc09352012-07-27 23:57:19 +00005883 if (stop_state == eStateExited)
5884 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005885
Sean Callananbf154da2012-08-08 17:35:10 +00005886 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005887 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005888 break;
5889 }
Sean Callanana46ec452012-07-11 21:31:24 +00005890 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005891
Sean Callanana46ec452012-07-11 21:31:24 +00005892 if (keep_going)
5893 continue;
5894 else
5895 break;
5896 }
5897 else
5898 {
5899 if (log)
5900 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005901 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005902 break;
5903 }
5904 }
5905 else
5906 {
5907 // If we didn't get an event that means we've timed out...
5908 // We will interrupt the process here. Depending on what we were asked to do we will
5909 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005910
Sean Callanana46ec452012-07-11 21:31:24 +00005911 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005912 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005913 {
Jim Ingham0161b492013-02-09 01:29:05 +00005914 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005915 {
5916 if (timeout_usec != 0)
5917 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005918 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005919 "running for %" PRIu32 " usec with all threads enabled.",
5920 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005921 }
5922 else
5923 {
5924 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005925 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005926 }
5927 }
Sean Callanana46ec452012-07-11 21:31:24 +00005928 else
5929 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005930 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005931 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005932 }
5933 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005934 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005935 "abandoning execution.",
5936 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005937 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005938
Jim Ingham0161b492013-02-09 01:29:05 +00005939 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5940 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5941 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5942 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5943 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005944
Jim Ingham0161b492013-02-09 01:29:05 +00005945 bool back_to_top = true;
5946 uint32_t try_halt_again = 0;
5947 bool do_halt = true;
5948 const uint32_t num_retries = 5;
5949 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005950 {
Jim Ingham0161b492013-02-09 01:29:05 +00005951 Error halt_error;
5952 if (do_halt)
5953 {
5954 if (log)
5955 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5956 halt_error = Halt();
5957 }
5958 if (halt_error.Success())
5959 {
5960 if (log)
5961 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005962
Jim Ingham0161b492013-02-09 01:29:05 +00005963 real_timeout = TimeValue::Now();
5964 real_timeout.OffsetWithMicroSeconds(500000);
5965
5966 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005967
Jim Ingham0161b492013-02-09 01:29:05 +00005968 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005969 {
Jim Ingham0161b492013-02-09 01:29:05 +00005970 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5971 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005972 {
Jim Ingham0161b492013-02-09 01:29:05 +00005973 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5974 if (stop_state == lldb::eStateStopped
5975 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5976 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005977 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005978
Jim Ingham0161b492013-02-09 01:29:05 +00005979 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005980 {
Jim Ingham0161b492013-02-09 01:29:05 +00005981 // Between the time we initiated the Halt and the time we delivered it, the process could have
5982 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005983
Jim Ingham0161b492013-02-09 01:29:05 +00005984 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5985 {
5986 if (log)
5987 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5988 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005989 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005990 back_to_top = false;
5991 break;
5992 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005993
Jim Ingham0161b492013-02-09 01:29:05 +00005994 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5995 {
5996 if (log)
5997 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5998 "Exiting wait loop.");
5999 try_halt_again++;
6000 do_halt = false;
6001 continue;
6002 }
Sean Callanana46ec452012-07-11 21:31:24 +00006003
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006004 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00006005 {
6006 if (log)
6007 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006008 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006009 back_to_top = false;
6010 break;
6011 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006012
Jim Ingham0161b492013-02-09 01:29:05 +00006013 if (before_first_timeout)
6014 {
6015 // Set all the other threads to run, and return to the top of the loop, which will continue;
6016 before_first_timeout = false;
6017 thread_plan_sp->SetStopOthers (false);
6018 if (log)
6019 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00006020
Jim Ingham0161b492013-02-09 01:29:05 +00006021 back_to_top = true;
6022 break;
6023 }
6024 else
6025 {
6026 // Running all threads failed, so return Interrupted.
6027 if (log)
6028 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006029 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006030 back_to_top = false;
6031 break;
6032 }
Sean Callanana46ec452012-07-11 21:31:24 +00006033 }
6034 }
6035 else
Jim Ingham0161b492013-02-09 01:29:05 +00006036 { if (log)
6037 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
6038 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006039 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006040 back_to_top = false;
6041 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006042 }
6043 }
Jim Ingham0161b492013-02-09 01:29:05 +00006044 else
6045 {
6046 try_halt_again++;
6047 continue;
6048 }
Sean Callanana46ec452012-07-11 21:31:24 +00006049 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006050
Jim Ingham0161b492013-02-09 01:29:05 +00006051 if (!back_to_top || try_halt_again > num_retries)
6052 break;
6053 else
6054 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006055 }
Sean Callanana46ec452012-07-11 21:31:24 +00006056 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006057
Sean Callanana46ec452012-07-11 21:31:24 +00006058 // 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 +00006059 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006060 {
6061 StopPrivateStateThread();
6062 Error error;
6063 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006064 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006065 {
6066 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6067 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006068 if (old_state != eStateInvalid)
6069 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006070 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006071
Jim Ingham184e9812013-01-15 02:47:48 +00006072 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6073 // could happen:
6074 // 1) The execution successfully completed
6075 // 2) We hit a breakpoint, and ignore_breakpoints was true
6076 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006077 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6078 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006079
Jim Ingham8646d3c2014-05-05 02:47:44 +00006080 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006081 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006082 {
6083 thread_plan_sp->RestoreThreadState();
6084 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006085
Sean Callanana46ec452012-07-11 21:31:24 +00006086 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006087 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006088 {
6089 if (log)
6090 {
6091 StreamString s;
6092 if (event_sp)
6093 event_sp->Dump (&s);
6094 else
6095 {
6096 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6097 }
6098
6099 StreamString ts;
6100
6101 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006102
Sean Callanana46ec452012-07-11 21:31:24 +00006103 do
6104 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006105 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006106 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006107 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006108 break;
6109 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006110 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006111 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006112 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006113 break;
6114 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006115 else
Sean Callanana46ec452012-07-11 21:31:24 +00006116 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006117 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6118
6119 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006120 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006121 event_explanation = "<no event data>";
6122 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006123 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006124
Jim Inghamcfc09352012-07-27 23:57:19 +00006125 Process *process = event_data->GetProcessSP().get();
6126
6127 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006128 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006129 event_explanation = "<no process>";
6130 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006131 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006132
Jim Inghamcfc09352012-07-27 23:57:19 +00006133 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006134
Jim Inghamcfc09352012-07-27 23:57:19 +00006135 uint32_t num_threads = thread_list.GetSize();
6136 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006137
Jim Inghamcfc09352012-07-27 23:57:19 +00006138 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006139
Jim Inghamcfc09352012-07-27 23:57:19 +00006140 for (thread_index = 0;
6141 thread_index < num_threads;
6142 ++thread_index)
6143 {
6144 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006145
Jim Inghamcfc09352012-07-27 23:57:19 +00006146 if (!thread)
6147 {
6148 ts.Printf("<?> ");
6149 continue;
6150 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006151
Daniel Malead01b2952012-11-29 21:49:15 +00006152 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006153 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006154
Jim Inghamcfc09352012-07-27 23:57:19 +00006155 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006156 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006157 else
6158 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006159
Jim Inghamcfc09352012-07-27 23:57:19 +00006160 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6161 if (stop_info_sp)
6162 {
6163 const char *stop_desc = stop_info_sp->GetDescription();
6164 if (stop_desc)
6165 ts.PutCString (stop_desc);
6166 }
6167 ts.Printf(">");
6168 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006169
Jim Inghamcfc09352012-07-27 23:57:19 +00006170 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006171 }
Sean Callanana46ec452012-07-11 21:31:24 +00006172 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006173
Jim Inghamcfc09352012-07-27 23:57:19 +00006174 if (event_explanation)
6175 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006176 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006177 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6178 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006179
Jim Inghame4483cf2013-09-27 01:13:01 +00006180 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006181 {
6182 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006183 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6184 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006185 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6186 thread_plan_sp->SetPrivate (orig_plan_private);
6187 }
6188 else
6189 {
6190 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006191 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6192 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006193 }
6194 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006195 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006196 {
6197 if (log)
6198 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006199
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006200 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006201 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006202 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006203 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006204 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006205 }
6206 else
6207 {
Sean Callanana46ec452012-07-11 21:31:24 +00006208 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006209 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006210 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006211 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006212 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006213 }
6214 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6215 {
6216 if (log)
6217 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006218 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006219 }
6220 else
6221 {
6222 if (log)
6223 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006224 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006225 {
6226 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006227 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006228 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6229 thread_plan_sp->SetPrivate (orig_plan_private);
6230 }
6231 }
6232 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006233
Sean Callanana46ec452012-07-11 21:31:24 +00006234 // Thread we ran the function in may have gone away because we ran the target
6235 // Check that it's still there, and if it is put it back in the context. Also restore the
6236 // frame in the context if it is still present.
6237 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6238 if (thread)
6239 {
6240 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6241 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006242
Sean Callanana46ec452012-07-11 21:31:24 +00006243 // Also restore the current process'es selected frame & thread, since this function calling may
6244 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006245
Sean Callanana46ec452012-07-11 21:31:24 +00006246 if (selected_tid != LLDB_INVALID_THREAD_ID)
6247 {
6248 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6249 {
6250 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006251 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006252 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006253 if (old_frame_sp)
6254 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006255 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006256 }
6257 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006258
Sean Callanana46ec452012-07-11 21:31:24 +00006259 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006260
Sean Callanana46ec452012-07-11 21:31:24 +00006261 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006262 {
Sean Callanana46ec452012-07-11 21:31:24 +00006263 if (log)
6264 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6265 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006266 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006267
Jim Inghamf48169b2010-11-30 02:22:11 +00006268 return return_value;
6269}
6270
6271const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006272Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006273{
6274 const char *result_name;
6275
6276 switch (result)
6277 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006278 case eExpressionCompleted:
6279 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006280 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006281 case eExpressionDiscarded:
6282 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006283 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006284 case eExpressionInterrupted:
6285 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006286 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006287 case eExpressionHitBreakpoint:
6288 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006289 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006290 case eExpressionSetupError:
6291 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006292 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006293 case eExpressionParseError:
6294 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006295 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006296 case eExpressionResultUnavailable:
6297 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006298 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006299 case eExpressionTimedOut:
6300 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006301 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006302 case eExpressionStoppedForDebug:
6303 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006304 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006305 }
6306 return result_name;
6307}
6308
Greg Clayton7260f622011-04-18 08:33:37 +00006309void
6310Process::GetStatus (Stream &strm)
6311{
6312 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006313 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006314 {
6315 if (state == eStateExited)
6316 {
6317 int exit_status = GetExitStatus();
6318 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006319 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006320 GetID(),
6321 exit_status,
6322 exit_status,
6323 exit_description ? exit_description : "");
6324 }
6325 else
6326 {
6327 if (state == eStateConnected)
6328 strm.Printf ("Connected to remote target.\n");
6329 else
Daniel Malead01b2952012-11-29 21:49:15 +00006330 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006331 }
6332 }
6333 else
6334 {
Daniel Malead01b2952012-11-29 21:49:15 +00006335 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006336 }
6337}
6338
6339size_t
6340Process::GetThreadStatus (Stream &strm,
6341 bool only_threads_with_stop_reason,
6342 uint32_t start_frame,
6343 uint32_t num_frames,
6344 uint32_t num_frames_with_source)
6345{
6346 size_t num_thread_infos_dumped = 0;
6347
Jim Ingham4a65fb12014-03-07 11:20:03 +00006348 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6349 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6350 // ID's, and look them up one by one:
6351
6352 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006353 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006354 //Scope for thread list locker;
6355 {
6356 Mutex::Locker locker (GetThreadList().GetMutex());
6357 ThreadList &curr_thread_list = GetThreadList();
6358 num_threads = curr_thread_list.GetSize();
6359 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006360 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006361 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006362 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006363 }
6364
Greg Clayton7260f622011-04-18 08:33:37 +00006365 for (uint32_t i = 0; i < num_threads; i++)
6366 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006367 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006368 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006369 {
6370 if (only_threads_with_stop_reason)
6371 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006372 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006373 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006374 continue;
6375 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006376 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006377 start_frame,
6378 num_frames,
6379 num_frames_with_source);
6380 ++num_thread_infos_dumped;
6381 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006382 else
6383 {
6384 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6385 if (log)
6386 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6387
6388 }
Greg Clayton7260f622011-04-18 08:33:37 +00006389 }
6390 return num_thread_infos_dumped;
6391}
6392
Greg Claytona9f40ad2012-02-22 04:37:26 +00006393void
6394Process::AddInvalidMemoryRegion (const LoadRange &region)
6395{
6396 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6397}
6398
6399bool
6400Process::RemoveInvalidMemoryRange (const LoadRange &region)
6401{
6402 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6403}
6404
Jim Ingham372787f2012-04-07 00:00:41 +00006405void
6406Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6407{
6408 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6409}
6410
6411bool
6412Process::RunPreResumeActions ()
6413{
6414 bool result = true;
6415 while (!m_pre_resume_actions.empty())
6416 {
6417 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6418 m_pre_resume_actions.pop_back();
6419 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006420 if (result == true)
6421 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006422 }
6423 return result;
6424}
6425
6426void
6427Process::ClearPreResumeActions ()
6428{
6429 m_pre_resume_actions.clear();
6430}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006431
Zachary Turner93749ab2015-03-03 21:51:25 +00006432ProcessRunLock &
6433Process::GetRunLock()
6434{
6435 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6436 return m_private_run_lock;
6437 else
6438 return m_public_run_lock;
6439}
6440
Greg Claytonfa559e52012-05-18 02:38:05 +00006441void
6442Process::Flush ()
6443{
6444 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006445 m_extended_thread_list.Flush();
6446 m_extended_thread_stop_id = 0;
6447 m_queue_list.Clear();
6448 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006449}
Greg Clayton90ba8112012-12-05 00:16:59 +00006450
6451void
6452Process::DidExec ()
6453{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006454 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6455 if (log)
6456 log->Printf ("Process::%s()", __FUNCTION__);
6457
Greg Clayton90ba8112012-12-05 00:16:59 +00006458 Target &target = GetTarget();
6459 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006460 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006461 m_dynamic_checkers_ap.reset();
6462 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006463 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006464 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006465 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006466 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006467 m_image_tokens.clear();
6468 m_allocated_memory_cache.Clear();
6469 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006470 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006471 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006472 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006473 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006474 DoDidExec();
6475 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006476 // Flush the process (threads and all stack frames) after running CompleteAttach()
6477 // in case the dynamic loader loaded things in new locations.
6478 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006479
6480 // After we figure out what was loaded/unloaded in CompleteAttach,
6481 // we need to let the target know so it can do any cleanup it needs to.
6482 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006483}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006484
Jim Ingham1460e4b2014-01-10 23:46:59 +00006485addr_t
6486Process::ResolveIndirectFunction(const Address *address, Error &error)
6487{
6488 if (address == nullptr)
6489 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006490 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006491 return LLDB_INVALID_ADDRESS;
6492 }
6493
6494 addr_t function_addr = LLDB_INVALID_ADDRESS;
6495
6496 addr_t addr = address->GetLoadAddress(&GetTarget());
6497 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6498 if (iter != m_resolved_indirect_addresses.end())
6499 {
6500 function_addr = (*iter).second;
6501 }
6502 else
6503 {
6504 if (!InferiorCall(this, address, function_addr))
6505 {
6506 Symbol *symbol = address->CalculateSymbolContextSymbol();
6507 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6508 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6509 function_addr = LLDB_INVALID_ADDRESS;
6510 }
6511 else
6512 {
6513 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6514 }
6515 }
6516 return function_addr;
6517}
6518
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006519void
6520Process::ModulesDidLoad (ModuleList &module_list)
6521{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006522 SystemRuntime *sys_runtime = GetSystemRuntime();
6523 if (sys_runtime)
6524 {
6525 sys_runtime->ModulesDidLoad (module_list);
6526 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006527
Kuba Breckaafdf8422014-10-10 23:43:03 +00006528 GetJITLoaders().ModulesDidLoad (module_list);
6529
6530 // Give runtimes a chance to be created.
6531 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6532
6533 // Tell runtimes about new modules.
6534 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6535 {
6536 InstrumentationRuntimeSP runtime = pos->second;
6537 runtime->ModulesDidLoad(module_list);
6538 }
6539
Greg Clayton35ca64b2015-04-16 17:13:34 +00006540 // Let any language runtimes we have already created know
6541 // about the modules that loaded.
6542
6543 // Iterate over a copy of this language runtime list in case
6544 // the language runtime ModulesDidLoad somehow causes the language
6545 // riuntime to be unloaded.
6546 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6547 for (const auto &pair: language_runtimes)
6548 {
6549 // We must check language_runtime_sp to make sure it is not
6550 // NULL as we might cache the fact that we didn't have a
6551 // language runtime for a language.
6552 LanguageRuntimeSP language_runtime_sp = pair.second;
6553 if (language_runtime_sp)
6554 language_runtime_sp->ModulesDidLoad(module_list);
6555 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006556}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006557
Jason Molendaef7d6412015-08-06 03:27:10 +00006558void
6559Process::PrintWarning (uint64_t warning_type, void *repeat_key, const char *fmt, ...)
6560{
6561 bool print_warning = true;
6562
6563 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
6564 if (stream_sp.get() == nullptr)
6565 return;
6566 if (warning_type == eWarningsOptimization
6567 && GetWarningsOptimization() == false)
6568 {
6569 return;
6570 }
6571
6572 if (repeat_key != nullptr)
6573 {
6574 WarningsCollection::iterator it = m_warnings_issued.find (warning_type);
6575 if (it == m_warnings_issued.end())
6576 {
6577 m_warnings_issued[warning_type] = WarningsPointerSet();
6578 m_warnings_issued[warning_type].insert (repeat_key);
6579 }
6580 else
6581 {
6582 if (it->second.find (repeat_key) != it->second.end())
6583 {
6584 print_warning = false;
6585 }
6586 else
6587 {
6588 it->second.insert (repeat_key);
6589 }
6590 }
6591 }
6592
6593 if (print_warning)
6594 {
6595 va_list args;
6596 va_start (args, fmt);
6597 stream_sp->PrintfVarArg (fmt, args);
6598 va_end (args);
6599 }
6600}
6601
Jason Molenda484900b2015-08-10 07:55:25 +00006602void
6603Process::PrintWarningOptimization (const SymbolContext &sc)
6604{
6605 if (GetWarningsOptimization() == true
6606 && sc.module_sp.get()
6607 && sc.module_sp->GetFileSpec().GetFilename().IsEmpty() == false
6608 && sc.function
6609 && sc.function->GetIsOptimized() == true)
6610 {
6611 PrintWarning (Process::Warnings::eWarningsOptimization, sc.module_sp.get(), "%s was compiled with optimization - stepping may behave oddly; variables may not be available.\n", sc.module_sp->GetFileSpec().GetFilename().GetCString());
6612 }
6613}
6614
Kuba Breckaa51ea382014-09-06 01:33:13 +00006615ThreadCollectionSP
6616Process::GetHistoryThreads(lldb::addr_t addr)
6617{
6618 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006619
Kuba Breckaa51ea382014-09-06 01:33:13 +00006620 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6621
6622 if (! memory_history.get()) {
6623 return threads;
6624 }
6625
6626 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6627
6628 return threads;
6629}
Kuba Brecka63927542014-10-11 01:59:32 +00006630
6631InstrumentationRuntimeSP
6632Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6633{
6634 InstrumentationRuntimeCollection::iterator pos;
6635 pos = m_instrumentation_runtimes.find (type);
6636 if (pos == m_instrumentation_runtimes.end())
6637 {
6638 return InstrumentationRuntimeSP();
6639 }
6640 else
6641 return (*pos).second;
6642}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006643
6644bool
6645Process::GetModuleSpec(const FileSpec& module_file_spec,
6646 const ArchSpec& arch,
6647 ModuleSpec& module_spec)
6648{
6649 module_spec.Clear();
6650 return false;
6651}