blob: adc393fae6717a75d249141e66bc5bb39e19c1ae [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"
Greg Claytoneb0103f2011-04-07 22:46:35 +000021#include "lldb/Expression/ClangUserExpression.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"
Zachary Turner93a66fc2014-10-06 21:22:36 +000031#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000033#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000034#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000035#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000036#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000037#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000039#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000040#include "lldb/Target/LanguageRuntime.h"
41#include "lldb/Target/CPPLanguageRuntime.h"
42#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000043#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000045#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000046#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Target/Target.h"
48#include "lldb/Target/TargetList.h"
49#include "lldb/Target/Thread.h"
50#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000051#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000052#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000053#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000054#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055
56using namespace lldb;
57using namespace lldb_private;
58
Greg Clayton67cc0632012-08-22 17:17:09 +000059
60// Comment out line below to disable memory caching, overriding the process setting
61// target.process.disable-memory-cache
62#define ENABLE_MEMORY_CACHING
63
64#ifdef ENABLE_MEMORY_CACHING
65#define DISABLE_MEM_CACHE_DEFAULT false
66#else
67#define DISABLE_MEM_CACHE_DEFAULT true
68#endif
69
70class ProcessOptionValueProperties : public OptionValueProperties
71{
72public:
73 ProcessOptionValueProperties (const ConstString &name) :
74 OptionValueProperties (name)
75 {
76 }
77
78 // This constructor is used when creating ProcessOptionValueProperties when it
79 // is part of a new lldb_private::Process instance. It will copy all current
80 // global property values as needed
81 ProcessOptionValueProperties (ProcessProperties *global_properties) :
82 OptionValueProperties(*global_properties->GetValueProperties())
83 {
84 }
85
86 virtual const Property *
87 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
88 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000089 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000090 // try and grab the setting from the current process if there is one. Else we just
91 // use the one from this instance.
92 if (exe_ctx)
93 {
94 Process *process = exe_ctx->GetProcessPtr();
95 if (process)
96 {
97 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
98 if (this != instance_properties)
99 return instance_properties->ProtectedGetPropertyAtIndex (idx);
100 }
101 }
102 return ProtectedGetPropertyAtIndex (idx);
103 }
104};
105
106static PropertyDefinition
107g_properties[] =
108{
109 { "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 +0000110 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
111 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000112 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
113 { "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 +0000114 { "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 +0000115 { "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 +0000116 { "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 +0000117 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Jason Molendaef7d6412015-08-06 03:27:10 +0000118 { "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 +0000119 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
120};
121
122enum {
123 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000124 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000125 ePropertyIgnoreBreakpointsInExpressions,
126 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000127 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000128 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000129 ePropertyDetachKeepsStopped,
Jason Molendaef7d6412015-08-06 03:27:10 +0000130 ePropertyMemCacheLineSize,
131 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000132};
133
Greg Clayton332e8b12015-01-13 21:13:08 +0000134ProcessProperties::ProcessProperties (lldb_private::Process *process) :
135 Properties (),
136 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000137{
Greg Clayton332e8b12015-01-13 21:13:08 +0000138 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000139 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000140 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000141 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
142 m_collection_sp->Initialize(g_properties);
143 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000144 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000145 true,
146 Thread::GetGlobalProperties()->GetValueProperties());
147 }
148 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000149 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000150 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000151 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
152 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000153}
154
155ProcessProperties::~ProcessProperties()
156{
157}
158
Greg Clayton332e8b12015-01-13 21:13:08 +0000159void
160ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
161{
162 ProcessProperties *properties = (ProcessProperties *)baton;
163 if (properties->m_process)
164 properties->m_process->LoadOperatingSystemPlugin(true);
165}
166
Greg Clayton67cc0632012-08-22 17:17:09 +0000167bool
168ProcessProperties::GetDisableMemoryCache() const
169{
170 const uint32_t idx = ePropertyDisableMemCache;
171 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
172}
173
Jason Molendaf0340c92014-09-03 22:30:54 +0000174uint64_t
175ProcessProperties::GetMemoryCacheLineSize() const
176{
177 const uint32_t idx = ePropertyMemCacheLineSize;
178 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
179}
180
Greg Clayton67cc0632012-08-22 17:17:09 +0000181Args
182ProcessProperties::GetExtraStartupCommands () const
183{
184 Args args;
185 const uint32_t idx = ePropertyExtraStartCommand;
186 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
187 return args;
188}
189
190void
191ProcessProperties::SetExtraStartupCommands (const Args &args)
192{
193 const uint32_t idx = ePropertyExtraStartCommand;
194 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
195}
196
Greg Claytonc9d645d2012-10-18 22:40:37 +0000197FileSpec
198ProcessProperties::GetPythonOSPluginPath () const
199{
200 const uint32_t idx = ePropertyPythonOSPluginPath;
201 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
202}
203
204void
205ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
206{
207 const uint32_t idx = ePropertyPythonOSPluginPath;
208 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
209}
210
Jim Ingham184e9812013-01-15 02:47:48 +0000211
212bool
213ProcessProperties::GetIgnoreBreakpointsInExpressions () const
214{
215 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
216 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
217}
218
219void
220ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
221{
222 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
223 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
224}
225
226bool
227ProcessProperties::GetUnwindOnErrorInExpressions () const
228{
229 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
230 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
231}
232
233void
234ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
235{
236 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
237 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
238}
239
Jim Ingham29950772013-01-26 02:19:28 +0000240bool
241ProcessProperties::GetStopOnSharedLibraryEvents () const
242{
243 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
244 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
245}
246
247void
248ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
249{
250 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
251 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
252}
253
Jim Inghamacff8952013-05-02 00:27:30 +0000254bool
255ProcessProperties::GetDetachKeepsStopped () const
256{
257 const uint32_t idx = ePropertyDetachKeepsStopped;
258 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
259}
260
261void
262ProcessProperties::SetDetachKeepsStopped (bool stop)
263{
264 const uint32_t idx = ePropertyDetachKeepsStopped;
265 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
266}
267
Jason Molendaef7d6412015-08-06 03:27:10 +0000268bool
269ProcessProperties::GetWarningsOptimization () const
270{
271 const uint32_t idx = ePropertyWarningOptimization;
272 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
273}
274
Greg Clayton32e0a752011-03-30 18:16:51 +0000275void
Greg Clayton8b82f082011-04-12 05:54:46 +0000276ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000277{
278 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000279 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000280 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000281
282 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000283 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000284
285 if (m_executable)
286 {
287 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
288 s.PutCString (" file = ");
289 m_executable.Dump(&s);
290 s.EOL();
291 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 if (argc > 0)
294 {
295 for (uint32_t i=0; i<argc; i++)
296 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000298 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000300 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000301 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000302 }
303 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000304
305 const uint32_t envc = m_environment.GetArgumentCount();
306 if (envc > 0)
307 {
308 for (uint32_t i=0; i<envc; i++)
309 {
310 const char *env = m_environment.GetArgumentAtIndex(i);
311 if (i < 10)
312 s.Printf (" env[%u] = %s\n", i, env);
313 else
314 s.Printf ("env[%u] = %s\n", i, env);
315 }
316 }
317
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000318 if (m_arch.IsValid())
319 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
320
Greg Clayton8b82f082011-04-12 05:54:46 +0000321 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000322 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000323 cstr = platform->GetUserName (m_uid);
324 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000325 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000326 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000327 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000328 cstr = platform->GetGroupName (m_gid);
329 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000330 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000331 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000332 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000333 cstr = platform->GetUserName (m_euid);
334 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000335 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000336 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000337 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000338 cstr = platform->GetGroupName (m_egid);
339 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000340 }
341}
342
343void
Greg Clayton8b82f082011-04-12 05:54:46 +0000344ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000345{
Greg Clayton8b82f082011-04-12 05:54:46 +0000346 const char *label;
347 if (show_args || verbose)
348 label = "ARGUMENTS";
349 else
350 label = "NAME";
351
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000352 if (verbose)
353 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000354 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000355 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
356 }
357 else
358 {
Jim Ingham368ac222014-08-15 17:05:27 +0000359 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
360 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000362}
363
364void
Greg Clayton8b82f082011-04-12 05:54:46 +0000365ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000366{
367 if (m_pid != LLDB_INVALID_PROCESS_ID)
368 {
369 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000370 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000371
Greg Clayton32e0a752011-03-30 18:16:51 +0000372
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 if (verbose)
374 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000375 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000376 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
377 s.Printf ("%-10s ", cstr);
378 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000379 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000380
Greg Clayton8b82f082011-04-12 05:54:46 +0000381 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000382 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
383 s.Printf ("%-10s ", cstr);
384 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000385 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000386
Greg Clayton8b82f082011-04-12 05:54:46 +0000387 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000388 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
389 s.Printf ("%-10s ", cstr);
390 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000391 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000392
Greg Clayton8b82f082011-04-12 05:54:46 +0000393 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000394 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
395 s.Printf ("%-10s ", cstr);
396 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000397 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000398 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
399 }
400 else
401 {
Jim Ingham368ac222014-08-15 17:05:27 +0000402 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000403 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000404 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000405 }
406
Greg Clayton8b82f082011-04-12 05:54:46 +0000407 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000408 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000410 if (argc > 0)
411 {
412 for (uint32_t i=0; i<argc; i++)
413 {
414 if (i > 0)
415 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000416 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000417 }
418 }
419 }
420 else
421 {
422 s.PutCString (GetName());
423 }
424
425 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000426 }
427}
428
Greg Clayton8b82f082011-04-12 05:54:46 +0000429Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000430ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000431{
432 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000433 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000434
435 switch (short_option)
436 {
437 case 's': // Stop at program entry point
438 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
439 break;
440
Greg Clayton8b82f082011-04-12 05:54:46 +0000441 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000442 {
443 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000444 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000445 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000446 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000447 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000448
449 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000450 {
451 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000452 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000453 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000454 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000455 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000456
457 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000458 {
459 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000460 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000461 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000462 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000463 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000464
Greg Clayton8b82f082011-04-12 05:54:46 +0000465 case 'p': // Process plug-in name
466 launch_info.SetProcessPluginName (option_arg);
467 break;
468
469 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000470 {
471 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000472 const FileSpec dev_null{"/dev/null", false};
473 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000474 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000475 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000476 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000477 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000478 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000479 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000480 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000481
482 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000483 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000484 break;
485
486 case 't': // Open process in new terminal window
487 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
488 break;
489
490 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000491 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
492 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000493 break;
494
Todd Fiala51637922014-08-19 17:40:43 +0000495 case 'A': // Disable ASLR.
496 {
497 bool success;
498 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
499 if (success)
500 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
501 else
502 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000503 break;
Todd Fiala51637922014-08-19 17:40:43 +0000504 }
505
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000506 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000507 {
508 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000509 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000510 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000511 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000512 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000513 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000514 break;
515 }
516
Todd Fiala51637922014-08-19 17:40:43 +0000517 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000518 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000519 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000520 else
Zachary Turner10687b02014-10-20 17:46:43 +0000521 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000522 break;
523
Greg Clayton8b82f082011-04-12 05:54:46 +0000524 case 'v':
525 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
526 break;
527
528 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000529 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000530 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000531 }
532 return error;
533}
534
535OptionDefinition
536ProcessLaunchCommandOptions::g_option_table[] =
537{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000538{ 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 +0000539{ 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 +0000540{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
541{ 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."},
542{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
543{ 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 +0000544{ 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 +0000545
Zachary Turnerd37221d2014-07-09 16:31:49 +0000546{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
547{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
548{ 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 +0000549
Zachary Turnerd37221d2014-07-09 16:31:49 +0000550{ 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 +0000551
Zachary Turnerd37221d2014-07-09 16:31:49 +0000552{ 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 +0000553{ 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 +0000554{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000555};
556
557
558
559bool
560ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000561{
562 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
563 return true;
564 const char *match_name = m_match_info.GetName();
565 if (!match_name)
566 return true;
567
568 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
569}
570
571bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000572ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000573{
574 if (!NameMatches (proc_info.GetName()))
575 return false;
576
577 if (m_match_info.ProcessIDIsValid() &&
578 m_match_info.GetProcessID() != proc_info.GetProcessID())
579 return false;
580
581 if (m_match_info.ParentProcessIDIsValid() &&
582 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
583 return false;
584
Greg Clayton8b82f082011-04-12 05:54:46 +0000585 if (m_match_info.UserIDIsValid () &&
586 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000587 return false;
588
Greg Clayton8b82f082011-04-12 05:54:46 +0000589 if (m_match_info.GroupIDIsValid () &&
590 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000591 return false;
592
593 if (m_match_info.EffectiveUserIDIsValid () &&
594 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
595 return false;
596
597 if (m_match_info.EffectiveGroupIDIsValid () &&
598 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
599 return false;
600
601 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000602 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000603 return false;
604 return true;
605}
606
607bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000608ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000609{
610 if (m_name_match_type != eNameMatchIgnore)
611 return false;
612
613 if (m_match_info.ProcessIDIsValid())
614 return false;
615
616 if (m_match_info.ParentProcessIDIsValid())
617 return false;
618
Greg Clayton8b82f082011-04-12 05:54:46 +0000619 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000620 return false;
621
Greg Clayton8b82f082011-04-12 05:54:46 +0000622 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000623 return false;
624
625 if (m_match_info.EffectiveUserIDIsValid ())
626 return false;
627
628 if (m_match_info.EffectiveGroupIDIsValid ())
629 return false;
630
631 if (m_match_info.GetArchitecture().IsValid())
632 return false;
633
634 if (m_match_all_users)
635 return false;
636
637 return true;
638
639}
640
641void
Greg Clayton8b82f082011-04-12 05:54:46 +0000642ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000643{
644 m_match_info.Clear();
645 m_name_match_type = eNameMatchIgnore;
646 m_match_all_users = false;
647}
Greg Clayton58be07b2011-01-07 06:08:19 +0000648
Greg Claytonc3776bf2012-02-09 06:16:32 +0000649ProcessSP
650Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651{
Greg Clayton949e8222013-01-16 17:29:04 +0000652 static uint32_t g_process_unique_id = 0;
653
Greg Claytonc3776bf2012-02-09 06:16:32 +0000654 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000655 ProcessCreateInstance create_callback = NULL;
656 if (plugin_name)
657 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000658 ConstString const_plugin_name(plugin_name);
659 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 if (create_callback)
661 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000662 process_sp = create_callback(target, listener, crash_file_path);
663 if (process_sp)
664 {
Greg Clayton949e8222013-01-16 17:29:04 +0000665 if (process_sp->CanDebug(target, true))
666 {
667 process_sp->m_process_unique_id = ++g_process_unique_id;
668 }
669 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000670 process_sp.reset();
671 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000672 }
673 }
674 else
675 {
Greg Claytonc982c762010-07-09 20:39:50 +0000676 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000678 process_sp = create_callback(target, listener, crash_file_path);
679 if (process_sp)
680 {
Greg Clayton949e8222013-01-16 17:29:04 +0000681 if (process_sp->CanDebug(target, false))
682 {
683 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000684 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000685 }
686 else
687 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000688 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 }
690 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000691 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692}
693
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000694ConstString &
695Process::GetStaticBroadcasterClass ()
696{
697 static ConstString class_name ("lldb.process");
698 return class_name;
699}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000700
701//----------------------------------------------------------------------
702// Process constructor
703//----------------------------------------------------------------------
704Process::Process(Target &target, Listener &listener) :
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000705 Process(target, listener, UnixSignals::Create(HostInfo::GetArchitecture()))
Todd Fiala4ceced32014-08-29 17:35:57 +0000706{
707 // This constructor just delegates to the full Process constructor,
708 // defaulting to using the Host's UnixSignals.
709}
710
711Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000712 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 UserID (LLDB_INVALID_PROCESS_ID),
Ilia K8a00a562015-03-17 16:54:52 +0000714 Broadcaster (&(target.GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716 m_public_state (eStateUnloaded),
717 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000718 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
719 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720 m_private_state_listener ("lldb.process.internal_state_listener"),
721 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000722 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000723 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000725 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726 m_exit_status (-1),
727 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000728 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000729 m_thread_mutex (Mutex::eMutexTypeRecursive),
730 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000732 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000733 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000734 m_queue_list (this),
735 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000737 m_image_tokens (),
738 m_listener (listener),
739 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000740 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000741 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000742 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000743 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000744 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000745 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000746 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000747 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000748 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000749 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
750 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32 +0000751 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42 +0000752 m_memory_cache (*this),
753 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000754 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000755 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000756 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000757 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000758 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000759 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58 +0000760 m_finalizing (false),
761 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000762 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000763 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000764 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000765 m_destroy_in_process (false),
Ewan Crawford90ff7912015-07-14 10:56:58 +0000766 m_can_interpret_function_calls(false),
Jason Molendaef7d6412015-08-06 03:27:10 +0000767 m_warnings_issued (),
Jason Molenda69b6b632013-03-05 03:33:59 +0000768 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000770 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000771
Greg Clayton5160ce52013-03-27 23:08:40 +0000772 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000773 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000774 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775
Todd Fiala4ceced32014-08-29 17:35:57 +0000776 if (!m_unix_signals_sp)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000777 m_unix_signals_sp = std::make_shared<UnixSignals>();
Todd Fiala4ceced32014-08-29 17:35:57 +0000778
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000779 SetEventName (eBroadcastBitStateChanged, "state-changed");
780 SetEventName (eBroadcastBitInterrupt, "interrupt");
781 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
782 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000783 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000784
Greg Clayton35a4cc52012-10-29 20:52:08 +0000785 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
786 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
787 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
788
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 listener.StartListeningForEvents (this,
790 eBroadcastBitStateChanged |
791 eBroadcastBitInterrupt |
792 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000793 eBroadcastBitSTDERR |
794 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795
796 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000797 eBroadcastBitStateChanged |
798 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799
800 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
801 eBroadcastInternalStateControlStop |
802 eBroadcastInternalStateControlPause |
803 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000804 // We need something valid here, even if just the default UnixSignalsSP.
805 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806}
807
808//----------------------------------------------------------------------
809// Destructor
810//----------------------------------------------------------------------
811Process::~Process()
812{
Greg Clayton5160ce52013-03-27 23:08:40 +0000813 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000815 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000817
818 // ThreadList::Clear() will try to acquire this process's mutex, so
819 // explicitly clear the thread list here to ensure that the mutex
820 // is not destroyed before the thread list.
821 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822}
823
Greg Clayton67cc0632012-08-22 17:17:09 +0000824const ProcessPropertiesSP &
825Process::GetGlobalProperties()
826{
827 static ProcessPropertiesSP g_settings_sp;
828 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000829 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000830 return g_settings_sp;
831}
832
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000833void
834Process::Finalize()
835{
Greg Claytonc00ca312015-04-02 18:44:58 +0000836 m_finalizing = true;
837
Ilia Kc7efd562015-03-26 07:40:40 +0000838 // Destroy this process if needed
839 switch (GetPrivateState())
840 {
841 case eStateConnected:
842 case eStateAttaching:
843 case eStateLaunching:
844 case eStateStopped:
845 case eStateRunning:
846 case eStateStepping:
847 case eStateCrashed:
848 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000849 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000850 break;
851
852 case eStateInvalid:
853 case eStateUnloaded:
854 case eStateDetached:
855 case eStateExited:
856 break;
857 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000858
Greg Clayton1ed54f52011-10-01 00:45:15 +0000859 // Clear our broadcaster before we proceed with destroying
860 Broadcaster::Clear();
861
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862 // Do any cleanup needed prior to being destructed... Subclasses
863 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000864
865 // We need to destroy the loader before the derived Process class gets destroyed
866 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000867 m_dynamic_checkers_ap.reset();
868 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000869 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000870 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000871 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000872 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000873 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000874 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000875 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000876 m_queue_list.Clear();
877 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000878 std::vector<Notifications> empty_notifications;
879 m_notifications.swap(empty_notifications);
880 m_image_tokens.clear();
881 m_memory_cache.Clear();
882 m_allocated_memory_cache.Clear();
883 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000884 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000885 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000886 m_stop_info_override_callback = NULL;
Greg Clayton08765fa2015-05-28 03:24:30 +0000887 // Clear the last natural stop ID since it has a strong
888 // reference to this process
889 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000890//#ifdef LLDB_CONFIGURATION_DEBUG
891// StreamFile s(stdout, false);
892// EventSP event_sp;
893// while (m_private_state_listener.GetNextEvent(event_sp))
894// {
895// event_sp->Dump (&s);
896// s.EOL();
897// }
898//#endif
899 // We have to be very careful here as the m_private_state_listener might
900 // contain events that have ProcessSP values in them which can keep this
901 // process around forever. These events need to be cleared out.
902 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000903 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
904 m_public_run_lock.SetStopped();
905 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
906 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000907 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000908}
909
910void
911Process::RegisterNotificationCallbacks (const Notifications& callbacks)
912{
913 m_notifications.push_back(callbacks);
914 if (callbacks.initialize != NULL)
915 callbacks.initialize (callbacks.baton, this);
916}
917
918bool
919Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
920{
921 std::vector<Notifications>::iterator pos, end = m_notifications.end();
922 for (pos = m_notifications.begin(); pos != end; ++pos)
923 {
924 if (pos->baton == callbacks.baton &&
925 pos->initialize == callbacks.initialize &&
926 pos->process_state_changed == callbacks.process_state_changed)
927 {
928 m_notifications.erase(pos);
929 return true;
930 }
931 }
932 return false;
933}
934
935void
936Process::SynchronouslyNotifyStateChanged (StateType state)
937{
938 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
939 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
940 {
941 if (notification_pos->process_state_changed)
942 notification_pos->process_state_changed (notification_pos->baton, this, state);
943 }
944}
945
946// FIXME: We need to do some work on events before the general Listener sees them.
947// For instance if we are continuing from a breakpoint, we need to ensure that we do
948// the little "insert real insn, step & stop" trick. But we can't do that when the
949// event is delivered by the broadcaster - since that is done on the thread that is
950// waiting for new events, so if we needed more than one event for our handling, we would
951// stall. So instead we do it when we fetch the event off of the queue.
952//
953
954StateType
955Process::GetNextEvent (EventSP &event_sp)
956{
957 StateType state = eStateInvalid;
958
959 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
960 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
961
962 return state;
963}
964
Pavel Labath44464872015-05-27 12:40:32 +0000965void
966Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000967{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000968 // don't sync (potentially context switch) in case where there is no process IO
Pavel Labath44464872015-05-27 12:40:32 +0000969 if (! m_process_input_reader)
970 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000971
Pavel Labath44464872015-05-27 12:40:32 +0000972 TimeValue timeout = TimeValue::Now();
973 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
974 uint32_t new_iohandler_id = 0;
975 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000976
Pavel Labath44464872015-05-27 12:40:32 +0000977 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
978 if (log)
979 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 +0000980}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000981
982StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000983Process::WaitForProcessToStop (const TimeValue *timeout,
984 EventSP *event_sp_ptr,
985 bool wait_always,
986 Listener *hijack_listener,
987 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000988{
Jim Ingham4b536182011-08-09 02:12:22 +0000989 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
990 // We have to actually check each event, and in the case of a stopped event check the restarted flag
991 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000992 if (event_sp_ptr)
993 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000994 StateType state = GetState();
995 // If we are exited or detached, we won't ever get back to any
996 // other valid state...
997 if (state == eStateDetached || state == eStateExited)
998 return state;
999
Daniel Malea9e9919f2013-10-09 16:56:28 +00001000 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1001 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001002 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
1003 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001004
1005 if (!wait_always &&
1006 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +00001007 StateIsStoppedState(GetPrivateState(), true))
1008 {
Daniel Malea9e9919f2013-10-09 16:56:28 +00001009 if (log)
1010 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1011 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001012 // We need to toggle the run lock as this won't get done in
1013 // SetPublicState() if the process is hijacked.
1014 if (hijack_listener)
1015 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001016 return state;
1017 }
1018
Jim Ingham4b536182011-08-09 02:12:22 +00001019 while (state != eStateInvalid)
1020 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001021 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001022 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001023 if (event_sp_ptr && event_sp)
1024 *event_sp_ptr = event_sp;
1025
Greg Claytondc6224e2014-10-21 01:00:42 +00001026 bool pop_process_io_handler = hijack_listener != NULL;
1027 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1028
Jim Ingham4b536182011-08-09 02:12:22 +00001029 switch (state)
1030 {
1031 case eStateCrashed:
1032 case eStateDetached:
1033 case eStateExited:
1034 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001035 // We need to toggle the run lock as this won't get done in
1036 // SetPublicState() if the process is hijacked.
1037 if (hijack_listener)
1038 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001039 return state;
1040 case eStateStopped:
1041 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1042 continue;
1043 else
Greg Clayton44d93782014-01-27 23:43:24 +00001044 {
1045 // We need to toggle the run lock as this won't get done in
1046 // SetPublicState() if the process is hijacked.
1047 if (hijack_listener)
1048 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001049 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001050 }
Jim Ingham4b536182011-08-09 02:12:22 +00001051 default:
1052 continue;
1053 }
1054 }
1055 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056}
1057
Greg Claytondc6224e2014-10-21 01:00:42 +00001058bool
1059Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1060 Stream *stream,
1061 bool &pop_process_io_handler)
1062{
1063 const bool handle_pop = pop_process_io_handler == true;
1064
1065 pop_process_io_handler = false;
1066 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1067
1068 if (!process_sp)
1069 return false;
1070
1071 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1072 if (event_state == eStateInvalid)
1073 return false;
1074
1075 switch (event_state)
1076 {
1077 case eStateInvalid:
1078 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001079 case eStateAttaching:
1080 case eStateLaunching:
1081 case eStateStepping:
1082 case eStateDetached:
1083 {
1084 if (stream)
1085 stream->Printf ("Process %" PRIu64 " %s\n",
1086 process_sp->GetID(),
1087 StateAsCString (event_state));
1088
1089 if (event_state == eStateDetached)
1090 pop_process_io_handler = true;
1091 }
1092 break;
1093
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001094 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001095 case eStateRunning:
1096 // Don't be chatty when we run...
1097 break;
1098
1099 case eStateExited:
1100 if (stream)
1101 process_sp->GetStatus(*stream);
1102 pop_process_io_handler = true;
1103 break;
1104
1105 case eStateStopped:
1106 case eStateCrashed:
1107 case eStateSuspended:
1108 // Make sure the program hasn't been auto-restarted:
1109 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1110 {
1111 if (stream)
1112 {
1113 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1114 if (num_reasons > 0)
1115 {
1116 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1117 if (num_reasons == 1)
1118 {
1119 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1120 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1121 process_sp->GetID(),
1122 reason ? reason : "<UNKNOWN REASON>");
1123 }
1124 else
1125 {
1126 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1127 process_sp->GetID());
1128
1129
1130 for (size_t i = 0; i < num_reasons; i++)
1131 {
1132 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1133 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1134 }
1135 }
1136 }
1137 }
1138 }
1139 else
1140 {
1141 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1142 {
1143 ThreadList &thread_list = process_sp->GetThreadList();
1144 Mutex::Locker locker (thread_list.GetMutex());
1145
1146 ThreadSP curr_thread (thread_list.GetSelectedThread());
1147 ThreadSP thread;
1148 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1149 if (curr_thread)
1150 curr_thread_stop_reason = curr_thread->GetStopReason();
1151 if (!curr_thread ||
1152 !curr_thread->IsValid() ||
1153 curr_thread_stop_reason == eStopReasonInvalid ||
1154 curr_thread_stop_reason == eStopReasonNone)
1155 {
1156 // Prefer a thread that has just completed its plan over another thread as current thread.
1157 ThreadSP plan_thread;
1158 ThreadSP other_thread;
Jim Inghamce400d92015-07-08 00:06:30 +00001159
Greg Claytondc6224e2014-10-21 01:00:42 +00001160 const size_t num_threads = thread_list.GetSize();
1161 size_t i;
1162 for (i = 0; i < num_threads; ++i)
1163 {
1164 thread = thread_list.GetThreadAtIndex(i);
1165 StopReason thread_stop_reason = thread->GetStopReason();
1166 switch (thread_stop_reason)
1167 {
1168 case eStopReasonInvalid:
1169 case eStopReasonNone:
1170 break;
1171
Jim Inghamce400d92015-07-08 00:06:30 +00001172 case eStopReasonSignal:
1173 {
1174 // Don't select a signal thread if we weren't going to stop at that
1175 // signal. We have to have had another reason for stopping here, and
1176 // the user doesn't want to see this thread.
1177 uint64_t signo = thread->GetStopInfo()->GetValue();
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001178 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
Jim Inghamce400d92015-07-08 00:06:30 +00001179 {
1180 if (!other_thread)
1181 other_thread = thread;
1182 }
1183 break;
1184 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001185 case eStopReasonTrace:
1186 case eStopReasonBreakpoint:
1187 case eStopReasonWatchpoint:
Greg Claytondc6224e2014-10-21 01:00:42 +00001188 case eStopReasonException:
1189 case eStopReasonExec:
1190 case eStopReasonThreadExiting:
1191 case eStopReasonInstrumentation:
1192 if (!other_thread)
1193 other_thread = thread;
1194 break;
1195 case eStopReasonPlanComplete:
1196 if (!plan_thread)
1197 plan_thread = thread;
1198 break;
1199 }
1200 }
1201 if (plan_thread)
1202 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1203 else if (other_thread)
1204 thread_list.SetSelectedThreadByID (other_thread->GetID());
1205 else
1206 {
1207 if (curr_thread && curr_thread->IsValid())
1208 thread = curr_thread;
1209 else
1210 thread = thread_list.GetThreadAtIndex(0);
1211
1212 if (thread)
1213 thread_list.SetSelectedThreadByID (thread->GetID());
1214 }
1215 }
1216 }
1217 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1218 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1219 // have a hard time restarting the process.
1220 if (stream)
1221 {
1222 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1223 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1224 {
1225 const bool only_threads_with_stop_reason = true;
1226 const uint32_t start_frame = 0;
1227 const uint32_t num_frames = 1;
1228 const uint32_t num_frames_with_source = 1;
1229 process_sp->GetStatus(*stream);
1230 process_sp->GetThreadStatus (*stream,
1231 only_threads_with_stop_reason,
1232 start_frame,
1233 num_frames,
1234 num_frames_with_source);
1235 }
1236 else
1237 {
1238 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1239 if (target_idx != UINT32_MAX)
1240 stream->Printf ("Target %d: (", target_idx);
1241 else
1242 stream->Printf ("Target <unknown index>: (");
1243 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1244 stream->Printf (") stopped.\n");
1245 }
1246 }
1247
1248 // Pop the process IO handler
1249 pop_process_io_handler = true;
1250 }
1251 break;
1252 }
1253
1254 if (handle_pop && pop_process_io_handler)
1255 process_sp->PopProcessIOHandler();
1256
1257 return true;
1258}
1259
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260
1261StateType
1262Process::WaitForState
1263(
1264 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001265 const StateType *match_states,
1266 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001267)
1268{
1269 EventSP event_sp;
1270 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001271 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272 while (state != eStateInvalid)
1273 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001274 // If we are exited or detached, we won't ever get back to any
1275 // other valid state...
1276 if (state == eStateDetached || state == eStateExited)
1277 return state;
1278
Greg Clayton44d93782014-01-27 23:43:24 +00001279 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001280
1281 for (i=0; i<num_match_states; ++i)
1282 {
1283 if (match_states[i] == state)
1284 return state;
1285 }
1286 }
1287 return state;
1288}
1289
Jim Ingham30f9b212010-10-11 23:53:14 +00001290bool
1291Process::HijackProcessEvents (Listener *listener)
1292{
1293 if (listener != NULL)
1294 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001295 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001296 }
1297 else
1298 return false;
1299}
1300
1301void
1302Process::RestoreProcessEvents ()
1303{
1304 RestoreBroadcaster();
1305}
1306
Jim Ingham0f16e732011-02-08 05:20:59 +00001307bool
1308Process::HijackPrivateProcessEvents (Listener *listener)
1309{
1310 if (listener != NULL)
1311 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001312 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001313 }
1314 else
1315 return false;
1316}
1317
1318void
1319Process::RestorePrivateProcessEvents ()
1320{
1321 m_private_state_broadcaster.RestoreBroadcaster();
1322}
1323
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001325Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001326{
Greg Clayton5160ce52013-03-27 23:08:40 +00001327 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328
1329 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001330 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1331 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332
Greg Clayton44d93782014-01-27 23:43:24 +00001333 Listener *listener = hijack_listener;
1334 if (listener == NULL)
1335 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001336
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001338 if (listener->WaitForEventForBroadcasterWithType (timeout,
1339 this,
1340 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1341 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001342 {
1343 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1344 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1345 else if (log)
1346 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1347 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001348
1349 if (log)
1350 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001351 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352 StateAsCString(state));
1353 return state;
1354}
1355
1356Event *
1357Process::PeekAtStateChangedEvents ()
1358{
Greg Clayton5160ce52013-03-27 23:08:40 +00001359 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360
1361 if (log)
1362 log->Printf ("Process::%s...", __FUNCTION__);
1363
1364 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001365 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1366 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367 if (log)
1368 {
1369 if (event_ptr)
1370 {
1371 log->Printf ("Process::%s (event_ptr) => %s",
1372 __FUNCTION__,
1373 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1374 }
1375 else
1376 {
1377 log->Printf ("Process::%s no events found",
1378 __FUNCTION__);
1379 }
1380 }
1381 return event_ptr;
1382}
1383
1384StateType
1385Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1386{
Greg Clayton5160ce52013-03-27 23:08:40 +00001387 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388
1389 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001390 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1391 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392
1393 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001394 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1395 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001396 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001397 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001398 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1399 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400
1401 // This is a bit of a hack, but when we wait here we could very well return
1402 // to the command-line, and that could disable the log, which would render the
1403 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001405 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1406 __FUNCTION__, static_cast<const void *>(timeout),
1407 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001408 return state;
1409}
1410
1411bool
1412Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1413{
Greg Clayton5160ce52013-03-27 23:08:40 +00001414 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415
1416 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001417 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1418 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419
1420 if (control_only)
1421 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1422 else
1423 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1424}
1425
1426bool
1427Process::IsRunning () const
1428{
1429 return StateIsRunningState (m_public_state.GetValue());
1430}
1431
1432int
1433Process::GetExitStatus ()
1434{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001435 Mutex::Locker locker (m_exit_status_mutex);
1436
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 if (m_public_state.GetValue() == eStateExited)
1438 return m_exit_status;
1439 return -1;
1440}
1441
Greg Clayton85851dd2010-12-04 00:10:17 +00001442
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001443const char *
1444Process::GetExitDescription ()
1445{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001446 Mutex::Locker locker (m_exit_status_mutex);
1447
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1449 return m_exit_string.c_str();
1450 return NULL;
1451}
1452
Greg Clayton6779606a2011-01-22 23:43:18 +00001453bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001454Process::SetExitStatus (int status, const char *cstr)
1455{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001456 // Use a mutex to protect setting the exit status.
1457 Mutex::Locker locker (m_exit_status_mutex);
1458
Greg Clayton5160ce52013-03-27 23:08:40 +00001459 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001460 if (log)
1461 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1462 status, status,
1463 cstr ? "\"" : "",
1464 cstr ? cstr : "NULL",
1465 cstr ? "\"" : "");
1466
Greg Clayton6779606a2011-01-22 23:43:18 +00001467 // We were already in the exited state
1468 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001469 {
Greg Clayton385d6032011-01-26 23:47:29 +00001470 if (log)
1471 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001472 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001473 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001474
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001475 m_exit_status = status;
1476 if (cstr)
1477 m_exit_string = cstr;
1478 else
1479 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480
Greg Clayton5df78fa2015-05-23 03:54:53 +00001481 // When we exit, we no longer need to the communication channel
Greg Clayton5df78fa2015-05-23 03:54:53 +00001482 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00001483 m_stdio_communication.StopReadThread();
Greg Clayton5df78fa2015-05-23 03:54:53 +00001484 m_stdin_forward = false;
1485
1486 // And we don't need the input reader anymore as well
1487 if (m_process_input_reader)
1488 {
1489 m_process_input_reader->SetIsDone(true);
1490 m_process_input_reader->Cancel();
1491 m_process_input_reader.reset();
1492 }
Greg Clayton10177aa2010-12-08 05:08:21 +00001493
Greg Clayton08765fa2015-05-28 03:24:30 +00001494 // Clear the last natural stop ID since it has a strong
1495 // reference to this process
1496 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1497
Greg Clayton6779606a2011-01-22 23:43:18 +00001498 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001499
1500 // Allow subclasses to do some cleanup
1501 DidExit ();
1502
Greg Clayton6779606a2011-01-22 23:43:18 +00001503 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504}
1505
1506// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001507// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508// found in the global target list (we want to be completely sure that the
1509// lldb_private::Process doesn't go away before we can deliver the signal.
1510bool
Greg Claytone4e45922011-11-16 05:37:56 +00001511Process::SetProcessExitStatus (void *callback_baton,
1512 lldb::pid_t pid,
1513 bool exited,
1514 int signo, // Zero for no signal
1515 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001516)
1517{
Greg Clayton5160ce52013-03-27 23:08:40 +00001518 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001519 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001520 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001521 callback_baton,
1522 pid,
1523 exited,
1524 signo,
1525 exit_status);
1526
1527 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001528 {
Greg Clayton66111032010-06-23 01:19:29 +00001529 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530 if (target_sp)
1531 {
1532 ProcessSP process_sp (target_sp->GetProcessSP());
1533 if (process_sp)
1534 {
1535 const char *signal_cstr = NULL;
1536 if (signo)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001537 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001538
1539 process_sp->SetExitStatus (exit_status, signal_cstr);
1540 }
1541 }
1542 return true;
1543 }
1544 return false;
1545}
1546
1547
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001548void
1549Process::UpdateThreadListIfNeeded ()
1550{
1551 const uint32_t stop_id = GetStopID();
1552 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1553 {
Greg Clayton2637f822011-11-17 01:23:07 +00001554 const StateType state = GetPrivateState();
1555 if (StateIsStoppedState (state, true))
1556 {
1557 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001558 // m_thread_list does have its own mutex, but we need to
1559 // hold onto the mutex between the call to UpdateThreadList(...)
1560 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001561 ThreadList &old_thread_list = m_thread_list;
1562 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001563 ThreadList new_thread_list(this);
1564 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001565 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001566 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001567 {
Jim Ingham09437922013-03-01 20:04:25 +00001568 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1569 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1570 // shutting us down, causing a deadlock.
1571 if (!m_destroy_in_process)
1572 {
1573 OperatingSystem *os = GetOperatingSystem ();
1574 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001575 {
1576 // Clear any old backing threads where memory threads might have been
1577 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001578 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001579 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001580 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001581
Greg Clayton15484402015-05-15 18:40:24 +00001582 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1583 // can run an expression to determine if a SBValue is a dynamic type or not
1584 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1585 // that require running code...
1586
1587 Target &target = GetTarget();
1588 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1589 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1590 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1591
Greg Claytonb3ae8762013-04-12 20:07:46 +00001592 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001593
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001594 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1595 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1596 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 +00001597
1598 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1599 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001600 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001601 else
1602 {
1603 // No OS plug-in, the new thread list is the same as the real thread list
1604 new_thread_list = real_thread_list;
1605 }
Jim Ingham09437922013-03-01 20:04:25 +00001606 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001607
1608 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001609 m_thread_list.Update (new_thread_list);
1610 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001611
Jason Molenda4ff13262013-11-20 00:31:38 +00001612 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1613 {
1614 // Clear any extended threads that we may have accumulated previously
1615 m_extended_thread_list.Clear();
1616 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001617
1618 m_queue_list.Clear();
1619 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001620 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001621 }
Greg Clayton2637f822011-11-17 01:23:07 +00001622 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001623 }
1624}
1625
Jason Molenda5e8dce42013-12-13 00:29:16 +00001626void
1627Process::UpdateQueueListIfNeeded ()
1628{
1629 if (m_system_runtime_ap.get())
1630 {
1631 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1632 {
1633 const StateType state = GetPrivateState();
1634 if (StateIsStoppedState (state, true))
1635 {
1636 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1637 m_queue_list_stop_id = GetLastNaturalStopID();
1638 }
1639 }
1640 }
1641}
1642
Greg Claytona4d87472013-01-18 23:41:08 +00001643ThreadSP
1644Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1645{
1646 OperatingSystem *os = GetOperatingSystem ();
1647 if (os)
1648 return os->CreateThread(tid, context);
1649 return ThreadSP();
1650}
1651
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001652uint32_t
1653Process::GetNextThreadIndexID (uint64_t thread_id)
1654{
1655 return AssignIndexIDToThread(thread_id);
1656}
1657
1658bool
1659Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1660{
1661 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1662 if (iterator == m_thread_id_to_index_id_map.end())
1663 {
1664 return false;
1665 }
1666 else
1667 {
1668 return true;
1669 }
1670}
1671
1672uint32_t
1673Process::AssignIndexIDToThread(uint64_t thread_id)
1674{
1675 uint32_t result = 0;
1676 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1677 if (iterator == m_thread_id_to_index_id_map.end())
1678 {
1679 result = ++m_thread_index_id;
1680 m_thread_id_to_index_id_map[thread_id] = result;
1681 }
1682 else
1683 {
1684 result = iterator->second;
1685 }
1686
1687 return result;
1688}
1689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001690StateType
1691Process::GetState()
1692{
1693 // If any other threads access this we will need a mutex for it
1694 return m_public_state.GetValue ();
1695}
1696
Greg Claytondc6224e2014-10-21 01:00:42 +00001697bool
1698Process::StateChangedIsExternallyHijacked()
1699{
1700 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1701 {
1702 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1703 return true;
1704 }
1705 return false;
1706}
1707
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001708void
Jim Ingham221d51c2013-05-08 00:35:16 +00001709Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710{
Greg Clayton5160ce52013-03-27 23:08:40 +00001711 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001712 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001713 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001714 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001716
1717 // On the transition from Run to Stopped, we unlock the writer end of the
1718 // run lock. The lock gets locked in Resume, which is the public API
1719 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001720 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001721 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001722 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001723 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001724 if (log)
1725 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001726 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001727 }
1728 else
1729 {
1730 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1731 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001732 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001733 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001734 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001735 {
1736 if (log)
1737 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001738 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001739 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001740 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001741 }
1742 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001743}
1744
Jim Ingham3b8285d2012-04-19 01:40:33 +00001745Error
1746Process::Resume ()
1747{
Greg Clayton5160ce52013-03-27 23:08:40 +00001748 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001749 if (log)
1750 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001751 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001752 {
1753 Error error("Resume request failed - process still running.");
1754 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001755 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001756 return error;
1757 }
1758 return PrivateResume();
1759}
1760
Greg Claytondc6224e2014-10-21 01:00:42 +00001761Error
1762Process::ResumeSynchronous (Stream *stream)
1763{
1764 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1765 if (log)
1766 log->Printf("Process::ResumeSynchronous -- locking run lock");
1767 if (!m_public_run_lock.TrySetRunning())
1768 {
1769 Error error("Resume request failed - process still running.");
1770 if (log)
1771 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1772 return error;
1773 }
1774
1775 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1776 HijackProcessEvents(listener_sp.get());
1777
1778 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001779 if (error.Success())
1780 {
1781 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1782 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1783 if (!StateIsStoppedState(state, must_be_alive))
1784 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1785 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001786
1787 // Undo the hijacking of process events...
1788 RestoreProcessEvents();
1789
Greg Claytondc6224e2014-10-21 01:00:42 +00001790 return error;
1791}
1792
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793StateType
1794Process::GetPrivateState ()
1795{
1796 return m_private_state.GetValue();
1797}
1798
1799void
1800Process::SetPrivateState (StateType new_state)
1801{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001802 if (m_finalize_called)
1803 return;
1804
Greg Clayton5160ce52013-03-27 23:08:40 +00001805 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 bool state_changed = false;
1807
1808 if (log)
1809 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1810
Andrew Kaylor29d65742013-05-10 17:19:04 +00001811 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812 Mutex::Locker locker(m_private_state.GetMutex());
1813
1814 const StateType old_state = m_private_state.GetValueNoLock ();
1815 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001816
Greg Claytonaa49c832013-05-03 22:25:56 +00001817 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1818 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1819 if (old_state_is_stopped != new_state_is_stopped)
1820 {
1821 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001822 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001823 else
Ed Maste64fad602013-07-29 20:58:06 +00001824 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001825 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001826
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001827 if (state_changed)
1828 {
1829 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001830 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001831 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001833 // Note, this currently assumes that all threads in the list
1834 // stop when the process stops. In the future we will want to
1835 // support a debugging model where some threads continue to run
1836 // while others are stopped. When that happens we will either need
1837 // a way for the thread list to identify which threads are stopping
1838 // or create a special thread list containing only threads which
1839 // actually stopped.
1840 //
1841 // The process plugin is responsible for managing the actual
1842 // behavior of the threads and should have stopped any threads
1843 // that are going to stop before we get here.
1844 m_thread_list.DidStop();
1845
Jim Ingham4b536182011-08-09 02:12:22 +00001846 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001847 if (!m_mod_id.IsLastResumeForUserExpression())
1848 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001849 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001851 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001852 }
Ilia K38810f42015-05-20 10:15:47 +00001853
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001854 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001855 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:47 +00001856 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001857 else
Ilia K38810f42015-05-20 10:15:47 +00001858 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001859 }
1860 else
1861 {
1862 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001863 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 }
1865}
1866
Jim Ingham0faa43f2011-11-08 03:00:11 +00001867void
1868Process::SetRunningUserExpression (bool on)
1869{
1870 m_mod_id.SetRunningUserExpression (on);
1871}
1872
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873addr_t
1874Process::GetImageInfoAddress()
1875{
1876 return LLDB_INVALID_ADDRESS;
1877}
1878
Greg Clayton8f343b02010-11-04 01:54:29 +00001879//----------------------------------------------------------------------
1880// LoadImage
1881//
1882// This function provides a default implementation that works for most
1883// unix variants. Any Process subclasses that need to do shared library
1884// loading differently should override LoadImage and UnloadImage and
1885// do what is needed.
1886//----------------------------------------------------------------------
1887uint32_t
1888Process::LoadImage (const FileSpec &image_spec, Error &error)
1889{
Greg Claytonc00ca312015-04-02 18:44:58 +00001890 if (m_finalizing)
1891 {
1892 error.SetErrorString("process is tearing itself down");
1893 return LLDB_INVALID_IMAGE_TOKEN;
1894 }
1895
Greg Claytonac7a3db2012-04-18 00:05:19 +00001896 char path[PATH_MAX];
1897 image_spec.GetPath(path, sizeof(path));
1898
Greg Clayton8f343b02010-11-04 01:54:29 +00001899 DynamicLoader *loader = GetDynamicLoader();
1900 if (loader)
1901 {
1902 error = loader->CanLoadImage();
1903 if (error.Fail())
1904 return LLDB_INVALID_IMAGE_TOKEN;
1905 }
1906
1907 if (error.Success())
1908 {
1909 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001910
1911 if (thread_sp)
1912 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001913 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001914
1915 if (frame_sp)
1916 {
1917 ExecutionContext exe_ctx;
1918 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001919 EvaluateExpressionOptions expr_options;
1920 expr_options.SetUnwindOnError(true);
1921 expr_options.SetIgnoreBreakpoints(true);
1922 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001923 expr_options.SetResultIsInternal(true);
1924
Greg Clayton8f343b02010-11-04 01:54:29 +00001925 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001926 expr.Printf(R"(
1927 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1928 the_result.image_ptr = dlopen ("%s", 2);
1929 if (the_result.image_ptr == (void *) 0x0)
1930 {
1931 the_result.error_str = dlerror();
1932 }
1933 else
1934 {
1935 the_result.error_str = (const char *) 0x0;
1936 }
1937 the_result;
1938 )",
1939 path);
1940 const char *prefix = R"(
1941 extern "C" void* dlopen (const char *path, int mode);
1942 extern "C" const char *dlerror (void);
1943 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001944 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001945 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001946 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001947 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001948 expr.GetData(),
1949 prefix,
1950 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001951 expr_error);
1952 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001953 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001954 error = result_valobj_sp->GetError();
1955 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001956 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001957 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001958 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1959 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001960 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001961 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1962 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1963 {
1964 uint32_t image_token = m_image_tokens.size();
1965 m_image_tokens.push_back (image_ptr);
1966 return image_token;
1967 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001968 else if (image_ptr == 0)
1969 {
Jim Ingham6971b862014-07-19 00:37:06 +00001970 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1971 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001972 {
Jim Ingham6971b862014-07-19 00:37:06 +00001973 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001974 {
Enrico Granata2206b482014-10-30 18:27:31 +00001975 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1976 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001977 if (error.Success() && num_chars > 0)
1978 {
1979 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001980 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1981 }
1982 else
1983 {
1984 error.Clear();
1985 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001986 }
1987 }
1988 }
1989 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001990 }
1991 }
1992 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001993 else
1994 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001995 }
1996 }
1997 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001998 if (!error.AsCString())
1999 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00002000 return LLDB_INVALID_IMAGE_TOKEN;
2001}
2002
2003//----------------------------------------------------------------------
2004// UnloadImage
2005//
2006// This function provides a default implementation that works for most
2007// unix variants. Any Process subclasses that need to do shared library
2008// loading differently should override LoadImage and UnloadImage and
2009// do what is needed.
2010//----------------------------------------------------------------------
2011Error
2012Process::UnloadImage (uint32_t image_token)
2013{
2014 Error error;
Greg Claytonc00ca312015-04-02 18:44:58 +00002015
2016 if (m_finalizing)
2017 {
2018 error.SetErrorString("process is tearing itself down");
2019 return error;
2020 }
2021
Greg Clayton8f343b02010-11-04 01:54:29 +00002022 if (image_token < m_image_tokens.size())
2023 {
2024 const addr_t image_addr = m_image_tokens[image_token];
2025 if (image_addr == LLDB_INVALID_ADDRESS)
2026 {
2027 error.SetErrorString("image already unloaded");
2028 }
2029 else
2030 {
2031 DynamicLoader *loader = GetDynamicLoader();
2032 if (loader)
2033 error = loader->CanLoadImage();
2034
2035 if (error.Success())
2036 {
2037 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00002038
2039 if (thread_sp)
2040 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002041 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00002042
2043 if (frame_sp)
2044 {
2045 ExecutionContext exe_ctx;
2046 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00002047 EvaluateExpressionOptions expr_options;
2048 expr_options.SetUnwindOnError(true);
2049 expr_options.SetIgnoreBreakpoints(true);
2050 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00002051 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00002052 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00002053 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00002054 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00002055 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00002056 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002057 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00002058 expr.GetData(),
2059 prefix,
2060 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002061 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002062 if (result_valobj_sp->GetError().Success())
2063 {
2064 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002065 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002066 {
2067 if (scalar.UInt(1))
2068 {
2069 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2070 }
2071 else
2072 {
2073 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2074 }
2075 }
2076 }
2077 else
2078 {
2079 error = result_valobj_sp->GetError();
2080 }
2081 }
2082 }
2083 }
2084 }
2085 }
2086 else
2087 {
2088 error.SetErrorString("invalid image token");
2089 }
2090 return error;
2091}
2092
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002093const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002094Process::GetABI()
2095{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002096 if (!m_abi_sp)
2097 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2098 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002099}
2100
Jim Ingham22777012010-09-23 02:01:19 +00002101LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002102Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002103{
Greg Claytonc00ca312015-04-02 18:44:58 +00002104 if (m_finalizing)
2105 return nullptr;
2106
Jim Ingham22777012010-09-23 02:01:19 +00002107 LanguageRuntimeCollection::iterator pos;
2108 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002109 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002110 {
Jim Inghamab175242012-03-10 00:22:19 +00002111 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002112
Jim Inghamab175242012-03-10 00:22:19 +00002113 m_language_runtimes[language] = runtime_sp;
2114 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002115 }
2116 else
2117 return (*pos).second.get();
2118}
2119
2120CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002121Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002122{
Jim Inghamab175242012-03-10 00:22:19 +00002123 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002124 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2125 return static_cast<CPPLanguageRuntime *> (runtime);
2126 return NULL;
2127}
2128
2129ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002130Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002131{
Jim Inghamab175242012-03-10 00:22:19 +00002132 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002133 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2134 return static_cast<ObjCLanguageRuntime *> (runtime);
2135 return NULL;
2136}
2137
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002138bool
2139Process::IsPossibleDynamicValue (ValueObject& in_value)
2140{
Greg Claytonc00ca312015-04-02 18:44:58 +00002141 if (m_finalizing)
2142 return false;
2143
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002144 if (in_value.IsDynamic())
2145 return false;
2146 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2147
2148 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2149 {
2150 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2151 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2152 }
2153
2154 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2155 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2156 return true;
2157
2158 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2159 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2160}
2161
Zachary Turner93749ab2015-03-03 21:51:25 +00002162void
2163Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2164{
2165 m_dynamic_checkers_ap.reset(dynamic_checkers);
2166}
2167
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168BreakpointSiteList &
2169Process::GetBreakpointSiteList()
2170{
2171 return m_breakpoint_site_list;
2172}
2173
2174const BreakpointSiteList &
2175Process::GetBreakpointSiteList() const
2176{
2177 return m_breakpoint_site_list;
2178}
2179
2180
2181void
2182Process::DisableAllBreakpointSites ()
2183{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002184 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2185// bp_site->SetEnabled(true);
2186 DisableBreakpointSite(bp_site);
2187 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002188}
2189
2190Error
2191Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2192{
2193 Error error (DisableBreakpointSiteByID (break_id));
2194
2195 if (error.Success())
2196 m_breakpoint_site_list.Remove(break_id);
2197
2198 return error;
2199}
2200
2201Error
2202Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2203{
2204 Error error;
2205 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2206 if (bp_site_sp)
2207 {
2208 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002209 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002210 }
2211 else
2212 {
Daniel Malead01b2952012-11-29 21:49:15 +00002213 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214 }
2215
2216 return error;
2217}
2218
2219Error
2220Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2221{
2222 Error error;
2223 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2224 if (bp_site_sp)
2225 {
2226 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002227 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002228 }
2229 else
2230 {
Daniel Malead01b2952012-11-29 21:49:15 +00002231 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232 }
2233 return error;
2234}
2235
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002236lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002237Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002239 addr_t load_addr = LLDB_INVALID_ADDRESS;
2240
2241 bool show_error = true;
2242 switch (GetState())
2243 {
2244 case eStateInvalid:
2245 case eStateUnloaded:
2246 case eStateConnected:
2247 case eStateAttaching:
2248 case eStateLaunching:
2249 case eStateDetached:
2250 case eStateExited:
2251 show_error = false;
2252 break;
2253
2254 case eStateStopped:
2255 case eStateRunning:
2256 case eStateStepping:
2257 case eStateCrashed:
2258 case eStateSuspended:
2259 show_error = IsAlive();
2260 break;
2261 }
2262
2263 // Reset the IsIndirect flag here, in case the location changes from
2264 // pointing to a indirect symbol to a regular symbol.
2265 owner->SetIsIndirect (false);
2266
2267 if (owner->ShouldResolveIndirectFunctions())
2268 {
2269 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2270 if (symbol && symbol->IsIndirect())
2271 {
2272 Error error;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002273 Address symbol_address = symbol->GetAddress();
2274 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:59 +00002275 if (!error.Success() && show_error)
2276 {
Greg Clayton44d93782014-01-27 23:43:24 +00002277 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
Greg Clayton358cf1e2015-06-25 21:46:34 +00002278 symbol->GetLoadAddress(&m_target),
Greg Clayton44d93782014-01-27 23:43:24 +00002279 owner->GetBreakpoint().GetID(),
2280 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002281 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002282 return LLDB_INVALID_BREAK_ID;
2283 }
2284 Address resolved_address(load_addr);
2285 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2286 owner->SetIsIndirect(true);
2287 }
2288 else
2289 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2290 }
2291 else
2292 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2293
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002294 if (load_addr != LLDB_INVALID_ADDRESS)
2295 {
2296 BreakpointSiteSP bp_site_sp;
2297
2298 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2299 // create a new breakpoint site and add it.
2300
2301 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2302
2303 if (bp_site_sp)
2304 {
2305 bp_site_sp->AddOwner (owner);
2306 owner->SetBreakpointSite (bp_site_sp);
2307 return bp_site_sp->GetID();
2308 }
2309 else
2310 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002311 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 if (bp_site_sp)
2313 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002314 Error error = EnableBreakpointSite (bp_site_sp.get());
2315 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002316 {
2317 owner->SetBreakpointSite (bp_site_sp);
2318 return m_breakpoint_site_list.Add (bp_site_sp);
2319 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002320 else
2321 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002322 if (show_error)
2323 {
2324 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002325 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2326 load_addr,
2327 owner->GetBreakpoint().GetID(),
2328 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002329 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002330 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002331 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332 }
2333 }
2334 }
2335 // We failed to enable the breakpoint
2336 return LLDB_INVALID_BREAK_ID;
2337
2338}
2339
2340void
2341Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2342{
2343 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2344 if (num_owners == 0)
2345 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002346 // Don't try to disable the site if we don't have a live process anymore.
2347 if (IsAlive())
2348 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2350 }
2351}
2352
2353
2354size_t
2355Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2356{
2357 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002358 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002359
Jim Ingham20c77192011-06-29 19:42:28 +00002360 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002362 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2363 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002364 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002365 addr_t intersect_addr;
2366 size_t intersect_size;
2367 size_t opcode_offset;
2368 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002369 {
2370 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2371 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002372 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002373 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002374 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002375 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002377 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378 }
2379 return bytes_removed;
2380}
2381
2382
Greg Claytonded470d2011-03-19 01:12:21 +00002383
2384size_t
2385Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2386{
2387 PlatformSP platform_sp (m_target.GetPlatform());
2388 if (platform_sp)
2389 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2390 return 0;
2391}
2392
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393Error
2394Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2395{
2396 Error error;
2397 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002398 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399 const addr_t bp_addr = bp_site->GetLoadAddress();
2400 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002401 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402 if (bp_site->IsEnabled())
2403 {
2404 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002405 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 +00002406 return error;
2407 }
2408
2409 if (bp_addr == LLDB_INVALID_ADDRESS)
2410 {
2411 error.SetErrorString("BreakpointSite contains an invalid load address.");
2412 return error;
2413 }
2414 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2415 // trap for the breakpoint site
2416 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2417
2418 if (bp_opcode_size == 0)
2419 {
Daniel Malead01b2952012-11-29 21:49:15 +00002420 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002421 }
2422 else
2423 {
2424 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2425
2426 if (bp_opcode_bytes == NULL)
2427 {
2428 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2429 return error;
2430 }
2431
2432 // Save the original opcode by reading it
2433 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2434 {
2435 // Write a software breakpoint in place of the original opcode
2436 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2437 {
2438 uint8_t verify_bp_opcode_bytes[64];
2439 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2440 {
2441 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2442 {
2443 bp_site->SetEnabled(true);
2444 bp_site->SetType (BreakpointSite::eSoftware);
2445 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002446 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002447 bp_site->GetID(),
2448 (uint64_t)bp_addr);
2449 }
2450 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002451 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452 }
2453 else
2454 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2455 }
2456 else
2457 error.SetErrorString("Unable to write breakpoint trap to memory.");
2458 }
2459 else
2460 error.SetErrorString("Unable to read memory at breakpoint address.");
2461 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002462 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002463 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002464 bp_site->GetID(),
2465 (uint64_t)bp_addr,
2466 error.AsCString());
2467 return error;
2468}
2469
2470Error
2471Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2472{
2473 Error error;
2474 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002475 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 addr_t bp_addr = bp_site->GetLoadAddress();
2477 lldb::user_id_t breakID = bp_site->GetID();
2478 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002479 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480
2481 if (bp_site->IsHardware())
2482 {
2483 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2484 }
2485 else if (bp_site->IsEnabled())
2486 {
2487 const size_t break_op_size = bp_site->GetByteSize();
2488 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2489 if (break_op_size > 0)
2490 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002491 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002492 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002493 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002494 bool break_op_found = false;
2495
2496 // Read the breakpoint opcode
2497 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2498 {
2499 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002500 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2502 {
2503 break_op_found = true;
2504 // We found a valid breakpoint opcode at this address, now restore
2505 // the saved opcode.
2506 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2507 {
2508 verify = true;
2509 }
2510 else
2511 error.SetErrorString("Memory write failed when restoring original opcode.");
2512 }
2513 else
2514 {
2515 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2516 // Set verify to true and so we can check if the original opcode has already been restored
2517 verify = true;
2518 }
2519
2520 if (verify)
2521 {
Greg Claytonc982c762010-07-09 20:39:50 +00002522 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002523 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002524 // Verify that our original opcode made it back to the inferior
2525 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2526 {
2527 // compare the memory we just read with the original opcode
2528 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2529 {
2530 // SUCCESS
2531 bp_site->SetEnabled(false);
2532 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002533 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 +00002534 return error;
2535 }
2536 else
2537 {
2538 if (break_op_found)
2539 error.SetErrorString("Failed to restore original opcode.");
2540 }
2541 }
2542 else
2543 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2544 }
2545 }
2546 else
2547 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2548 }
2549 }
2550 else
2551 {
2552 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002553 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 +00002554 return error;
2555 }
2556
2557 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002558 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559 bp_site->GetID(),
2560 (uint64_t)bp_addr,
2561 error.AsCString());
2562 return error;
2563
2564}
2565
Greg Clayton58be07b2011-01-07 06:08:19 +00002566// Uncomment to verify memory caching works after making changes to caching code
2567//#define VERIFY_MEMORY_READS
2568
Sean Callanan64c0cf22012-06-07 22:26:42 +00002569size_t
2570Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2571{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002572 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002573 if (!GetDisableMemoryCache())
2574 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002575#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002576 // Memory caching is enabled, with debug verification
2577
2578 if (buf && size)
2579 {
2580 // Uncomment the line below to make sure memory caching is working.
2581 // I ran this through the test suite and got no assertions, so I am
2582 // pretty confident this is working well. If any changes are made to
2583 // memory caching, uncomment the line below and test your changes!
2584
2585 // Verify all memory reads by using the cache first, then redundantly
2586 // reading the same memory from the inferior and comparing to make sure
2587 // everything is exactly the same.
2588 std::string verify_buf (size, '\0');
2589 assert (verify_buf.size() == size);
2590 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2591 Error verify_error;
2592 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2593 assert (cache_bytes_read == verify_bytes_read);
2594 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2595 assert (verify_error.Success() == error.Success());
2596 return cache_bytes_read;
2597 }
2598 return 0;
2599#else // !defined(VERIFY_MEMORY_READS)
2600 // Memory caching is enabled, without debug verification
2601
2602 return m_memory_cache.Read (addr, buf, size, error);
2603#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002604 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002605 else
2606 {
2607 // Memory caching is disabled
2608
2609 return ReadMemoryFromInferior (addr, buf, size, error);
2610 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002611}
Greg Clayton58be07b2011-01-07 06:08:19 +00002612
Greg Clayton4c82d422012-05-18 23:20:01 +00002613size_t
2614Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2615{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002616 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002617 out_str.clear();
2618 addr_t curr_addr = addr;
2619 while (1)
2620 {
2621 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2622 if (length == 0)
2623 break;
2624 out_str.append(buf, length);
2625 // If we got "length - 1" bytes, we didn't get the whole C string, we
2626 // need to read some more characters
2627 if (length == sizeof(buf) - 1)
2628 curr_addr += length;
2629 else
2630 break;
2631 }
2632 return out_str.size();
2633}
2634
Greg Clayton58be07b2011-01-07 06:08:19 +00002635
2636size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002637Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2638 size_t type_width)
2639{
2640 size_t total_bytes_read = 0;
2641 if (dst && max_bytes && type_width && max_bytes >= type_width)
2642 {
2643 // Ensure a null terminator independent of the number of bytes that is read.
2644 memset (dst, 0, max_bytes);
2645 size_t bytes_left = max_bytes - type_width;
2646
2647 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2648 assert(sizeof(terminator) >= type_width &&
2649 "Attempting to validate a string with more than 4 bytes per character!");
2650
2651 addr_t curr_addr = addr;
2652 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2653 char *curr_dst = dst;
2654
2655 error.Clear();
2656 while (bytes_left > 0 && error.Success())
2657 {
2658 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2659 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2660 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2661
2662 if (bytes_read == 0)
2663 break;
2664
2665 // Search for a null terminator of correct size and alignment in bytes_read
2666 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2667 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2668 if (::strncmp(&dst[i], terminator, type_width) == 0)
2669 {
2670 error.Clear();
2671 return i;
2672 }
2673
2674 total_bytes_read += bytes_read;
2675 curr_dst += bytes_read;
2676 curr_addr += bytes_read;
2677 bytes_left -= bytes_read;
2678 }
2679 }
2680 else
2681 {
2682 if (max_bytes)
2683 error.SetErrorString("invalid arguments");
2684 }
2685 return total_bytes_read;
2686}
2687
2688// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2689// null terminators.
2690size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002691Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002692{
2693 size_t total_cstr_len = 0;
2694 if (dst && dst_max_len)
2695 {
Greg Claytone91b7952011-12-15 03:14:23 +00002696 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002697 // NULL out everything just to be safe
2698 memset (dst, 0, dst_max_len);
2699 Error error;
2700 addr_t curr_addr = addr;
2701 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2702 size_t bytes_left = dst_max_len - 1;
2703 char *curr_dst = dst;
2704
2705 while (bytes_left > 0)
2706 {
2707 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2708 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2709 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2710
2711 if (bytes_read == 0)
2712 {
Greg Claytone91b7952011-12-15 03:14:23 +00002713 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002714 dst[total_cstr_len] = '\0';
2715 break;
2716 }
2717 const size_t len = strlen(curr_dst);
2718
2719 total_cstr_len += len;
2720
2721 if (len < bytes_to_read)
2722 break;
2723
2724 curr_dst += bytes_read;
2725 curr_addr += bytes_read;
2726 bytes_left -= bytes_read;
2727 }
2728 }
Greg Claytone91b7952011-12-15 03:14:23 +00002729 else
2730 {
2731 if (dst == NULL)
2732 result_error.SetErrorString("invalid arguments");
2733 else
2734 result_error.Clear();
2735 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002736 return total_cstr_len;
2737}
2738
2739size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002740Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2741{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002742 if (buf == NULL || size == 0)
2743 return 0;
2744
2745 size_t bytes_read = 0;
2746 uint8_t *bytes = (uint8_t *)buf;
2747
2748 while (bytes_read < size)
2749 {
2750 const size_t curr_size = size - bytes_read;
2751 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2752 bytes + bytes_read,
2753 curr_size,
2754 error);
2755 bytes_read += curr_bytes_read;
2756 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2757 break;
2758 }
2759
2760 // Replace any software breakpoint opcodes that fall into this range back
2761 // into "buf" before we return
2762 if (bytes_read > 0)
2763 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2764 return bytes_read;
2765}
2766
Greg Clayton58a4c462010-12-16 20:01:20 +00002767uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002768Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002769{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002770 Scalar scalar;
2771 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2772 return scalar.ULongLong(fail_value);
2773 return fail_value;
2774}
2775
2776addr_t
2777Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2778{
2779 Scalar scalar;
2780 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2781 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2782 return LLDB_INVALID_ADDRESS;
2783}
2784
2785
2786bool
2787Process::WritePointerToMemory (lldb::addr_t vm_addr,
2788 lldb::addr_t ptr_value,
2789 Error &error)
2790{
2791 Scalar scalar;
2792 const uint32_t addr_byte_size = GetAddressByteSize();
2793 if (addr_byte_size <= 4)
2794 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002795 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002796 scalar = ptr_value;
2797 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002798}
2799
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800size_t
2801Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2802{
2803 size_t bytes_written = 0;
2804 const uint8_t *bytes = (const uint8_t *)buf;
2805
2806 while (bytes_written < size)
2807 {
2808 const size_t curr_size = size - bytes_written;
2809 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2810 bytes + bytes_written,
2811 curr_size,
2812 error);
2813 bytes_written += curr_bytes_written;
2814 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2815 break;
2816 }
2817 return bytes_written;
2818}
2819
2820size_t
2821Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2822{
Greg Clayton58be07b2011-01-07 06:08:19 +00002823#if defined (ENABLE_MEMORY_CACHING)
2824 m_memory_cache.Flush (addr, size);
2825#endif
2826
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002827 if (buf == NULL || size == 0)
2828 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002829
Jim Ingham4b536182011-08-09 02:12:22 +00002830 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002831
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002832 // We need to write any data that would go where any current software traps
2833 // (enabled software breakpoints) any software traps (breakpoints) that we
2834 // may have placed in our tasks memory.
2835
Greg Claytond8cf1a12013-06-12 00:46:38 +00002836 BreakpointSiteList bp_sites_in_range;
2837
2838 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002840 // No breakpoint sites overlap
2841 if (bp_sites_in_range.IsEmpty())
2842 return WriteMemoryPrivate (addr, buf, size, error);
2843 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002844 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002845 const uint8_t *ubuf = (const uint8_t *)buf;
2846 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002847
Greg Claytond8cf1a12013-06-12 00:46:38 +00002848 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2849
2850 if (error.Success())
2851 {
2852 addr_t intersect_addr;
2853 size_t intersect_size;
2854 size_t opcode_offset;
2855 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
Bruce Mitchener8a67bf72015-07-24 00:23:29 +00002856 UNUSED_IF_ASSERT_DISABLED(intersects);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002857 assert(intersects);
2858 assert(addr <= intersect_addr && intersect_addr < addr + size);
2859 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2860 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2861
2862 // Check for bytes before this breakpoint
2863 const addr_t curr_addr = addr + bytes_written;
2864 if (intersect_addr > curr_addr)
2865 {
2866 // There are some bytes before this breakpoint that we need to
2867 // just write to memory
2868 size_t curr_size = intersect_addr - curr_addr;
2869 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2870 ubuf + bytes_written,
2871 curr_size,
2872 error);
2873 bytes_written += curr_bytes_written;
2874 if (curr_bytes_written != curr_size)
2875 {
2876 // We weren't able to write all of the requested bytes, we
2877 // are done looping and will return the number of bytes that
2878 // we have written so far.
2879 if (error.Success())
2880 error.SetErrorToGenericError();
2881 }
2882 }
2883 // Now write any bytes that would cover up any software breakpoints
2884 // directly into the breakpoint opcode buffer
2885 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2886 bytes_written += intersect_size;
2887 }
2888 });
2889
2890 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002891 WriteMemoryPrivate (addr + bytes_written,
2892 ubuf + bytes_written,
2893 size - bytes_written,
2894 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002895 }
2896 }
2897 else
2898 {
2899 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900 }
2901
2902 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002903 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002905
2906size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002907Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002908{
2909 if (byte_size == UINT32_MAX)
2910 byte_size = scalar.GetByteSize();
2911 if (byte_size > 0)
2912 {
2913 uint8_t buf[32];
2914 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2915 if (mem_size > 0)
2916 return WriteMemory(addr, buf, mem_size, error);
2917 else
2918 error.SetErrorString ("failed to get scalar as memory data");
2919 }
2920 else
2921 {
2922 error.SetErrorString ("invalid scalar value");
2923 }
2924 return 0;
2925}
2926
2927size_t
2928Process::ReadScalarIntegerFromMemory (addr_t addr,
2929 uint32_t byte_size,
2930 bool is_signed,
2931 Scalar &scalar,
2932 Error &error)
2933{
Greg Clayton7060f892013-05-01 23:41:30 +00002934 uint64_t uval = 0;
2935 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002936 {
Greg Clayton7060f892013-05-01 23:41:30 +00002937 error.SetErrorString ("byte size is zero");
2938 }
2939 else if (byte_size & (byte_size - 1))
2940 {
2941 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2942 }
2943 else if (byte_size <= sizeof(uval))
2944 {
2945 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002946 if (bytes_read == byte_size)
2947 {
2948 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002949 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002950 if (byte_size <= 4)
2951 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002952 else
Greg Clayton7060f892013-05-01 23:41:30 +00002953 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002954 if (is_signed)
2955 scalar.SignExtend(byte_size * 8);
2956 return bytes_read;
2957 }
2958 }
2959 else
2960 {
2961 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2962 }
2963 return 0;
2964}
2965
Greg Claytond495c532011-05-17 03:37:42 +00002966#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002967addr_t
2968Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2969{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002970 if (GetPrivateState() != eStateStopped)
2971 return LLDB_INVALID_ADDRESS;
2972
Greg Claytond495c532011-05-17 03:37:42 +00002973#if defined (USE_ALLOCATE_MEMORY_CACHE)
2974 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2975#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002976 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002977 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002978 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002979 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 +00002980 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002981 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002982 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002983 m_mod_id.GetStopID(),
2984 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002985 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002986#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002987}
2988
Sean Callanan90539452011-09-20 23:01:51 +00002989bool
2990Process::CanJIT ()
2991{
Sean Callanana7b443a2012-02-14 22:50:38 +00002992 if (m_can_jit == eCanJITDontKnow)
2993 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002994 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002995 Error err;
2996
2997 uint64_t allocated_memory = AllocateMemory(8,
2998 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2999 err);
3000
3001 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00003002 {
Sean Callanana7b443a2012-02-14 22:50:38 +00003003 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00003004 if (log)
3005 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
3006 }
Sean Callanana7b443a2012-02-14 22:50:38 +00003007 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003008 {
Sean Callanana7b443a2012-02-14 22:50:38 +00003009 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00003010 if (log)
3011 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
3012 }
Sean Callanana7b443a2012-02-14 22:50:38 +00003013
3014 DeallocateMemory (allocated_memory);
3015 }
3016
Sean Callanan90539452011-09-20 23:01:51 +00003017 return m_can_jit == eCanJITYes;
3018}
3019
3020void
3021Process::SetCanJIT (bool can_jit)
3022{
3023 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
3024}
3025
Ewan Crawford90ff7912015-07-14 10:56:58 +00003026void
3027Process::SetCanRunCode (bool can_run_code)
3028{
3029 SetCanJIT(can_run_code);
3030 m_can_interpret_function_calls = can_run_code;
3031}
3032
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033Error
3034Process::DeallocateMemory (addr_t ptr)
3035{
Greg Claytond495c532011-05-17 03:37:42 +00003036 Error error;
3037#if defined (USE_ALLOCATE_MEMORY_CACHE)
3038 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
3039 {
Daniel Malead01b2952012-11-29 21:49:15 +00003040 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00003041 }
3042#else
3043 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00003044
Greg Clayton5160ce52013-03-27 23:08:40 +00003045 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00003046 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003047 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 +00003048 ptr,
3049 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00003050 m_mod_id.GetStopID(),
3051 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00003052#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00003053 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054}
3055
Han Ming Ongc811d382012-11-17 00:33:14 +00003056
Greg Claytonc9660542012-02-05 02:38:54 +00003057ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00003058Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00003059 lldb::addr_t header_addr,
3060 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00003061{
Jason Molenda08a32582015-07-25 02:39:42 +00003062 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
3063 if (log)
3064 {
3065 log->Printf ("Process::ReadModuleFromMemory reading %s binary from memory", file_spec.GetPath().c_str());
3066 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003067 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00003068 if (module_sp)
3069 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003070 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00003071 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003072 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003073 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00003074 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003075 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00003076}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077
Zachary Turner93749ab2015-03-03 21:51:25 +00003078bool
3079Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3080{
3081 MemoryRegionInfo range_info;
3082 permissions = 0;
3083 Error error (GetMemoryRegionInfo (load_addr, range_info));
3084 if (!error.Success())
3085 return false;
3086 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3087 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3088 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3089 {
3090 return false;
3091 }
3092
3093 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3094 permissions |= lldb::ePermissionsReadable;
3095
3096 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3097 permissions |= lldb::ePermissionsWritable;
3098
3099 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3100 permissions |= lldb::ePermissionsExecutable;
3101
3102 return true;
3103}
3104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003105Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003106Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107{
3108 Error error;
3109 error.SetErrorString("watchpoints are not supported");
3110 return error;
3111}
3112
3113Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003114Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115{
3116 Error error;
3117 error.SetErrorString("watchpoints are not supported");
3118 return error;
3119}
3120
3121StateType
3122Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3123{
3124 StateType state;
3125 // Now wait for the process to launch and return control to us, and then
3126 // call DidLaunch:
3127 while (1)
3128 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003129 event_sp.reset();
3130 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3131
Greg Clayton2637f822011-11-17 01:23:07 +00003132 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003134
3135 // If state is invalid, then we timed out
3136 if (state == eStateInvalid)
3137 break;
3138
3139 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003140 HandlePrivateEvent (event_sp);
3141 }
3142 return state;
3143}
3144
Greg Clayton332e8b12015-01-13 21:13:08 +00003145void
3146Process::LoadOperatingSystemPlugin(bool flush)
3147{
3148 if (flush)
3149 m_thread_list.Clear();
3150 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3151 if (flush)
3152 Flush();
3153}
3154
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003156Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157{
3158 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003159 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003160 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003161 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003162 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003163 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003164 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003165 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166
Greg Claytonaa149cb2011-08-11 02:48:45 +00003167 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003168 if (exe_module)
3169 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003170 char local_exec_file_path[PATH_MAX];
3171 char platform_exec_file_path[PATH_MAX];
3172 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3173 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003174 if (exe_module->GetFileSpec().Exists())
3175 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003176 // Install anything that might need to be installed prior to launching.
3177 // For host systems, this will do nothing, but if we are connected to a
3178 // remote platform it will install any needed binaries
3179 error = GetTarget().Install(&launch_info);
3180 if (error.Fail())
3181 return error;
3182
Greg Clayton71337622011-02-24 22:24:29 +00003183 if (PrivateStateThreadIsValid ())
3184 PausePrivateStateThread ();
3185
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186 error = WillLaunch (exe_module);
3187 if (error.Success())
3188 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003189 const bool restarted = false;
3190 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003191 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192
Ed Maste64fad602013-07-29 20:58:06 +00003193 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003194 {
3195 // Now launch using these arguments.
3196 error = DoLaunch (exe_module, launch_info);
3197 }
3198 else
3199 {
3200 // This shouldn't happen
3201 error.SetErrorString("failed to acquire process run lock");
3202 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003203
3204 if (error.Fail())
3205 {
3206 if (GetID() != LLDB_INVALID_PROCESS_ID)
3207 {
3208 SetID (LLDB_INVALID_PROCESS_ID);
3209 const char *error_string = error.AsCString();
3210 if (error_string == NULL)
3211 error_string = "launch failed";
3212 SetExitStatus (-1, error_string);
3213 }
3214 }
3215 else
3216 {
3217 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003218 TimeValue timeout_time;
3219 timeout_time = TimeValue::Now();
3220 timeout_time.OffsetWithSeconds(10);
3221 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222
Greg Clayton1a38ea72011-06-22 01:42:17 +00003223 if (state == eStateInvalid || event_sp.get() == NULL)
3224 {
3225 // We were able to launch the process, but we failed to
3226 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003227 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003228 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003229 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003230 }
3231 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003232 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003233
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234 DidLaunch ();
3235
Greg Claytonc859e2d2012-02-13 23:10:39 +00003236 DynamicLoader *dyld = GetDynamicLoader ();
3237 if (dyld)
3238 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003239
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003240 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003241
Jason Molendaeef51062013-11-05 03:57:19 +00003242 SystemRuntime *system_runtime = GetSystemRuntime ();
3243 if (system_runtime)
3244 system_runtime->DidLaunch();
3245
Greg Clayton332e8b12015-01-13 21:13:08 +00003246 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003247
3248 // Note, the stop event was consumed above, but not handled. This was done
3249 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3250 // Directly set the state. This is done to prevent a stop message with a bunch
3251 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3252 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003253
3254 if (PrivateStateThreadIsValid ())
3255 ResumePrivateStateThread ();
3256 else
3257 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003258
3259 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003260
3261 // Target was stopped at entry as was intended. Need to notify the listeners
3262 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003263 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003264 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265 }
3266 else if (state == eStateExited)
3267 {
3268 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3269 // not likely to work, and return an invalid pid.
3270 HandlePrivateEvent (event_sp);
3271 }
3272 }
3273 }
3274 }
3275 else
3276 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003277 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003278 }
3279 }
3280 return error;
3281}
3282
Greg Claytonc3776bf2012-02-09 06:16:32 +00003283
3284Error
3285Process::LoadCore ()
3286{
3287 Error error = DoLoadCore();
3288 if (error.Success())
3289 {
Greg Clayton35824e32015-02-20 20:59:47 +00003290 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003291 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003292
Greg Claytonc3776bf2012-02-09 06:16:32 +00003293 if (PrivateStateThreadIsValid ())
3294 ResumePrivateStateThread ();
3295 else
3296 StartPrivateStateThread ();
3297
Greg Claytonc859e2d2012-02-13 23:10:39 +00003298 DynamicLoader *dyld = GetDynamicLoader ();
3299 if (dyld)
3300 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003301
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003302 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003303
Jason Molendaeef51062013-11-05 03:57:19 +00003304 SystemRuntime *system_runtime = GetSystemRuntime ();
3305 if (system_runtime)
3306 system_runtime->DidAttach();
3307
Greg Claytonc859e2d2012-02-13 23:10:39 +00003308 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003309 // We successfully loaded a core file, now pretend we stopped so we can
3310 // show all of the threads in the core file and explore the crashed
3311 // state.
3312 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003313
3314 // Wait indefinitely for a stopped event since we just posted one above...
3315 lldb::EventSP event_sp;
3316 listener.WaitForEvent (NULL, event_sp);
3317 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3318
3319 if (!StateIsStoppedState (state, false))
3320 {
3321 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3322 if (log)
3323 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3324 error.SetErrorString ("Did not get stopped event after loading the core file.");
3325 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003326 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003327 }
3328 return error;
3329}
3330
Greg Claytonc859e2d2012-02-13 23:10:39 +00003331DynamicLoader *
3332Process::GetDynamicLoader ()
3333{
3334 if (m_dyld_ap.get() == NULL)
3335 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3336 return m_dyld_ap.get();
3337}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003338
Todd Fialaaf245d12014-06-30 21:05:18 +00003339const lldb::DataBufferSP
3340Process::GetAuxvData()
3341{
3342 return DataBufferSP ();
3343}
3344
Andrew MacPherson17220c12014-03-05 10:12:43 +00003345JITLoaderList &
3346Process::GetJITLoaders ()
3347{
3348 if (!m_jit_loaders_ap)
3349 {
3350 m_jit_loaders_ap.reset(new JITLoaderList());
3351 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3352 }
3353 return *m_jit_loaders_ap;
3354}
3355
Jason Molendaeef51062013-11-05 03:57:19 +00003356SystemRuntime *
3357Process::GetSystemRuntime ()
3358{
3359 if (m_system_runtime_ap.get() == NULL)
3360 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3361 return m_system_runtime_ap.get();
3362}
3363
Todd Fiala76e0fc92014-08-27 22:58:26 +00003364Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3365 NextEventAction (process),
3366 m_exec_count (exec_count)
3367{
3368 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3369 if (log)
3370 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3371}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003372
Jim Inghambb3a2832011-01-29 01:49:25 +00003373Process::NextEventAction::EventActionResult
3374Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003375{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003376 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3377
Jim Inghambb3a2832011-01-29 01:49:25 +00003378 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003379 if (log)
3380 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3381
3382 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003383 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003384 case eStateAttaching:
3385 return eEventActionSuccess;
3386
Greg Clayton513c26c2011-01-29 07:10:55 +00003387 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003388 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003389 return eEventActionRetry;
3390
3391 case eStateStopped:
3392 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003393 {
3394 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003395 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003396 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003397 // We don't want these events to be reported, so go set the ShouldReportStop here:
3398 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3399
Greg Claytonc9ed4782011-11-12 02:10:56 +00003400 if (m_exec_count > 0)
3401 {
3402 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003403
3404 if (log)
3405 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3406
Jim Ingham221d51c2013-05-08 00:35:16 +00003407 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003408 return eEventActionRetry;
3409 }
3410 else
3411 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003412 if (log)
3413 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3414
Greg Claytonc9ed4782011-11-12 02:10:56 +00003415 m_process->CompleteAttach ();
3416 return eEventActionSuccess;
3417 }
3418 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003419 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003420
Greg Clayton513c26c2011-01-29 07:10:55 +00003421 default:
3422 case eStateExited:
3423 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003424 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003425 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003426
3427 m_exit_string.assign ("No valid Process");
3428 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003429}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430
Jim Inghambb3a2832011-01-29 01:49:25 +00003431Process::NextEventAction::EventActionResult
3432Process::AttachCompletionHandler::HandleBeingInterrupted()
3433{
3434 return eEventActionSuccess;
3435}
3436
3437const char *
3438Process::AttachCompletionHandler::GetExitString ()
3439{
3440 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003441}
3442
Greg Clayton8012cad2014-11-17 19:39:20 +00003443Listener &
3444ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3445{
3446 if (m_listener_sp)
3447 return *m_listener_sp;
3448 else
3449 return debugger.GetListener();
3450}
3451
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003453Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003455 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003456 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003457 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003458 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003459 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003460 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003461 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003462
Greg Clayton144f3a92011-11-15 03:53:30 +00003463 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003464 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003465 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003466 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003467 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003468
Greg Clayton144f3a92011-11-15 03:53:30 +00003469 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003470 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003471 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3472
3473 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003474 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003475 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3476 if (error.Success())
3477 {
Ed Maste64fad602013-07-29 20:58:06 +00003478 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003479 {
3480 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003481 const bool restarted = false;
3482 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003483 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003484 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003485 }
3486 else
3487 {
3488 // This shouldn't happen
3489 error.SetErrorString("failed to acquire process run lock");
3490 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003491
Greg Clayton144f3a92011-11-15 03:53:30 +00003492 if (error.Fail())
3493 {
3494 if (GetID() != LLDB_INVALID_PROCESS_ID)
3495 {
3496 SetID (LLDB_INVALID_PROCESS_ID);
3497 if (error.AsCString() == NULL)
3498 error.SetErrorString("attach failed");
3499
3500 SetExitStatus(-1, error.AsCString());
3501 }
3502 }
3503 else
3504 {
3505 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3506 StartPrivateStateThread();
3507 }
3508 return error;
3509 }
Greg Claytone996fd32011-03-08 22:40:15 +00003510 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003511 else
Greg Claytone996fd32011-03-08 22:40:15 +00003512 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003513 ProcessInstanceInfoList process_infos;
3514 PlatformSP platform_sp (m_target.GetPlatform ());
3515
3516 if (platform_sp)
3517 {
3518 ProcessInstanceInfoMatch match_info;
3519 match_info.GetProcessInfo() = attach_info;
3520 match_info.SetNameMatchType (eNameMatchEquals);
3521 platform_sp->FindProcesses (match_info, process_infos);
3522 const uint32_t num_matches = process_infos.GetSize();
3523 if (num_matches == 1)
3524 {
3525 attach_pid = process_infos.GetProcessIDAtIndex(0);
3526 // Fall through and attach using the above process ID
3527 }
3528 else
3529 {
3530 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3531 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003532 {
3533 StreamString s;
3534 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3535 for (size_t i = 0; i < num_matches; i++)
3536 {
3537 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3538 }
3539 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3540 process_name,
3541 s.GetData());
3542 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003543 else
3544 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3545 }
3546 }
3547 else
3548 {
3549 error.SetErrorString ("invalid platform, can't find processes by name");
3550 return error;
3551 }
Greg Claytone996fd32011-03-08 22:40:15 +00003552 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003553 }
3554 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003555 {
3556 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003557 }
3558 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003559
3560 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003561 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003562 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003563 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003564 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003565
Ed Maste64fad602013-07-29 20:58:06 +00003566 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003567 {
3568 // Now attach using these arguments.
3569 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003570 const bool restarted = false;
3571 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003572 error = DoAttachToProcessWithID (attach_pid, attach_info);
3573 }
3574 else
3575 {
3576 // This shouldn't happen
3577 error.SetErrorString("failed to acquire process run lock");
3578 }
3579
Greg Clayton144f3a92011-11-15 03:53:30 +00003580 if (error.Success())
3581 {
3582
3583 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3584 StartPrivateStateThread();
3585 }
3586 else
Greg Claytone996fd32011-03-08 22:40:15 +00003587 {
3588 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003589 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003590
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003591 const char *error_string = error.AsCString();
3592 if (error_string == NULL)
3593 error_string = "attach failed";
3594
3595 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003596 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003597 }
3598 }
3599 return error;
3600}
3601
Greg Clayton93d3c8332011-02-16 04:46:07 +00003602void
3603Process::CompleteAttach ()
3604{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003605 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3606 if (log)
3607 log->Printf ("Process::%s()", __FUNCTION__);
3608
Greg Clayton93d3c8332011-02-16 04:46:07 +00003609 // Let the process subclass figure out at much as it can about the process
3610 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003611 ArchSpec process_arch;
3612 DidAttach(process_arch);
3613
3614 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003615 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003616 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003617 if (log)
3618 {
3619 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3620 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3621 __FUNCTION__,
3622 triple_str ? triple_str : "<null>");
3623 }
3624 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003625
Jim Ingham4299fdb2011-09-15 01:10:17 +00003626 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3627 // the same as the one we've already set, switch architectures.
3628 PlatformSP platform_sp (m_target.GetPlatform ());
3629 assert (platform_sp.get());
3630 if (platform_sp)
3631 {
Greg Clayton70512312012-05-08 01:45:38 +00003632 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003633 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003634 {
3635 ArchSpec platform_arch;
3636 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3637 if (platform_sp)
3638 {
3639 m_target.SetPlatform (platform_sp);
3640 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003641 if (log)
3642 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 +00003643 }
3644 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003645 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003646 {
3647 ProcessInstanceInfo process_info;
3648 platform_sp->GetProcessInfo (GetID(), process_info);
3649 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003650 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003651 {
Greg Clayton70512312012-05-08 01:45:38 +00003652 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003653 if (log)
3654 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 ());
3655 }
Greg Clayton70512312012-05-08 01:45:38 +00003656 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003657 }
3658
3659 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003660 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003661 DynamicLoader *dyld = GetDynamicLoader ();
3662 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003663 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003664 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003665 if (log)
3666 {
3667 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3668 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3669 __FUNCTION__,
3670 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3671 dyld->GetPluginName().AsCString ("<unnamed>"));
3672 }
3673 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003674
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003675 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003676
Jason Molendaeef51062013-11-05 03:57:19 +00003677 SystemRuntime *system_runtime = GetSystemRuntime ();
3678 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003679 {
Jason Molendaeef51062013-11-05 03:57:19 +00003680 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003681 if (log)
3682 {
3683 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3684 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3685 __FUNCTION__,
3686 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3687 system_runtime->GetPluginName().AsCString("<unnamed>"));
3688 }
3689 }
Jason Molendaeef51062013-11-05 03:57:19 +00003690
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003691 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003692 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003693 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003694 Mutex::Locker modules_locker(target_modules.GetMutex());
3695 size_t num_modules = target_modules.GetSize();
3696 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003697
Andy Gibbsa297a972013-06-19 19:04:53 +00003698 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003699 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003700 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003701 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003702 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003703 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003704 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003705 break;
3706 }
3707 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003708 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003709 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003710 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003711 if (log)
3712 {
3713 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3714 log->Printf ("Process::%s after looping through modules, target executable is %s",
3715 __FUNCTION__,
3716 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3717 }
3718 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003719
3720 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003721}
3722
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003724Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003725{
Greg Claytonb766a732011-02-04 01:58:07 +00003726 m_abi_sp.reset();
3727 m_process_input_reader.reset();
3728
3729 // Find the process and its architecture. Make sure it matches the architecture
3730 // of the current Target, and if not adjust it.
3731
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003732 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003733 if (error.Success())
3734 {
Greg Clayton71337622011-02-24 22:24:29 +00003735 if (GetID() != LLDB_INVALID_PROCESS_ID)
3736 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003737 EventSP event_sp;
3738 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3739
3740 if (state == eStateStopped || state == eStateCrashed)
3741 {
3742 // If we attached and actually have a process on the other end, then
3743 // this ended up being the equivalent of an attach.
3744 CompleteAttach ();
3745
3746 // This delays passing the stopped event to listeners till
3747 // CompleteAttach gets a chance to complete...
3748 HandlePrivateEvent (event_sp);
3749
3750 }
Greg Clayton71337622011-02-24 22:24:29 +00003751 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003752
3753 if (PrivateStateThreadIsValid ())
3754 ResumePrivateStateThread ();
3755 else
3756 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003757 }
3758 return error;
3759}
3760
3761
3762Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003763Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764{
Greg Clayton5160ce52013-03-27 23:08:40 +00003765 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003766 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003767 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003768 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003769 StateAsCString(m_public_state.GetValue()),
3770 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771
3772 Error error (WillResume());
3773 // Tell the process it is about to resume before the thread list
3774 if (error.Success())
3775 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003776 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777 // can let all of our threads know that they are about to be
3778 // resumed. Threads will each be called with
3779 // Thread::WillResume(StateType) where StateType contains the state
3780 // that they are supposed to have when the process is resumed
3781 // (suspended/running/stepping). Threads should also check
3782 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003783 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003784 if (m_thread_list.WillResume())
3785 {
Jim Ingham372787f2012-04-07 00:00:41 +00003786 // Last thing, do the PreResumeActions.
3787 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003788 {
Jim Ingham0161b492013-02-09 01:29:05 +00003789 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003790 }
3791 else
3792 {
3793 m_mod_id.BumpResumeID();
3794 error = DoResume();
3795 if (error.Success())
3796 {
3797 DidResume();
3798 m_thread_list.DidResume();
3799 if (log)
3800 log->Printf ("Process thinks the process has resumed.");
3801 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003802 }
3803 }
3804 else
3805 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003806 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3807 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003808 // and let the world handle them.
3809 if (log)
3810 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3811
3812 SetPrivateState(eStateRunning);
3813 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814 }
3815 }
Jim Ingham444586b2011-01-24 06:34:17 +00003816 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003817 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003818 return error;
3819}
3820
3821Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003822Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003823{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003824 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3825 // in case it was already set and some thread plan logic calls halt on its
3826 // own.
3827 m_clear_thread_plans_on_stop |= clear_thread_plans;
3828
Jim Inghamaacc3182012-06-06 00:29:30 +00003829 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3830 // we could just straightaway get another event. It just narrows the window...
3831 m_currently_handling_event.WaitForValueEqualTo(false);
3832
3833
Jim Inghambb3a2832011-01-29 01:49:25 +00003834 // Pause our private state thread so we can ensure no one else eats
3835 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003836 Listener halt_listener ("lldb.process.halt_listener");
3837 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003838
Jim Inghambb3a2832011-01-29 01:49:25 +00003839 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003840 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003841
Greg Clayton06357c92014-07-30 17:38:47 +00003842 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003843 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003844 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003845
Greg Clayton513c26c2011-01-29 07:10:55 +00003846 bool caused_stop = false;
3847
3848 // Ask the process subclass to actually halt our process
3849 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003851 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003852 if (m_public_state.GetValue() == eStateAttaching)
3853 {
Greg Clayton06357c92014-07-30 17:38:47 +00003854 // Don't hijack and eat the eStateExited as the code that was doing
3855 // the attach will be waiting for this event...
3856 RestorePrivateProcessEvents();
3857 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003858 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:58 +00003859 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:55 +00003860 }
3861 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003862 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003863 // If "caused_stop" is true, then DoHalt stopped the process. If
3864 // "caused_stop" is false, the process was already stopped.
3865 // If the DoHalt caused the process to stop, then we want to catch
3866 // this event and set the interrupted bool to true before we pass
3867 // this along so clients know that the process was interrupted by
3868 // a halt command.
3869 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003870 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003871 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003872 TimeValue timeout_time;
3873 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003874 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003875 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3876 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003877
Jim Ingham0f16e732011-02-08 05:20:59 +00003878 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003879 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003880 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003881 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003882 }
3883 else
3884 {
Greg Clayton2637f822011-11-17 01:23:07 +00003885 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003886 {
3887 // We caused the process to interrupt itself, so mark this
3888 // as such in the stop event so clients can tell an interrupted
3889 // process from a natural stop
3890 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3891 }
3892 else
3893 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003894 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003895 if (log)
3896 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3897 error.SetErrorString ("Did not get stopped event after halt.");
3898 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003899 }
3900 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003901 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003902 }
3903 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003904 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003905 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003906 if (!restored_process_events)
3907 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003908
3909 // Post any event we might have consumed. If all goes well, we will have
3910 // stopped the process, intercepted the event and set the interrupted
3911 // bool in the event. Post it to the private event queue and that will end up
3912 // correctly setting the state.
3913 if (event_sp)
3914 m_private_state_broadcaster.BroadcastEvent(event_sp);
3915
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003916 return error;
3917}
3918
3919Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003920Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3921{
3922 Error error;
3923 if (m_public_state.GetValue() == eStateRunning)
3924 {
3925 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3926 if (log)
3927 log->Printf("Process::Destroy() About to halt.");
3928 error = Halt();
3929 if (error.Success())
3930 {
3931 // Consume the halt event.
3932 TimeValue timeout (TimeValue::Now());
3933 timeout.OffsetWithSeconds(1);
3934 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3935
3936 // If the process exited while we were waiting for it to stop, put the exited event into
3937 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3938 // they don't have a process anymore...
3939
3940 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3941 {
3942 if (log)
3943 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3944 return error;
3945 }
3946 else
3947 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3948
3949 if (state != eStateStopped)
3950 {
3951 if (log)
3952 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3953 // If we really couldn't stop the process then we should just error out here, but if the
3954 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3955 StateType private_state = m_private_state.GetValue();
3956 if (private_state != eStateStopped)
3957 {
3958 return error;
3959 }
3960 }
3961 }
3962 else
3963 {
3964 if (log)
3965 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3966 }
3967 }
3968 return error;
3969}
3970
3971Error
Jim Inghamacff8952013-05-02 00:27:30 +00003972Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003973{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003974 EventSP exit_event_sp;
3975 Error error;
3976 m_destroy_in_process = true;
3977
3978 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003979
3980 if (error.Success())
3981 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003982 if (DetachRequiresHalt())
3983 {
3984 error = HaltForDestroyOrDetach (exit_event_sp);
3985 if (!error.Success())
3986 {
3987 m_destroy_in_process = false;
3988 return error;
3989 }
3990 else if (exit_event_sp)
3991 {
3992 // We shouldn't need to do anything else here. There's no process left to detach from...
3993 StopPrivateStateThread();
3994 m_destroy_in_process = false;
3995 return error;
3996 }
3997 }
3998
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003999 m_thread_list.DiscardThreadPlans();
4000 DisableAllBreakpointSites();
4001
Jim Inghamacff8952013-05-02 00:27:30 +00004002 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004003 if (error.Success())
4004 {
4005 DidDetach();
4006 StopPrivateStateThread();
4007 }
Jim Inghamacff8952013-05-02 00:27:30 +00004008 else
4009 {
4010 return error;
4011 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004012 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004013 m_destroy_in_process = false;
4014
4015 // If we exited when we were waiting for a process to stop, then
4016 // forward the event here so we don't lose the event
4017 if (exit_event_sp)
4018 {
4019 // Directly broadcast our exited event because we shut down our
4020 // private state thread above
4021 BroadcastEvent(exit_event_sp);
4022 }
4023
4024 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4025 // the last events through the event system, in which case we might strand the write lock. Unlock
4026 // it here so when we do to tear down the process we don't get an error destroying the lock.
4027
Ed Maste64fad602013-07-29 20:58:06 +00004028 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004029 return error;
4030}
4031
4032Error
Jason Molendaede31932015-04-17 05:01:58 +00004033Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004034{
Jim Ingham09437922013-03-01 20:04:25 +00004035
4036 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
4037 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
4038 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00004039
4040 if (force_kill)
4041 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00004042
Ilia Kfcc89a02015-03-26 07:08:47 +00004043 if (GetShouldDetach())
4044 {
4045 // FIXME: This will have to be a process setting:
4046 bool keep_stopped = false;
4047 Detach(keep_stopped);
4048 }
4049
Jim Ingham09437922013-03-01 20:04:25 +00004050 m_destroy_in_process = true;
4051
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004052 Error error (WillDestroy());
4053 if (error.Success())
4054 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00004055 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004056 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00004057 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004058 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00004059 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004060
Jim Inghamaacc3182012-06-06 00:29:30 +00004061 if (m_public_state.GetValue() != eStateRunning)
4062 {
4063 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4064 // kill it, we don't want it hitting a breakpoint...
4065 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4066 // we're not going to have much luck doing this now.
4067 m_thread_list.DiscardThreadPlans();
4068 DisableAllBreakpointSites();
4069 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004070
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004071 error = DoDestroy();
4072 if (error.Success())
4073 {
4074 DidDestroy();
4075 StopPrivateStateThread();
4076 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004077 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00004078 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:04 +00004079 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00004080
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004081 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00004082 {
4083 m_process_input_reader->SetIsDone(true);
4084 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004085 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00004086 }
4087
Greg Clayton85fb1b92012-09-11 02:33:37 +00004088 // If we exited when we were waiting for a process to stop, then
4089 // forward the event here so we don't lose the event
4090 if (exit_event_sp)
4091 {
4092 // Directly broadcast our exited event because we shut down our
4093 // private state thread above
4094 BroadcastEvent(exit_event_sp);
4095 }
4096
Jim Inghamb1e2e842012-04-12 18:49:31 +00004097 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4098 // the last events through the event system, in which case we might strand the write lock. Unlock
4099 // 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 +00004100 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004101 }
Jim Ingham09437922013-03-01 20:04:25 +00004102
4103 m_destroy_in_process = false;
4104
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004105 return error;
4106}
4107
4108Error
4109Process::Signal (int signal)
4110{
4111 Error error (WillSignal());
4112 if (error.Success())
4113 {
4114 error = DoSignal(signal);
4115 if (error.Success())
4116 DidSignal();
4117 }
4118 return error;
4119}
4120
Zachary Turner93749ab2015-03-03 21:51:25 +00004121void
4122Process::SetUnixSignals (const UnixSignalsSP &signals_sp)
4123{
4124 assert (signals_sp && "null signals_sp");
4125 m_unix_signals_sp = signals_sp;
4126}
4127
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00004128const lldb::UnixSignalsSP &
Zachary Turner93749ab2015-03-03 21:51:25 +00004129Process::GetUnixSignals ()
4130{
4131 assert (m_unix_signals_sp && "null m_unix_signals_sp");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00004132 return m_unix_signals_sp;
Zachary Turner93749ab2015-03-03 21:51:25 +00004133}
4134
Greg Clayton514487e2011-02-15 21:59:32 +00004135lldb::ByteOrder
4136Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004137{
Greg Clayton514487e2011-02-15 21:59:32 +00004138 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004139}
4140
4141uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00004142Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004143{
Greg Clayton514487e2011-02-15 21:59:32 +00004144 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145}
4146
Greg Clayton514487e2011-02-15 21:59:32 +00004147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004148bool
4149Process::ShouldBroadcastEvent (Event *event_ptr)
4150{
4151 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4152 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00004153 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00004154
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004155 switch (state)
4156 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004157 case eStateDetached:
4158 case eStateExited:
4159 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00004160 m_stdio_communication.SynchronizeWithReadThread();
4161 // fall-through
4162 case eStateConnected:
4163 case eStateAttaching:
4164 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165 // These events indicate changes in the state of the debugging session, always report them.
4166 return_value = true;
4167 break;
4168 case eStateInvalid:
4169 // We stopped for no apparent reason, don't report it.
4170 return_value = false;
4171 break;
4172 case eStateRunning:
4173 case eStateStepping:
4174 // If we've started the target running, we handle the cases where we
4175 // are already running and where there is a transition from stopped to
4176 // running differently.
4177 // running -> running: Automatically suppress extra running events
4178 // stopped -> running: Report except when there is one or more no votes
4179 // and no yes votes.
4180 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004181 if (m_force_next_event_delivery)
4182 return_value = true;
4183 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004184 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004185 switch (m_last_broadcast_state)
4186 {
4187 case eStateRunning:
4188 case eStateStepping:
4189 // We always suppress multiple runnings with no PUBLIC stop in between.
4190 return_value = false;
4191 break;
4192 default:
4193 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004194 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004195 // events. If I run the lldb/test/thread/a.out file and
4196 // break at main.cpp:58, run and hit the breakpoints on
4197 // multiple threads, then somehow during the stepping over
4198 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004199
Jim Ingham1460e4b2014-01-10 23:46:59 +00004200 // This is a transition from stop to run.
4201 switch (m_thread_list.ShouldReportRun (event_ptr))
4202 {
4203 case eVoteYes:
4204 case eVoteNoOpinion:
4205 return_value = true;
4206 break;
4207 case eVoteNo:
4208 return_value = false;
4209 break;
4210 }
4211 break;
4212 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213 }
4214 break;
4215 case eStateStopped:
4216 case eStateCrashed:
4217 case eStateSuspended:
4218 {
4219 // We've stopped. First see if we're going to restart the target.
4220 // If we are going to stop, then we always broadcast the event.
4221 // 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 +00004222 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004223
Pavel Labath3f5df532015-03-12 10:12:41 +00004224 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00004225 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004226 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004227 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004228 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004229 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004230 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004231 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004232 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4233 // so they can properly set their state.
4234 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004235 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004236 }
4237 else
4238 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004239 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4240 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004241
Jim Ingham0161b492013-02-09 01:29:05 +00004242 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4243 // Asking the thread list is also not likely to go well, since we are running again.
4244 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004245
Jim Ingham0161b492013-02-09 01:29:05 +00004246 if (!was_restarted)
4247 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004248
Jim Ingham221d51c2013-05-08 00:35:16 +00004249 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004250 {
Jim Ingham0161b492013-02-09 01:29:05 +00004251 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4252 if (log)
4253 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004254 should_resume, StateAsCString(state),
4255 was_restarted, stop_vote);
4256
Jim Ingham0161b492013-02-09 01:29:05 +00004257 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004258 {
4259 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004260 return_value = true;
4261 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004262 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004263 case eVoteNo:
4264 return_value = false;
4265 break;
4266 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004267
Jim Inghamcb95f342012-09-05 21:13:56 +00004268 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004269 {
4270 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004271 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4272 static_cast<void*>(event_ptr),
4273 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004274 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004275 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004276 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004277
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278 }
4279 else
4280 {
4281 return_value = true;
4282 SynchronouslyNotifyStateChanged (state);
4283 }
4284 }
4285 }
Jim Ingham0161b492013-02-09 01:29:05 +00004286 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004287 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004288
Jim Ingham1460e4b2014-01-10 23:46:59 +00004289 // Forcing the next event delivery is a one shot deal. So reset it here.
4290 m_force_next_event_delivery = false;
4291
Jim Ingham0161b492013-02-09 01:29:05 +00004292 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4293 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4294 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4295 // because the PublicState reflects the last event pulled off the queue, and there may be several
4296 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4297 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004298
Jim Ingham0161b492013-02-09 01:29:05 +00004299 if (return_value)
4300 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004302 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004303 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004304 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004305 StateAsCString(m_last_broadcast_state),
4306 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004307 return return_value;
4308}
4309
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004310
4311bool
Jim Ingham60c915e2015-06-23 21:02:45 +00004312Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004313{
Greg Clayton5160ce52013-03-27 23:08:40 +00004314 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004315
Greg Clayton8b82f082011-04-12 05:54:46 +00004316 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004317 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004318 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4319
Jim Ingham60c915e2015-06-23 21:02:45 +00004320 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004321 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004322
4323 // Create a thread that watches our internal state and controls which
4324 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004325 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004326
Zachary Turner39de3112014-09-09 20:54:56 +00004327 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004328 {
Zachary Turner39de3112014-09-09 20:54:56 +00004329 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4330 if (already_running)
4331 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4332 else
4333 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004334 }
Jim Ingham372787f2012-04-07 00:00:41 +00004335 else
Todd Fiala17096d72014-07-16 19:03:16 +00004336 {
4337 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004338 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004339 else
Zachary Turner39de3112014-09-09 20:54:56 +00004340 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004341 }
4342
Jim Ingham076b3042012-04-10 01:21:57 +00004343 // Create the private state thread, and start it running.
Jim Ingham60c915e2015-06-23 21:02:45 +00004344 PrivateStateThreadArgs args = {this, is_secondary_thread};
4345 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) &args, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004346 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004347 {
4348 ResumePrivateStateThread();
4349 return true;
4350 }
4351 else
4352 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353}
4354
4355void
4356Process::PausePrivateStateThread ()
4357{
4358 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4359}
4360
4361void
4362Process::ResumePrivateStateThread ()
4363{
4364 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4365}
4366
4367void
4368Process::StopPrivateStateThread ()
4369{
Greg Clayton8b82f082011-04-12 05:54:46 +00004370 if (PrivateStateThreadIsValid ())
4371 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004372 else
4373 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004374 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004375 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004376 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004377 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004378}
4379
4380void
4381Process::ControlPrivateStateThread (uint32_t signal)
4382{
Greg Clayton5160ce52013-03-27 23:08:40 +00004383 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004384
4385 assert (signal == eBroadcastInternalStateControlStop ||
4386 signal == eBroadcastInternalStateControlPause ||
4387 signal == eBroadcastInternalStateControlResume);
4388
4389 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004390 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004392 // Signal the private state thread. First we should copy this is case the
4393 // thread starts exiting since the private state thread will NULL this out
4394 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004395 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004396 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004397 {
4398 TimeValue timeout_time;
4399 bool timed_out;
4400
4401 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4402
4403 timeout_time = TimeValue::Now();
4404 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004405 if (log)
4406 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004407 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4408 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4409
4410 if (signal == eBroadcastInternalStateControlStop)
4411 {
4412 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004413 {
Zachary Turner39de3112014-09-09 20:54:56 +00004414 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004415 if (log)
4416 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4417 }
4418 else
4419 {
4420 if (log)
4421 log->Printf ("The control event killed the private state thread without having to cancel.");
4422 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004423
4424 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004425 private_state_thread.Join(&result);
4426 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004427 }
4428 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004429 else
4430 {
4431 if (log)
4432 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4433 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004434}
4435
4436void
Jim Inghamcfc09352012-07-27 23:57:19 +00004437Process::SendAsyncInterrupt ()
4438{
4439 if (PrivateStateThreadIsValid())
4440 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4441 else
4442 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4443}
4444
4445void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004446Process::HandlePrivateEvent (EventSP &event_sp)
4447{
Greg Clayton5160ce52013-03-27 23:08:40 +00004448 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004449 m_resume_requested = false;
4450
Jim Inghamaacc3182012-06-06 00:29:30 +00004451 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004452
Greg Clayton414f5d32011-01-25 02:58:48 +00004453 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004454
4455 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004456 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004457 {
Jim Ingham754ab982011-01-29 04:05:41 +00004458 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004459 if (log)
4460 log->Printf ("Ran next event action, result was %d.", action_result);
4461
Jim Inghambb3a2832011-01-29 01:49:25 +00004462 switch (action_result)
4463 {
4464 case NextEventAction::eEventActionSuccess:
4465 SetNextEventAction(NULL);
4466 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004467
Jim Inghambb3a2832011-01-29 01:49:25 +00004468 case NextEventAction::eEventActionRetry:
4469 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004470
Jim Inghambb3a2832011-01-29 01:49:25 +00004471 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004472 // Handle Exiting Here. If we already got an exited event,
4473 // we should just propagate it. Otherwise, swallow this event,
4474 // and set our state to exit so the next event will kill us.
4475 if (new_state != eStateExited)
4476 {
4477 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004478 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004479 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004480 SetNextEventAction(NULL);
4481 return;
4482 }
4483 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004484 break;
4485 }
4486 }
4487
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004488 // See if we should broadcast this state to external clients?
4489 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004490
4491 if (should_broadcast)
4492 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004493 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004494 if (log)
4495 {
Daniel Malead01b2952012-11-29 21:49:15 +00004496 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004497 __FUNCTION__,
4498 GetID(),
4499 StateAsCString(new_state),
4500 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004501 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004502 }
Jim Ingham9575d842011-03-11 03:53:59 +00004503 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004504 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004505 {
4506 // Only push the input handler if we aren't fowarding events,
4507 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004508 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004509 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4510 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004511 {
Greg Clayton44d93782014-01-27 23:43:24 +00004512 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004513 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4514 if (log)
4515 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4516 }
Greg Clayton44d93782014-01-27 23:43:24 +00004517 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004518 else if (StateIsStoppedState(new_state, false))
4519 {
4520 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4521 {
4522 // If the lldb_private::Debugger is handling the events, we don't
4523 // want to pop the process IOHandler here, we want to do it when
4524 // we receive the stopped event so we can carefully control when
4525 // the process IOHandler is popped because when we stop we want to
4526 // display some text stating how and why we stopped, then maybe some
4527 // process/thread/frame info, and then we want the "(lldb) " prompt
4528 // to show up. If we pop the process IOHandler here, then we will
4529 // cause the command interpreter to become the top IOHandler after
4530 // the process pops off and it will update its prompt right away...
4531 // See the Debugger.cpp file where it calls the function as
4532 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4533 // Otherwise we end up getting overlapping "(lldb) " prompts and
4534 // garbled output.
4535 //
4536 // If we aren't handling the events in the debugger (which is indicated
4537 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4538 // are hijacked, then we always pop the process IO handler manually.
4539 // Hijacking happens when the internal process state thread is running
4540 // thread plans, or when commands want to run in synchronous mode
4541 // and they call "process->WaitForProcessToStop()". An example of something
4542 // that will hijack the events is a simple expression:
4543 //
4544 // (lldb) expr (int)puts("hello")
4545 //
4546 // This will cause the internal process state thread to resume and halt
4547 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4548 // events) and we do need the IO handler to be pushed and popped
4549 // correctly.
4550
4551 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4552 PopProcessIOHandler ();
4553 }
4554 }
Jim Ingham9575d842011-03-11 03:53:59 +00004555
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004556 BroadcastEvent (event_sp);
4557 }
4558 else
4559 {
4560 if (log)
4561 {
Daniel Malead01b2952012-11-29 21:49:15 +00004562 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004563 __FUNCTION__,
4564 GetID(),
4565 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004566 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004567 }
4568 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004569 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004570}
4571
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004572thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004573Process::PrivateStateThread (void *arg)
4574{
Jim Ingham60c915e2015-06-23 21:02:45 +00004575 PrivateStateThreadArgs *real_args = static_cast<PrivateStateThreadArgs *> (arg);
4576 thread_result_t result = real_args->process->RunPrivateStateThread(real_args->is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004577 return result;
4578}
4579
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004580thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004581Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004582{
Jim Ingham076b3042012-04-10 01:21:57 +00004583 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004584 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004585
Greg Clayton5160ce52013-03-27 23:08:40 +00004586 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004587 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004588 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4589 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004590
4591 bool exit_now = false;
4592 while (!exit_now)
4593 {
4594 EventSP event_sp;
4595 WaitForEventsPrivate (NULL, event_sp, control_only);
4596 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4597 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004598 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004599 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4600 __FUNCTION__, static_cast<void*>(this), GetID(),
4601 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004602
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004603 switch (event_sp->GetType())
4604 {
4605 case eBroadcastInternalStateControlStop:
4606 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004607 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004608
4609 case eBroadcastInternalStateControlPause:
4610 control_only = true;
4611 break;
4612
4613 case eBroadcastInternalStateControlResume:
4614 control_only = false;
4615 break;
4616 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004617
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004618 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004619 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004620 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004621 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4622 {
4623 if (m_public_state.GetValue() == eStateAttaching)
4624 {
4625 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004626 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4627 __FUNCTION__, static_cast<void*>(this),
4628 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004629 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4630 }
4631 else
4632 {
4633 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004634 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4635 __FUNCTION__, static_cast<void*>(this),
4636 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004637 Halt();
4638 }
4639 continue;
4640 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004641
4642 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4643
4644 if (internal_state != eStateInvalid)
4645 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004646 if (m_clear_thread_plans_on_stop &&
4647 StateIsStoppedState(internal_state, true))
4648 {
4649 m_clear_thread_plans_on_stop = false;
4650 m_thread_list.DiscardThreadPlans();
4651 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004652 HandlePrivateEvent (event_sp);
4653 }
4654
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004655 if (internal_state == eStateInvalid ||
4656 internal_state == eStateExited ||
4657 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004658 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004659 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004660 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4661 __FUNCTION__, static_cast<void*>(this), GetID(),
4662 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004663
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004664 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004665 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004666 }
4667
Caroline Tice20ad3c42010-10-29 21:48:37 +00004668 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004669 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004670 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4671 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004672
Jim Ingham60c915e2015-06-23 21:02:45 +00004673 // If we are a secondary thread, then the primary thread we are working for will have already
4674 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4675 // try to change it on the way out.
4676 if (!is_secondary_thread)
4677 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004678 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004679 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004680 return NULL;
4681}
4682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004683//------------------------------------------------------------------
4684// Process Event Data
4685//------------------------------------------------------------------
4686
4687Process::ProcessEventData::ProcessEventData () :
4688 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004689 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004690 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004691 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004692 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004693 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004694{
4695}
4696
4697Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4698 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004699 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004700 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004701 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004702 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004703 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004704{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004705 if (process_sp)
4706 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004707}
4708
4709Process::ProcessEventData::~ProcessEventData()
4710{
4711}
4712
4713const ConstString &
4714Process::ProcessEventData::GetFlavorString ()
4715{
4716 static ConstString g_flavor ("Process::ProcessEventData");
4717 return g_flavor;
4718}
4719
4720const ConstString &
4721Process::ProcessEventData::GetFlavor () const
4722{
4723 return ProcessEventData::GetFlavorString ();
4724}
4725
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004726void
4727Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4728{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004729 ProcessSP process_sp(m_process_wp.lock());
4730
4731 if (!process_sp)
4732 return;
4733
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004734 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004735 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4736 // the public event queue, then other times when we're pretending that this is where we stopped at the
4737 // end of expression evaluation. m_update_state is used to distinguish these
4738 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004739 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004740 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004741 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004742
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004743 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004744
4745 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4746 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4747 // end up restarting the process.
4748 if (m_interrupted)
4749 return;
4750
4751 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004752 if (m_state == eStateStopped && ! m_restarted)
Greg Clayton2e309072015-07-17 23:42:28 +00004753 {
4754 // Let process subclasses know we are about to do a public stop and
4755 // do anything they might need to in order to speed up register and
4756 // memory accesses.
4757 process_sp->WillPublicStop();
4758
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004759 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004760 uint32_t num_threads = curr_thread_list.GetSize();
4761 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004762
Jim Ingham4b536182011-08-09 02:12:22 +00004763 // The actions might change one of the thread's stop_info's opinions about whether we should
4764 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004765
4766 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4767 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4768 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4769 // 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
4770 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004771 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004772 for (idx = 0; idx < num_threads; ++idx)
4773 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4774
Jim Inghamc7078c22012-12-13 22:24:15 +00004775 // Use this to track whether we should continue from here. We will only continue the target running if
4776 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4777 // then it doesn't matter what the other threads say...
4778
4779 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004780
Jim Ingham0ad7e052013-04-25 02:04:59 +00004781 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4782 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4783 // thing to do is, and it's better to let the user decide than continue behind their backs.
4784
4785 bool does_anybody_have_an_opinion = false;
4786
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004787 for (idx = 0; idx < num_threads; ++idx)
4788 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004789 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004790 if (curr_thread_list.GetSize() != num_threads)
4791 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004792 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004793 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004794 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 +00004795 break;
4796 }
4797
4798 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4799
4800 if (thread_sp->GetIndexID() != thread_index_array[idx])
4801 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004802 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004803 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004804 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004805 idx,
4806 thread_index_array[idx],
4807 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004808 break;
4809 }
4810
Jim Inghamb15bfc72010-10-20 00:39:53 +00004811 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004812 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004813 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004814 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004815 bool this_thread_wants_to_stop;
4816 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004817 {
Jim Ingham0161b492013-02-09 01:29:05 +00004818 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4819 }
4820 else
4821 {
4822 stop_info_sp->PerformAction(event_ptr);
4823 // The stop action might restart the target. If it does, then we want to mark that in the
4824 // event so that whoever is receiving it will know to wait for the running event and reflect
4825 // that state appropriately.
4826 // We also need to stop processing actions, since they aren't expecting the target to be running.
4827
4828 // FIXME: we might have run.
4829 if (stop_info_sp->HasTargetRunSinceMe())
4830 {
4831 SetRestarted (true);
4832 break;
4833 }
4834
4835 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004836 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004837
Jim Inghamc7078c22012-12-13 22:24:15 +00004838 if (still_should_stop == false)
4839 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004840 }
4841 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004842
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004843
Jim Inghama8ca6e22013-05-03 23:04:37 +00004844 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004845 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004846 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004847 {
4848 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004849 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004850 // Use the public resume method here, since this is just
4851 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004852 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004853 }
4854 else
4855 {
4856 // If we didn't restart, run the Stop Hooks here:
4857 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004858 process_sp->GetTarget().RunStopHooks();
4859 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004860 SetRestarted(true);
4861 }
Jim Ingham9575d842011-03-11 03:53:59 +00004862 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004863 }
4864}
4865
4866void
4867Process::ProcessEventData::Dump (Stream *s) const
4868{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004869 ProcessSP process_sp(m_process_wp.lock());
4870
4871 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004872 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004873 static_cast<void*>(process_sp.get()), process_sp->GetID());
4874 else
4875 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004876
Greg Clayton8b82f082011-04-12 05:54:46 +00004877 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004878}
4879
4880const Process::ProcessEventData *
4881Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4882{
4883 if (event_ptr)
4884 {
4885 const EventData *event_data = event_ptr->GetData();
4886 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4887 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4888 }
4889 return NULL;
4890}
4891
4892ProcessSP
4893Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4894{
4895 ProcessSP process_sp;
4896 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4897 if (data)
4898 process_sp = data->GetProcessSP();
4899 return process_sp;
4900}
4901
4902StateType
4903Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4904{
4905 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4906 if (data == NULL)
4907 return eStateInvalid;
4908 else
4909 return data->GetState();
4910}
4911
4912bool
4913Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4914{
4915 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4916 if (data == NULL)
4917 return false;
4918 else
4919 return data->GetRestarted();
4920}
4921
4922void
4923Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4924{
4925 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4926 if (data != NULL)
4927 data->SetRestarted(new_value);
4928}
4929
Jim Ingham0161b492013-02-09 01:29:05 +00004930size_t
4931Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4932{
4933 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4934 if (data != NULL)
4935 return data->GetNumRestartedReasons();
4936 else
4937 return 0;
4938}
4939
4940const char *
4941Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4942{
4943 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4944 if (data != NULL)
4945 return data->GetRestartedReasonAtIndex(idx);
4946 else
4947 return NULL;
4948}
4949
4950void
4951Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4952{
4953 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4954 if (data != NULL)
4955 data->AddRestartedReason(reason);
4956}
4957
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004958bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004959Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4960{
4961 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4962 if (data == NULL)
4963 return false;
4964 else
4965 return data->GetInterrupted ();
4966}
4967
4968void
4969Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4970{
4971 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4972 if (data != NULL)
4973 data->SetInterrupted(new_value);
4974}
4975
4976bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004977Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4978{
4979 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4980 if (data)
4981 {
4982 data->SetUpdateStateOnRemoval();
4983 return true;
4984 }
4985 return false;
4986}
4987
Greg Claytond9e416c2012-02-18 05:35:26 +00004988lldb::TargetSP
4989Process::CalculateTarget ()
4990{
4991 return m_target.shared_from_this();
4992}
4993
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004994void
Greg Clayton0603aa92010-10-04 01:05:56 +00004995Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004996{
Greg Claytonc14ee322011-09-22 04:58:26 +00004997 exe_ctx.SetTargetPtr (&m_target);
4998 exe_ctx.SetProcessPtr (this);
4999 exe_ctx.SetThreadPtr(NULL);
5000 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005001}
5002
Greg Claytone996fd32011-03-08 22:40:15 +00005003//uint32_t
5004//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
5005//{
5006// return 0;
5007//}
5008//
5009//ArchSpec
5010//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
5011//{
5012// return Host::GetArchSpecForExistingProcess (pid);
5013//}
5014//
5015//ArchSpec
5016//Process::GetArchSpecForExistingProcess (const char *process_name)
5017//{
5018// return Host::GetArchSpecForExistingProcess (process_name);
5019//}
5020//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005021void
5022Process::AppendSTDOUT (const char * s, size_t len)
5023{
Greg Clayton3af9ea52010-11-18 05:57:03 +00005024 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005025 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00005026 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005027}
5028
5029void
Greg Clayton93e86192011-11-13 04:45:22 +00005030Process::AppendSTDERR (const char * s, size_t len)
5031{
5032 Mutex::Locker locker (m_stdio_communication_mutex);
5033 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00005034 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00005035}
5036
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005037void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005038Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005039{
5040 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005041 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005042 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
5043}
5044
5045size_t
5046Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
5047{
5048 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005049 if (m_profile_data.empty())
5050 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005051
5052 std::string &one_profile_data = m_profile_data.front();
5053 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005054 if (bytes_available > 0)
5055 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005056 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005057 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005058 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5059 static_cast<void*>(buf),
5060 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005061 if (bytes_available > buf_size)
5062 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005063 memcpy(buf, one_profile_data.c_str(), buf_size);
5064 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005065 bytes_available = buf_size;
5066 }
5067 else
5068 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005069 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005070 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005071 }
5072 }
5073 return bytes_available;
5074}
5075
5076
Greg Clayton93e86192011-11-13 04:45:22 +00005077//------------------------------------------------------------------
5078// Process STDIO
5079//------------------------------------------------------------------
5080
5081size_t
5082Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5083{
5084 Mutex::Locker locker(m_stdio_communication_mutex);
5085 size_t bytes_available = m_stdout_data.size();
5086 if (bytes_available > 0)
5087 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005088 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005089 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005090 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5091 static_cast<void*>(buf),
5092 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005093 if (bytes_available > buf_size)
5094 {
5095 memcpy(buf, m_stdout_data.c_str(), buf_size);
5096 m_stdout_data.erase(0, buf_size);
5097 bytes_available = buf_size;
5098 }
5099 else
5100 {
5101 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5102 m_stdout_data.clear();
5103 }
5104 }
5105 return bytes_available;
5106}
5107
5108
5109size_t
5110Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5111{
5112 Mutex::Locker locker(m_stdio_communication_mutex);
5113 size_t bytes_available = m_stderr_data.size();
5114 if (bytes_available > 0)
5115 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005116 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005117 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005118 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5119 static_cast<void*>(buf),
5120 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005121 if (bytes_available > buf_size)
5122 {
5123 memcpy(buf, m_stderr_data.c_str(), buf_size);
5124 m_stderr_data.erase(0, buf_size);
5125 bytes_available = buf_size;
5126 }
5127 else
5128 {
5129 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5130 m_stderr_data.clear();
5131 }
5132 }
5133 return bytes_available;
5134}
5135
5136void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005137Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5138{
5139 Process *process = (Process *) baton;
5140 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5141}
5142
Greg Clayton44d93782014-01-27 23:43:24 +00005143class IOHandlerProcessSTDIO :
5144 public IOHandler
5145{
5146public:
5147 IOHandlerProcessSTDIO (Process *process,
5148 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005149 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005150 m_process (process),
5151 m_read_file (),
5152 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005153 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005154 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005155 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00005156 m_read_file.SetDescriptor(GetInputFD(), false);
5157 }
5158
5159 virtual
5160 ~IOHandlerProcessSTDIO ()
5161 {
5162
5163 }
5164
Greg Clayton44d93782014-01-27 23:43:24 +00005165 // Each IOHandler gets to run until it is done. It should read data
5166 // from the "in" and place output into "out" and "err and return
5167 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00005168 void
5169 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00005170 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005171 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005172 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005173 SetIsDone(true);
5174 return;
5175 }
5176
5177 SetIsDone(false);
5178 const int read_fd = m_read_file.GetDescriptor();
5179 TerminalState terminal_state;
5180 terminal_state.Save (read_fd, false);
5181 Terminal terminal(read_fd);
5182 terminal.SetCanonical(false);
5183 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005184// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005185#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005186 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5187 while (!GetIsDone())
5188 {
5189 fd_set read_fdset;
5190 FD_ZERO (&read_fdset);
5191 FD_SET (read_fd, &read_fdset);
5192 FD_SET (pipe_read_fd, &read_fdset);
5193 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5194 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5195 if (num_set_fds < 0)
5196 {
5197 const int select_errno = errno;
5198
5199 if (select_errno != EINTR)
5200 SetIsDone(true);
5201 }
5202 else if (num_set_fds > 0)
5203 {
5204 char ch = 0;
5205 size_t n;
5206 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00005207 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005208 n = 1;
5209 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005210 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005211 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005212 SetIsDone(true);
5213 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005214 else
5215 SetIsDone(true);
5216 }
5217 if (FD_ISSET (pipe_read_fd, &read_fdset))
5218 {
5219 size_t bytes_read;
5220 // Consume the interrupt byte
5221 Error error = m_pipe.Read(&ch, 1, bytes_read);
5222 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00005223 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005224 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00005225 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005226 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00005227 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005228 break;
5229 case 'i':
5230 if (StateIsRunningState(m_process->GetState()))
5231 m_process->Halt();
5232 break;
Greg Clayton44d93782014-01-27 23:43:24 +00005233 }
5234 }
5235 }
Greg Clayton44d93782014-01-27 23:43:24 +00005236 }
Greg Clayton44d93782014-01-27 23:43:24 +00005237 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005238#endif
5239 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005240 }
5241
Pavel Labath44464872015-05-27 12:40:32 +00005242 void
5243 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005244 {
Greg Clayton19e11352014-02-26 22:47:33 +00005245 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005246 size_t bytes_written = 0;
5247 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005248 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005249
Pavel Labath44464872015-05-27 12:40:32 +00005250 bool
5251 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005252 {
Greg Clayton19e11352014-02-26 22:47:33 +00005253 // Do only things that are safe to do in an interrupt context (like in
5254 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5255 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5256 // that was written to the pipe and then call m_process->Halt() from a
5257 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005258 if (m_active)
5259 {
5260 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005261 size_t bytes_written = 0;
5262 Error result = m_pipe.Write(&ch, 1, bytes_written);
5263 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005264 }
5265 else
5266 {
5267 // This IOHandler might be pushed on the stack, but not being run currently
5268 // so do the right thing if we aren't actively watching for STDIN by sending
5269 // the interrupt to the process. Otherwise the write to the pipe above would
5270 // do nothing. This can happen when the command interpreter is running and
5271 // gets a "expression ...". It will be on the IOHandler thread and sending
5272 // the input is complete to the delegate which will cause the expression to
5273 // run, which will push the process IO handler, but not run it.
5274
5275 if (StateIsRunningState(m_process->GetState()))
5276 {
5277 m_process->SendAsyncInterrupt();
5278 return true;
5279 }
5280 }
5281 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005282 }
Greg Clayton44d93782014-01-27 23:43:24 +00005283
Pavel Labath44464872015-05-27 12:40:32 +00005284 void
5285 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005286 {
5287
5288 }
5289
5290protected:
5291 Process *m_process;
5292 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5293 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005294 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005295};
5296
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005297void
Greg Clayton44d93782014-01-27 23:43:24 +00005298Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005299{
5300 // First set up the Read Thread for reading/handling process I/O
5301
Greg Clayton44d93782014-01-27 23:43:24 +00005302 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005303
5304 if (conn_ap.get())
5305 {
5306 m_stdio_communication.SetConnection (conn_ap.release());
5307 if (m_stdio_communication.IsConnected())
5308 {
5309 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5310 m_stdio_communication.StartReadThread();
5311
5312 // Now read thread is set up, set up input reader.
5313
5314 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005315 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005316 }
5317 }
5318}
5319
Greg Claytonb4874f12014-02-28 18:22:24 +00005320bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005321Process::ProcessIOHandlerIsActive ()
5322{
5323 IOHandlerSP io_handler_sp (m_process_input_reader);
5324 if (io_handler_sp)
5325 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5326 return false;
5327}
5328bool
Greg Clayton44d93782014-01-27 23:43:24 +00005329Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005330{
Greg Clayton44d93782014-01-27 23:43:24 +00005331 IOHandlerSP io_handler_sp (m_process_input_reader);
5332 if (io_handler_sp)
5333 {
Pavel Labath44464872015-05-27 12:40:32 +00005334 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5335 if (log)
5336 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5337
Greg Clayton44d93782014-01-27 23:43:24 +00005338 io_handler_sp->SetIsDone(false);
5339 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005340 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005341 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005342 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005343}
5344
Greg Claytonb4874f12014-02-28 18:22:24 +00005345bool
Greg Clayton44d93782014-01-27 23:43:24 +00005346Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005347{
Greg Clayton44d93782014-01-27 23:43:24 +00005348 IOHandlerSP io_handler_sp (m_process_input_reader);
5349 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005350 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5351 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005352}
5353
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005354// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005355void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005356Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005357{
Greg Clayton6920b522012-08-22 18:39:03 +00005358 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005359}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005360
Greg Clayton99d0faf2010-11-18 23:32:35 +00005361void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005362Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005363{
Greg Clayton6920b522012-08-22 18:39:03 +00005364 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005365}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005366
Jim Ingham1624a2d2014-05-05 02:26:40 +00005367ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005368Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005369 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005370 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005371 Stream &errors)
5372{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005373 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005374
Jim Ingham77787032011-01-20 02:03:18 +00005375 if (thread_plan_sp.get() == NULL)
5376 {
5377 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005378 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005379 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005380
Jim Ingham7d7931d2013-03-28 00:05:34 +00005381 if (!thread_plan_sp->ValidatePlan(NULL))
5382 {
5383 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005384 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005385 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005386
Greg Claytonc14ee322011-09-22 04:58:26 +00005387 if (exe_ctx.GetProcessPtr() != this)
5388 {
5389 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005390 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005391 }
5392
5393 Thread *thread = exe_ctx.GetThreadPtr();
5394 if (thread == NULL)
5395 {
5396 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005397 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005398 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005399
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005400 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5401 // For that to be true the plan can't be private - since private plans suppress themselves in the
5402 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005403
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005404 bool orig_plan_private = thread_plan_sp->GetPrivate();
5405 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005406
Jim Ingham444586b2011-01-24 06:34:17 +00005407 if (m_private_state.GetValue() != eStateStopped)
5408 {
5409 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005410 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005411 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005412
Jim Ingham66243842011-08-13 00:56:10 +00005413 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005414 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005415 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005416 if (!selected_frame_sp)
5417 {
5418 thread->SetSelectedFrame(0);
5419 selected_frame_sp = thread->GetSelectedFrame();
5420 if (!selected_frame_sp)
5421 {
5422 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005423 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005424 }
5425 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005426
Jim Ingham11b0e052013-02-19 23:22:45 +00005427 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005428
5429 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5430 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005431
Greg Claytonc14ee322011-09-22 04:58:26 +00005432 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005433
Jim Ingham66243842011-08-13 00:56:10 +00005434 uint32_t selected_tid;
5435 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005436 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005437 {
5438 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005439 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005440 }
5441 else
5442 {
5443 selected_tid = LLDB_INVALID_THREAD_ID;
5444 }
5445
Zachary Turner39de3112014-09-09 20:54:56 +00005446 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005447 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005448 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005449
Greg Clayton5160ce52013-03-27 23:08:40 +00005450 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005451 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005452 {
Jim Ingham076b3042012-04-10 01:21:57 +00005453 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5454 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005455 // 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 +00005456 // we are fielding public events here.
5457 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005458 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 +00005459
Jim Ingham372787f2012-04-07 00:00:41 +00005460 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005461
5462 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5463 // returning control here.
5464 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5465 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5466 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5467 // do just what we want.
5468 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5469 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5470 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5471 old_state = m_public_state.GetValue();
5472 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005473
Jim Ingham076b3042012-04-10 01:21:57 +00005474 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005475 StartPrivateStateThread(true);
5476 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005477
Jim Ingham372787f2012-04-07 00:00:41 +00005478 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005479
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005480 if (options.GetDebug())
5481 {
5482 // In this case, we aren't actually going to run, we just want to stop right away.
5483 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5484 // FIXME: To make this prettier we should invent some stop reason for this, but that
5485 // is only cosmetic, and this functionality is only of use to lldb developers who can
5486 // live with not pretty...
5487 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005488 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005489 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005490
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005491 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005492
Sean Callanana46ec452012-07-11 21:31:24 +00005493 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005494
Jim Ingham77787032011-01-20 02:03:18 +00005495 {
Sean Callanana46ec452012-07-11 21:31:24 +00005496 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5497 // restored on exit to the function.
5498 //
5499 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5500 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005501
Sean Callanana46ec452012-07-11 21:31:24 +00005502 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005503
Jim Inghamf48169b2010-11-30 02:22:11 +00005504 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005505 {
5506 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005507 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005508 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005509 thread->GetIndexID(),
5510 thread->GetID(),
5511 s.GetData());
5512 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005513
Sean Callanana46ec452012-07-11 21:31:24 +00005514 bool got_event;
5515 lldb::EventSP event_sp;
5516 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005517
Sean Callanana46ec452012-07-11 21:31:24 +00005518 TimeValue* timeout_ptr = NULL;
5519 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005520
Jim Ingham0161b492013-02-09 01:29:05 +00005521 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 +00005522 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005523 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005524 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005525
Jim Ingham0161b492013-02-09 01:29:05 +00005526 // This is just for accounting:
5527 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005528
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005529 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005530 uint32_t one_thread_timeout_usec;
5531 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005532
5533 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5534 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5535 // first timeout already.
5536
5537 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005538 {
5539 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005540 one_thread_timeout_usec = 0;
5541 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005542 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005543 else
Jim Ingham0161b492013-02-09 01:29:05 +00005544 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005545 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005546
Jim Ingham914f4e72014-03-28 21:58:28 +00005547 // If the overall wait is forever, then we only need to set the one thread timeout:
5548 if (timeout_usec == 0)
5549 {
Ed Maste801335c2014-03-31 19:28:14 +00005550 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005551 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005552 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005553 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005554 }
Jim Ingham0161b492013-02-09 01:29:05 +00005555 else
5556 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005557 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5558 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5559 uint64_t computed_one_thread_timeout;
5560 if (option_one_thread_timeout != 0)
5561 {
5562 if (timeout_usec < option_one_thread_timeout)
5563 {
5564 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005565 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005566 }
5567 computed_one_thread_timeout = option_one_thread_timeout;
5568 }
5569 else
5570 {
5571 computed_one_thread_timeout = timeout_usec / 2;
5572 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5573 computed_one_thread_timeout = default_one_thread_timeout_usec;
5574 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005575 one_thread_timeout_usec = computed_one_thread_timeout;
5576 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5577
Jim Ingham0161b492013-02-09 01:29:05 +00005578 }
Jim Ingham0161b492013-02-09 01:29:05 +00005579 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005580
5581 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005582 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 +00005583 options.GetStopOthers(),
5584 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005585 before_first_timeout,
5586 one_thread_timeout_usec,
5587 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005588
Jim Ingham1460e4b2014-01-10 23:46:59 +00005589 // This isn't going to work if there are unfetched events on the queue.
5590 // Are there cases where we might want to run the remaining events here, and then try to
5591 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005592
Jim Ingham1460e4b2014-01-10 23:46:59 +00005593 Event *other_events = listener.PeekAtNextEvent();
5594 if (other_events != NULL)
5595 {
5596 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005597 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005598 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005599
Jim Ingham1460e4b2014-01-10 23:46:59 +00005600 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5601 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5602 // event coalescing to cause us to lose OUR running event...
5603 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005604
Jim Ingham8559a352012-11-26 23:52:18 +00005605 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5606 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005607
5608#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5609 // It's pretty much impossible to write test cases for things like:
5610 // One thread timeout expires, I go to halt, but the process already stopped
5611 // on the function call stop breakpoint. Turning on this define will make us not
5612 // fetch the first event till after the halt. So if you run a quick function, it will have
5613 // completed, and the completion event will be waiting, when you interrupt for halt.
5614 // The expression evaluation should still succeed.
5615 bool miss_first_event = true;
5616#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005617 TimeValue one_thread_timeout;
5618 TimeValue final_timeout;
5619
Jim Ingham35878c42014-04-08 21:33:21 +00005620
Sean Callanana46ec452012-07-11 21:31:24 +00005621 while (1)
5622 {
5623 // We usually want to resume the process if we get to the top of the loop.
5624 // The only exception is if we get two running events with no intervening
5625 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005626 if (log)
5627 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5628 do_resume,
5629 handle_running_event,
5630 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005631
Jim Ingham184e9812013-01-15 02:47:48 +00005632 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005633 {
5634 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005635
Jim Ingham184e9812013-01-15 02:47:48 +00005636 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005637 {
Jim Ingham0161b492013-02-09 01:29:05 +00005638 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005639 Error resume_error = PrivateResume ();
5640 if (!resume_error.Success())
5641 {
Jim Ingham0161b492013-02-09 01:29:05 +00005642 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5643 num_resumes,
5644 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005645 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005646 break;
5647 }
Sean Callanana46ec452012-07-11 21:31:24 +00005648 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005649
Jim Ingham0161b492013-02-09 01:29:05 +00005650 TimeValue resume_timeout = TimeValue::Now();
5651 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005652
Jim Ingham0161b492013-02-09 01:29:05 +00005653 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005654 if (!got_event)
5655 {
5656 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005657 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5658 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005659
Jim Ingham0161b492013-02-09 01:29:05 +00005660 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005661 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005662 break;
5663 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005664
Sean Callanana46ec452012-07-11 21:31:24 +00005665 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005666
Sean Callanana46ec452012-07-11 21:31:24 +00005667 if (stop_state != eStateRunning)
5668 {
Jim Ingham0161b492013-02-09 01:29:05 +00005669 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005670
Jim Ingham0161b492013-02-09 01:29:05 +00005671 if (stop_state == eStateStopped)
5672 {
5673 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5674 if (log)
5675 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5676 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5677 num_resumes,
5678 StateAsCString(stop_state),
5679 restarted,
5680 do_resume,
5681 handle_running_event);
5682 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005683
Jim Ingham0161b492013-02-09 01:29:05 +00005684 if (restarted)
5685 {
5686 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5687 // event here. But if I do, the best thing is to Halt and then get out of here.
5688 Halt();
5689 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005690
Jim Ingham35e1bda2012-10-16 21:41:58 +00005691 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5692 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005693 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005694 break;
5695 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005696
Sean Callanana46ec452012-07-11 21:31:24 +00005697 if (log)
5698 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5699 // We need to call the function synchronously, so spin waiting for it to return.
5700 // If we get interrupted while executing, we're going to lose our context, and
5701 // won't be able to gather the result at this point.
5702 // We set the timeout AFTER the resume, since the resume takes some time and we
5703 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005704 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005705 else
5706 {
Sean Callanana46ec452012-07-11 21:31:24 +00005707 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005708 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005709 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005710
Jim Ingham0161b492013-02-09 01:29:05 +00005711 if (before_first_timeout)
5712 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005713 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005714 {
5715 one_thread_timeout = TimeValue::Now();
5716 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005717 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005718 }
Jim Ingham0161b492013-02-09 01:29:05 +00005719 else
5720 {
5721 if (timeout_usec == 0)
5722 timeout_ptr = NULL;
5723 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005724 {
5725 final_timeout = TimeValue::Now();
5726 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005727 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005728 }
Jim Ingham0161b492013-02-09 01:29:05 +00005729 }
5730 }
5731 else
5732 {
5733 if (timeout_usec == 0)
5734 timeout_ptr = NULL;
5735 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005736 {
5737 final_timeout = TimeValue::Now();
5738 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005739 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005740 }
Jim Ingham0161b492013-02-09 01:29:05 +00005741 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005742
Jim Ingham0161b492013-02-09 01:29:05 +00005743 do_resume = true;
5744 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005745
Sean Callanana46ec452012-07-11 21:31:24 +00005746 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005747 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005748
Jim Ingham0f16e732011-02-08 05:20:59 +00005749 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005750 {
Sean Callanana46ec452012-07-11 21:31:24 +00005751 if (timeout_ptr)
5752 {
Matt Kopec676a4872013-02-21 23:55:31 +00005753 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005754 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5755 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005756 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005757 else
Sean Callanana46ec452012-07-11 21:31:24 +00005758 {
5759 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5760 }
5761 }
Jim Ingham35878c42014-04-08 21:33:21 +00005762
5763#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5764 // See comment above...
5765 if (miss_first_event)
5766 {
5767 usleep(1000);
5768 miss_first_event = false;
5769 got_event = false;
5770 }
5771 else
5772#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005773 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005774
Sean Callanana46ec452012-07-11 21:31:24 +00005775 if (got_event)
5776 {
5777 if (event_sp.get())
5778 {
5779 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005780 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005781 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005782 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005783 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005784 errors.Printf ("Execution halted by user interrupt.");
5785 if (log)
5786 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005787 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005788 }
5789 else
5790 {
5791 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5792 if (log)
5793 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005794
Jim Inghamcfc09352012-07-27 23:57:19 +00005795 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005796 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005797 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005798 {
Jim Ingham0161b492013-02-09 01:29:05 +00005799 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005800 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5801 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005802 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005803 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005804 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005805 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005806 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005807 }
5808 else
5809 {
Jim Ingham0161b492013-02-09 01:29:05 +00005810 // If we were restarted, we just need to go back up to fetch another event.
5811 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005812 {
5813 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005814 {
5815 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5816 }
5817 keep_going = true;
5818 do_resume = false;
5819 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005820
Jim Inghamcfc09352012-07-27 23:57:19 +00005821 }
5822 else
5823 {
Jim Ingham0161b492013-02-09 01:29:05 +00005824 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5825 StopReason stop_reason = eStopReasonInvalid;
5826 if (stop_info_sp)
5827 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005828
Jim Ingham0161b492013-02-09 01:29:05 +00005829 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5830 // it is OUR plan that is complete?
5831 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005832 {
5833 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005834 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5835 // Now mark this plan as private so it doesn't get reported as the stop reason
5836 // after this point.
5837 if (thread_plan_sp)
5838 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005839 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005840 }
5841 else
5842 {
Jim Ingham0161b492013-02-09 01:29:05 +00005843 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005844 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005845 {
5846 if (log)
5847 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005848 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005849 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005850 {
5851 event_to_broadcast_sp = event_sp;
5852 }
Jim Ingham0161b492013-02-09 01:29:05 +00005853 }
Jim Ingham184e9812013-01-15 02:47:48 +00005854 else
Jim Ingham0161b492013-02-09 01:29:05 +00005855 {
5856 if (log)
5857 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005858 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005859 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005860 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005861 }
Jim Ingham184e9812013-01-15 02:47:48 +00005862 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005863 }
Sean Callanana46ec452012-07-11 21:31:24 +00005864 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005865 }
5866 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005867
Jim Inghamcfc09352012-07-27 23:57:19 +00005868 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005869 // This shouldn't really happen, but sometimes we do get two running events without an
5870 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005871 do_resume = false;
5872 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005873 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005874 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005875
Jim Inghamcfc09352012-07-27 23:57:19 +00005876 default:
5877 if (log)
5878 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005879
Jim Inghamcfc09352012-07-27 23:57:19 +00005880 if (stop_state == eStateExited)
5881 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005882
Sean Callananbf154da2012-08-08 17:35:10 +00005883 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005884 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005885 break;
5886 }
Sean Callanana46ec452012-07-11 21:31:24 +00005887 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005888
Sean Callanana46ec452012-07-11 21:31:24 +00005889 if (keep_going)
5890 continue;
5891 else
5892 break;
5893 }
5894 else
5895 {
5896 if (log)
5897 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005898 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005899 break;
5900 }
5901 }
5902 else
5903 {
5904 // If we didn't get an event that means we've timed out...
5905 // We will interrupt the process here. Depending on what we were asked to do we will
5906 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005907
Sean Callanana46ec452012-07-11 21:31:24 +00005908 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005909 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005910 {
Jim Ingham0161b492013-02-09 01:29:05 +00005911 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005912 {
5913 if (timeout_usec != 0)
5914 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005915 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005916 "running for %" PRIu32 " usec with all threads enabled.",
5917 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005918 }
5919 else
5920 {
5921 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005922 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005923 }
5924 }
Sean Callanana46ec452012-07-11 21:31:24 +00005925 else
5926 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005927 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005928 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005929 }
5930 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005931 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005932 "abandoning execution.",
5933 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005934 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005935
Jim Ingham0161b492013-02-09 01:29:05 +00005936 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5937 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5938 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5939 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5940 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005941
Jim Ingham0161b492013-02-09 01:29:05 +00005942 bool back_to_top = true;
5943 uint32_t try_halt_again = 0;
5944 bool do_halt = true;
5945 const uint32_t num_retries = 5;
5946 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005947 {
Jim Ingham0161b492013-02-09 01:29:05 +00005948 Error halt_error;
5949 if (do_halt)
5950 {
5951 if (log)
5952 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5953 halt_error = Halt();
5954 }
5955 if (halt_error.Success())
5956 {
5957 if (log)
5958 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005959
Jim Ingham0161b492013-02-09 01:29:05 +00005960 real_timeout = TimeValue::Now();
5961 real_timeout.OffsetWithMicroSeconds(500000);
5962
5963 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005964
Jim Ingham0161b492013-02-09 01:29:05 +00005965 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005966 {
Jim Ingham0161b492013-02-09 01:29:05 +00005967 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5968 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005969 {
Jim Ingham0161b492013-02-09 01:29:05 +00005970 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5971 if (stop_state == lldb::eStateStopped
5972 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5973 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005974 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005975
Jim Ingham0161b492013-02-09 01:29:05 +00005976 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005977 {
Jim Ingham0161b492013-02-09 01:29:05 +00005978 // Between the time we initiated the Halt and the time we delivered it, the process could have
5979 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005980
Jim Ingham0161b492013-02-09 01:29:05 +00005981 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5982 {
5983 if (log)
5984 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5985 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005986 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005987 back_to_top = false;
5988 break;
5989 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005990
Jim Ingham0161b492013-02-09 01:29:05 +00005991 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5992 {
5993 if (log)
5994 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5995 "Exiting wait loop.");
5996 try_halt_again++;
5997 do_halt = false;
5998 continue;
5999 }
Sean Callanana46ec452012-07-11 21:31:24 +00006000
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006001 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00006002 {
6003 if (log)
6004 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006005 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006006 back_to_top = false;
6007 break;
6008 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006009
Jim Ingham0161b492013-02-09 01:29:05 +00006010 if (before_first_timeout)
6011 {
6012 // Set all the other threads to run, and return to the top of the loop, which will continue;
6013 before_first_timeout = false;
6014 thread_plan_sp->SetStopOthers (false);
6015 if (log)
6016 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00006017
Jim Ingham0161b492013-02-09 01:29:05 +00006018 back_to_top = true;
6019 break;
6020 }
6021 else
6022 {
6023 // Running all threads failed, so return Interrupted.
6024 if (log)
6025 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006026 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006027 back_to_top = false;
6028 break;
6029 }
Sean Callanana46ec452012-07-11 21:31:24 +00006030 }
6031 }
6032 else
Jim Ingham0161b492013-02-09 01:29:05 +00006033 { if (log)
6034 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
6035 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006036 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006037 back_to_top = false;
6038 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006039 }
6040 }
Jim Ingham0161b492013-02-09 01:29:05 +00006041 else
6042 {
6043 try_halt_again++;
6044 continue;
6045 }
Sean Callanana46ec452012-07-11 21:31:24 +00006046 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006047
Jim Ingham0161b492013-02-09 01:29:05 +00006048 if (!back_to_top || try_halt_again > num_retries)
6049 break;
6050 else
6051 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006052 }
Sean Callanana46ec452012-07-11 21:31:24 +00006053 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006054
Sean Callanana46ec452012-07-11 21:31:24 +00006055 // 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 +00006056 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006057 {
6058 StopPrivateStateThread();
6059 Error error;
6060 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006061 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006062 {
6063 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6064 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006065 if (old_state != eStateInvalid)
6066 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006067 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006068
Jim Ingham184e9812013-01-15 02:47:48 +00006069 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6070 // could happen:
6071 // 1) The execution successfully completed
6072 // 2) We hit a breakpoint, and ignore_breakpoints was true
6073 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006074 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6075 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006076
Jim Ingham8646d3c2014-05-05 02:47:44 +00006077 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006078 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006079 {
6080 thread_plan_sp->RestoreThreadState();
6081 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006082
Sean Callanana46ec452012-07-11 21:31:24 +00006083 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006084 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006085 {
6086 if (log)
6087 {
6088 StreamString s;
6089 if (event_sp)
6090 event_sp->Dump (&s);
6091 else
6092 {
6093 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6094 }
6095
6096 StreamString ts;
6097
6098 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006099
Sean Callanana46ec452012-07-11 21:31:24 +00006100 do
6101 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006102 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006103 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006104 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006105 break;
6106 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006107 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006108 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006109 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006110 break;
6111 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006112 else
Sean Callanana46ec452012-07-11 21:31:24 +00006113 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006114 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6115
6116 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006117 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006118 event_explanation = "<no event data>";
6119 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006120 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006121
Jim Inghamcfc09352012-07-27 23:57:19 +00006122 Process *process = event_data->GetProcessSP().get();
6123
6124 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006125 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006126 event_explanation = "<no process>";
6127 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006128 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006129
Jim Inghamcfc09352012-07-27 23:57:19 +00006130 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006131
Jim Inghamcfc09352012-07-27 23:57:19 +00006132 uint32_t num_threads = thread_list.GetSize();
6133 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006134
Jim Inghamcfc09352012-07-27 23:57:19 +00006135 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006136
Jim Inghamcfc09352012-07-27 23:57:19 +00006137 for (thread_index = 0;
6138 thread_index < num_threads;
6139 ++thread_index)
6140 {
6141 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006142
Jim Inghamcfc09352012-07-27 23:57:19 +00006143 if (!thread)
6144 {
6145 ts.Printf("<?> ");
6146 continue;
6147 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006148
Daniel Malead01b2952012-11-29 21:49:15 +00006149 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006150 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006151
Jim Inghamcfc09352012-07-27 23:57:19 +00006152 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006153 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006154 else
6155 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006156
Jim Inghamcfc09352012-07-27 23:57:19 +00006157 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6158 if (stop_info_sp)
6159 {
6160 const char *stop_desc = stop_info_sp->GetDescription();
6161 if (stop_desc)
6162 ts.PutCString (stop_desc);
6163 }
6164 ts.Printf(">");
6165 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006166
Jim Inghamcfc09352012-07-27 23:57:19 +00006167 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006168 }
Sean Callanana46ec452012-07-11 21:31:24 +00006169 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006170
Jim Inghamcfc09352012-07-27 23:57:19 +00006171 if (event_explanation)
6172 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006173 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006174 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6175 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006176
Jim Inghame4483cf2013-09-27 01:13:01 +00006177 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006178 {
6179 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006180 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6181 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006182 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6183 thread_plan_sp->SetPrivate (orig_plan_private);
6184 }
6185 else
6186 {
6187 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006188 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6189 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006190 }
6191 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006192 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006193 {
6194 if (log)
6195 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006196
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006197 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006198 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006199 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006200 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006201 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006202 }
6203 else
6204 {
Sean Callanana46ec452012-07-11 21:31:24 +00006205 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006206 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006207 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006208 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006209 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006210 }
6211 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6212 {
6213 if (log)
6214 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006215 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006216 }
6217 else
6218 {
6219 if (log)
6220 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006221 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006222 {
6223 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006224 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006225 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6226 thread_plan_sp->SetPrivate (orig_plan_private);
6227 }
6228 }
6229 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006230
Sean Callanana46ec452012-07-11 21:31:24 +00006231 // Thread we ran the function in may have gone away because we ran the target
6232 // Check that it's still there, and if it is put it back in the context. Also restore the
6233 // frame in the context if it is still present.
6234 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6235 if (thread)
6236 {
6237 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6238 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006239
Sean Callanana46ec452012-07-11 21:31:24 +00006240 // Also restore the current process'es selected frame & thread, since this function calling may
6241 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006242
Sean Callanana46ec452012-07-11 21:31:24 +00006243 if (selected_tid != LLDB_INVALID_THREAD_ID)
6244 {
6245 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6246 {
6247 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006248 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006249 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006250 if (old_frame_sp)
6251 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006252 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006253 }
6254 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006255
Sean Callanana46ec452012-07-11 21:31:24 +00006256 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006257
Sean Callanana46ec452012-07-11 21:31:24 +00006258 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006259 {
Sean Callanana46ec452012-07-11 21:31:24 +00006260 if (log)
6261 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6262 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006263 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006264
Jim Inghamf48169b2010-11-30 02:22:11 +00006265 return return_value;
6266}
6267
6268const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006269Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006270{
6271 const char *result_name;
6272
6273 switch (result)
6274 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006275 case eExpressionCompleted:
6276 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006277 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006278 case eExpressionDiscarded:
6279 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006280 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006281 case eExpressionInterrupted:
6282 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006283 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006284 case eExpressionHitBreakpoint:
6285 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006286 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006287 case eExpressionSetupError:
6288 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006289 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006290 case eExpressionParseError:
6291 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006292 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006293 case eExpressionResultUnavailable:
6294 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006295 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006296 case eExpressionTimedOut:
6297 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006298 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006299 case eExpressionStoppedForDebug:
6300 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006301 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006302 }
6303 return result_name;
6304}
6305
Greg Clayton7260f622011-04-18 08:33:37 +00006306void
6307Process::GetStatus (Stream &strm)
6308{
6309 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006310 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006311 {
6312 if (state == eStateExited)
6313 {
6314 int exit_status = GetExitStatus();
6315 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006316 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006317 GetID(),
6318 exit_status,
6319 exit_status,
6320 exit_description ? exit_description : "");
6321 }
6322 else
6323 {
6324 if (state == eStateConnected)
6325 strm.Printf ("Connected to remote target.\n");
6326 else
Daniel Malead01b2952012-11-29 21:49:15 +00006327 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006328 }
6329 }
6330 else
6331 {
Daniel Malead01b2952012-11-29 21:49:15 +00006332 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006333 }
6334}
6335
6336size_t
6337Process::GetThreadStatus (Stream &strm,
6338 bool only_threads_with_stop_reason,
6339 uint32_t start_frame,
6340 uint32_t num_frames,
6341 uint32_t num_frames_with_source)
6342{
6343 size_t num_thread_infos_dumped = 0;
6344
Jim Ingham4a65fb12014-03-07 11:20:03 +00006345 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6346 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6347 // ID's, and look them up one by one:
6348
6349 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006350 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006351 //Scope for thread list locker;
6352 {
6353 Mutex::Locker locker (GetThreadList().GetMutex());
6354 ThreadList &curr_thread_list = GetThreadList();
6355 num_threads = curr_thread_list.GetSize();
6356 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006357 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006358 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006359 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006360 }
6361
Greg Clayton7260f622011-04-18 08:33:37 +00006362 for (uint32_t i = 0; i < num_threads; i++)
6363 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006364 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006365 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006366 {
6367 if (only_threads_with_stop_reason)
6368 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006369 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006370 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006371 continue;
6372 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006373 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006374 start_frame,
6375 num_frames,
6376 num_frames_with_source);
6377 ++num_thread_infos_dumped;
6378 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006379 else
6380 {
6381 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6382 if (log)
6383 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6384
6385 }
Greg Clayton7260f622011-04-18 08:33:37 +00006386 }
6387 return num_thread_infos_dumped;
6388}
6389
Greg Claytona9f40ad2012-02-22 04:37:26 +00006390void
6391Process::AddInvalidMemoryRegion (const LoadRange &region)
6392{
6393 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6394}
6395
6396bool
6397Process::RemoveInvalidMemoryRange (const LoadRange &region)
6398{
6399 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6400}
6401
Jim Ingham372787f2012-04-07 00:00:41 +00006402void
6403Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6404{
6405 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6406}
6407
6408bool
6409Process::RunPreResumeActions ()
6410{
6411 bool result = true;
6412 while (!m_pre_resume_actions.empty())
6413 {
6414 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6415 m_pre_resume_actions.pop_back();
6416 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006417 if (result == true)
6418 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006419 }
6420 return result;
6421}
6422
6423void
6424Process::ClearPreResumeActions ()
6425{
6426 m_pre_resume_actions.clear();
6427}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006428
Zachary Turner93749ab2015-03-03 21:51:25 +00006429ProcessRunLock &
6430Process::GetRunLock()
6431{
6432 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6433 return m_private_run_lock;
6434 else
6435 return m_public_run_lock;
6436}
6437
Greg Claytonfa559e52012-05-18 02:38:05 +00006438void
6439Process::Flush ()
6440{
6441 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006442 m_extended_thread_list.Flush();
6443 m_extended_thread_stop_id = 0;
6444 m_queue_list.Clear();
6445 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006446}
Greg Clayton90ba8112012-12-05 00:16:59 +00006447
6448void
6449Process::DidExec ()
6450{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006451 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6452 if (log)
6453 log->Printf ("Process::%s()", __FUNCTION__);
6454
Greg Clayton90ba8112012-12-05 00:16:59 +00006455 Target &target = GetTarget();
6456 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006457 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006458 m_dynamic_checkers_ap.reset();
6459 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006460 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006461 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006462 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006463 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006464 m_image_tokens.clear();
6465 m_allocated_memory_cache.Clear();
6466 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006467 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006468 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006469 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006470 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006471 DoDidExec();
6472 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006473 // Flush the process (threads and all stack frames) after running CompleteAttach()
6474 // in case the dynamic loader loaded things in new locations.
6475 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006476
6477 // After we figure out what was loaded/unloaded in CompleteAttach,
6478 // we need to let the target know so it can do any cleanup it needs to.
6479 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006480}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006481
Jim Ingham1460e4b2014-01-10 23:46:59 +00006482addr_t
6483Process::ResolveIndirectFunction(const Address *address, Error &error)
6484{
6485 if (address == nullptr)
6486 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006487 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006488 return LLDB_INVALID_ADDRESS;
6489 }
6490
6491 addr_t function_addr = LLDB_INVALID_ADDRESS;
6492
6493 addr_t addr = address->GetLoadAddress(&GetTarget());
6494 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6495 if (iter != m_resolved_indirect_addresses.end())
6496 {
6497 function_addr = (*iter).second;
6498 }
6499 else
6500 {
6501 if (!InferiorCall(this, address, function_addr))
6502 {
6503 Symbol *symbol = address->CalculateSymbolContextSymbol();
6504 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6505 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6506 function_addr = LLDB_INVALID_ADDRESS;
6507 }
6508 else
6509 {
6510 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6511 }
6512 }
6513 return function_addr;
6514}
6515
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006516void
6517Process::ModulesDidLoad (ModuleList &module_list)
6518{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006519 SystemRuntime *sys_runtime = GetSystemRuntime();
6520 if (sys_runtime)
6521 {
6522 sys_runtime->ModulesDidLoad (module_list);
6523 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006524
Kuba Breckaafdf8422014-10-10 23:43:03 +00006525 GetJITLoaders().ModulesDidLoad (module_list);
6526
6527 // Give runtimes a chance to be created.
6528 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6529
6530 // Tell runtimes about new modules.
6531 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6532 {
6533 InstrumentationRuntimeSP runtime = pos->second;
6534 runtime->ModulesDidLoad(module_list);
6535 }
6536
Greg Clayton35ca64b2015-04-16 17:13:34 +00006537 // Let any language runtimes we have already created know
6538 // about the modules that loaded.
6539
6540 // Iterate over a copy of this language runtime list in case
6541 // the language runtime ModulesDidLoad somehow causes the language
6542 // riuntime to be unloaded.
6543 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6544 for (const auto &pair: language_runtimes)
6545 {
6546 // We must check language_runtime_sp to make sure it is not
6547 // NULL as we might cache the fact that we didn't have a
6548 // language runtime for a language.
6549 LanguageRuntimeSP language_runtime_sp = pair.second;
6550 if (language_runtime_sp)
6551 language_runtime_sp->ModulesDidLoad(module_list);
6552 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006553}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006554
Jason Molendaef7d6412015-08-06 03:27:10 +00006555void
6556Process::PrintWarning (uint64_t warning_type, void *repeat_key, const char *fmt, ...)
6557{
6558 bool print_warning = true;
6559
6560 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
6561 if (stream_sp.get() == nullptr)
6562 return;
6563 if (warning_type == eWarningsOptimization
6564 && GetWarningsOptimization() == false)
6565 {
6566 return;
6567 }
6568
6569 if (repeat_key != nullptr)
6570 {
6571 WarningsCollection::iterator it = m_warnings_issued.find (warning_type);
6572 if (it == m_warnings_issued.end())
6573 {
6574 m_warnings_issued[warning_type] = WarningsPointerSet();
6575 m_warnings_issued[warning_type].insert (repeat_key);
6576 }
6577 else
6578 {
6579 if (it->second.find (repeat_key) != it->second.end())
6580 {
6581 print_warning = false;
6582 }
6583 else
6584 {
6585 it->second.insert (repeat_key);
6586 }
6587 }
6588 }
6589
6590 if (print_warning)
6591 {
6592 va_list args;
6593 va_start (args, fmt);
6594 stream_sp->PrintfVarArg (fmt, args);
6595 va_end (args);
6596 }
6597}
6598
Kuba Breckaa51ea382014-09-06 01:33:13 +00006599ThreadCollectionSP
6600Process::GetHistoryThreads(lldb::addr_t addr)
6601{
6602 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006603
Kuba Breckaa51ea382014-09-06 01:33:13 +00006604 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6605
6606 if (! memory_history.get()) {
6607 return threads;
6608 }
6609
6610 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6611
6612 return threads;
6613}
Kuba Brecka63927542014-10-11 01:59:32 +00006614
6615InstrumentationRuntimeSP
6616Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6617{
6618 InstrumentationRuntimeCollection::iterator pos;
6619 pos = m_instrumentation_runtimes.find (type);
6620 if (pos == m_instrumentation_runtimes.end())
6621 {
6622 return InstrumentationRuntimeSP();
6623 }
6624 else
6625 return (*pos).second;
6626}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006627
6628bool
6629Process::GetModuleSpec(const FileSpec& module_file_spec,
6630 const ArchSpec& arch,
6631 ModuleSpec& module_spec)
6632{
6633 module_spec.Clear();
6634 return false;
6635}