blob: 41942829ca55826ae1df8ff515540e29adeeda7c [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" },
Greg Clayton67cc0632012-08-22 17:17:09 +0000118 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
119};
120
121enum {
122 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000123 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000124 ePropertyIgnoreBreakpointsInExpressions,
125 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000126 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000127 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000128 ePropertyDetachKeepsStopped,
129 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09 +0000130};
131
Greg Clayton332e8b12015-01-13 21:13:08 +0000132ProcessProperties::ProcessProperties (lldb_private::Process *process) :
133 Properties (),
134 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000135{
Greg Clayton332e8b12015-01-13 21:13:08 +0000136 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000137 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000138 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000139 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
140 m_collection_sp->Initialize(g_properties);
141 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000142 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000143 true,
144 Thread::GetGlobalProperties()->GetValueProperties());
145 }
146 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000147 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000148 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000149 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
150 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000151}
152
153ProcessProperties::~ProcessProperties()
154{
155}
156
Greg Clayton332e8b12015-01-13 21:13:08 +0000157void
158ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
159{
160 ProcessProperties *properties = (ProcessProperties *)baton;
161 if (properties->m_process)
162 properties->m_process->LoadOperatingSystemPlugin(true);
163}
164
Greg Clayton67cc0632012-08-22 17:17:09 +0000165bool
166ProcessProperties::GetDisableMemoryCache() const
167{
168 const uint32_t idx = ePropertyDisableMemCache;
169 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
170}
171
Jason Molendaf0340c92014-09-03 22:30:54 +0000172uint64_t
173ProcessProperties::GetMemoryCacheLineSize() const
174{
175 const uint32_t idx = ePropertyMemCacheLineSize;
176 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
177}
178
Greg Clayton67cc0632012-08-22 17:17:09 +0000179Args
180ProcessProperties::GetExtraStartupCommands () const
181{
182 Args args;
183 const uint32_t idx = ePropertyExtraStartCommand;
184 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
185 return args;
186}
187
188void
189ProcessProperties::SetExtraStartupCommands (const Args &args)
190{
191 const uint32_t idx = ePropertyExtraStartCommand;
192 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
193}
194
Greg Claytonc9d645d2012-10-18 22:40:37 +0000195FileSpec
196ProcessProperties::GetPythonOSPluginPath () const
197{
198 const uint32_t idx = ePropertyPythonOSPluginPath;
199 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
200}
201
202void
203ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
204{
205 const uint32_t idx = ePropertyPythonOSPluginPath;
206 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
207}
208
Jim Ingham184e9812013-01-15 02:47:48 +0000209
210bool
211ProcessProperties::GetIgnoreBreakpointsInExpressions () const
212{
213 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
214 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
215}
216
217void
218ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
219{
220 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
221 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
222}
223
224bool
225ProcessProperties::GetUnwindOnErrorInExpressions () const
226{
227 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
228 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
229}
230
231void
232ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
233{
234 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
235 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
236}
237
Jim Ingham29950772013-01-26 02:19:28 +0000238bool
239ProcessProperties::GetStopOnSharedLibraryEvents () const
240{
241 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
243}
244
245void
246ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
247{
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
249 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
250}
251
Jim Inghamacff8952013-05-02 00:27:30 +0000252bool
253ProcessProperties::GetDetachKeepsStopped () const
254{
255 const uint32_t idx = ePropertyDetachKeepsStopped;
256 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
257}
258
259void
260ProcessProperties::SetDetachKeepsStopped (bool stop)
261{
262 const uint32_t idx = ePropertyDetachKeepsStopped;
263 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
264}
265
Greg Clayton32e0a752011-03-30 18:16:51 +0000266void
Greg Clayton8b82f082011-04-12 05:54:46 +0000267ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000268{
269 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000270 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000271 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000272
273 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000274 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000275
276 if (m_executable)
277 {
278 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
279 s.PutCString (" file = ");
280 m_executable.Dump(&s);
281 s.EOL();
282 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000284 if (argc > 0)
285 {
286 for (uint32_t i=0; i<argc; i++)
287 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000289 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 }
294 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000295
296 const uint32_t envc = m_environment.GetArgumentCount();
297 if (envc > 0)
298 {
299 for (uint32_t i=0; i<envc; i++)
300 {
301 const char *env = m_environment.GetArgumentAtIndex(i);
302 if (i < 10)
303 s.Printf (" env[%u] = %s\n", i, env);
304 else
305 s.Printf ("env[%u] = %s\n", i, env);
306 }
307 }
308
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000309 if (m_arch.IsValid())
310 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
311
Greg Clayton8b82f082011-04-12 05:54:46 +0000312 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000313 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000314 cstr = platform->GetUserName (m_uid);
315 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000316 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000317 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000318 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000319 cstr = platform->GetGroupName (m_gid);
320 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000321 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000322 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000323 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000324 cstr = platform->GetUserName (m_euid);
325 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000326 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000327 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000328 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000329 cstr = platform->GetGroupName (m_egid);
330 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000331 }
332}
333
334void
Greg Clayton8b82f082011-04-12 05:54:46 +0000335ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000336{
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 const char *label;
338 if (show_args || verbose)
339 label = "ARGUMENTS";
340 else
341 label = "NAME";
342
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000343 if (verbose)
344 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000345 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000346 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
347 }
348 else
349 {
Jim Ingham368ac222014-08-15 17:05:27 +0000350 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
351 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000352 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000353}
354
355void
Greg Clayton8b82f082011-04-12 05:54:46 +0000356ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000357{
358 if (m_pid != LLDB_INVALID_PROCESS_ID)
359 {
360 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000361 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000362
Greg Clayton32e0a752011-03-30 18:16:51 +0000363
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000364 if (verbose)
365 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000366 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000367 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
368 s.Printf ("%-10s ", cstr);
369 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000371
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
374 s.Printf ("%-10s ", cstr);
375 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000376 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000377
Greg Clayton8b82f082011-04-12 05:54:46 +0000378 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000379 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
380 s.Printf ("%-10s ", cstr);
381 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000382 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383
Greg Clayton8b82f082011-04-12 05:54:46 +0000384 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000385 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
386 s.Printf ("%-10s ", cstr);
387 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000388 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000389 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
390 }
391 else
392 {
Jim Ingham368ac222014-08-15 17:05:27 +0000393 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000394 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000395 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000396 }
397
Greg Clayton8b82f082011-04-12 05:54:46 +0000398 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000399 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000400 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000401 if (argc > 0)
402 {
403 for (uint32_t i=0; i<argc; i++)
404 {
405 if (i > 0)
406 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000407 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000408 }
409 }
410 }
411 else
412 {
413 s.PutCString (GetName());
414 }
415
416 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000417 }
418}
419
Greg Clayton8b82f082011-04-12 05:54:46 +0000420Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000421ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000422{
423 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000424 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000425
426 switch (short_option)
427 {
428 case 's': // Stop at program entry point
429 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
430 break;
431
Greg Clayton8b82f082011-04-12 05:54:46 +0000432 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000433 {
434 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000435 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000436 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000437 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000438 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000439
440 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000441 {
442 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000443 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000444 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000445 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000446 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000447
448 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000449 {
450 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000451 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000452 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000453 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000454 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000455
Greg Clayton8b82f082011-04-12 05:54:46 +0000456 case 'p': // Process plug-in name
457 launch_info.SetProcessPluginName (option_arg);
458 break;
459
460 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000461 {
462 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000463 const FileSpec dev_null{"/dev/null", false};
464 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000465 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000466 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000467 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000468 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000469 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000470 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000471 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000472
473 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000474 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 break;
476
477 case 't': // Open process in new terminal window
478 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
479 break;
480
481 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000482 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
483 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000484 break;
485
Todd Fiala51637922014-08-19 17:40:43 +0000486 case 'A': // Disable ASLR.
487 {
488 bool success;
489 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
490 if (success)
491 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
492 else
493 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 break;
Todd Fiala51637922014-08-19 17:40:43 +0000495 }
496
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000497 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000498 {
499 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000500 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000501 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000502 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000503 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000504 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000505 break;
506 }
507
Todd Fiala51637922014-08-19 17:40:43 +0000508 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000509 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000510 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000511 else
Zachary Turner10687b02014-10-20 17:46:43 +0000512 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000513 break;
514
Greg Clayton8b82f082011-04-12 05:54:46 +0000515 case 'v':
516 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
517 break;
518
519 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000520 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000521 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000522 }
523 return error;
524}
525
526OptionDefinition
527ProcessLaunchCommandOptions::g_option_table[] =
528{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000529{ 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 +0000530{ 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 +0000531{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
532{ 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."},
533{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
534{ 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 +0000535{ 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 +0000536
Zachary Turnerd37221d2014-07-09 16:31:49 +0000537{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
538{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
539{ 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 +0000540
Zachary Turnerd37221d2014-07-09 16:31:49 +0000541{ 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 +0000542
Zachary Turnerd37221d2014-07-09 16:31:49 +0000543{ 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 +0000544{ 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 +0000545{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000546};
547
548
549
550bool
551ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000552{
553 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
554 return true;
555 const char *match_name = m_match_info.GetName();
556 if (!match_name)
557 return true;
558
559 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
560}
561
562bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000563ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000564{
565 if (!NameMatches (proc_info.GetName()))
566 return false;
567
568 if (m_match_info.ProcessIDIsValid() &&
569 m_match_info.GetProcessID() != proc_info.GetProcessID())
570 return false;
571
572 if (m_match_info.ParentProcessIDIsValid() &&
573 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
574 return false;
575
Greg Clayton8b82f082011-04-12 05:54:46 +0000576 if (m_match_info.UserIDIsValid () &&
577 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000578 return false;
579
Greg Clayton8b82f082011-04-12 05:54:46 +0000580 if (m_match_info.GroupIDIsValid () &&
581 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000582 return false;
583
584 if (m_match_info.EffectiveUserIDIsValid () &&
585 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
586 return false;
587
588 if (m_match_info.EffectiveGroupIDIsValid () &&
589 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
590 return false;
591
592 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000593 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000594 return false;
595 return true;
596}
597
598bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000599ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000600{
601 if (m_name_match_type != eNameMatchIgnore)
602 return false;
603
604 if (m_match_info.ProcessIDIsValid())
605 return false;
606
607 if (m_match_info.ParentProcessIDIsValid())
608 return false;
609
Greg Clayton8b82f082011-04-12 05:54:46 +0000610 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000611 return false;
612
Greg Clayton8b82f082011-04-12 05:54:46 +0000613 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000614 return false;
615
616 if (m_match_info.EffectiveUserIDIsValid ())
617 return false;
618
619 if (m_match_info.EffectiveGroupIDIsValid ())
620 return false;
621
622 if (m_match_info.GetArchitecture().IsValid())
623 return false;
624
625 if (m_match_all_users)
626 return false;
627
628 return true;
629
630}
631
632void
Greg Clayton8b82f082011-04-12 05:54:46 +0000633ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000634{
635 m_match_info.Clear();
636 m_name_match_type = eNameMatchIgnore;
637 m_match_all_users = false;
638}
Greg Clayton58be07b2011-01-07 06:08:19 +0000639
Greg Claytonc3776bf2012-02-09 06:16:32 +0000640ProcessSP
641Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642{
Greg Clayton949e8222013-01-16 17:29:04 +0000643 static uint32_t g_process_unique_id = 0;
644
Greg Claytonc3776bf2012-02-09 06:16:32 +0000645 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 ProcessCreateInstance create_callback = NULL;
647 if (plugin_name)
648 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000649 ConstString const_plugin_name(plugin_name);
650 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651 if (create_callback)
652 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000653 process_sp = create_callback(target, listener, crash_file_path);
654 if (process_sp)
655 {
Greg Clayton949e8222013-01-16 17:29:04 +0000656 if (process_sp->CanDebug(target, true))
657 {
658 process_sp->m_process_unique_id = ++g_process_unique_id;
659 }
660 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000661 process_sp.reset();
662 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 }
664 }
665 else
666 {
Greg Claytonc982c762010-07-09 20:39:50 +0000667 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000669 process_sp = create_callback(target, listener, crash_file_path);
670 if (process_sp)
671 {
Greg Clayton949e8222013-01-16 17:29:04 +0000672 if (process_sp->CanDebug(target, false))
673 {
674 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000675 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000676 }
677 else
678 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000679 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 }
681 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000682 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683}
684
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000685ConstString &
686Process::GetStaticBroadcasterClass ()
687{
688 static ConstString class_name ("lldb.process");
689 return class_name;
690}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691
692//----------------------------------------------------------------------
693// Process constructor
694//----------------------------------------------------------------------
695Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000696 Process(target, listener, Host::GetUnixSignals ())
697{
698 // This constructor just delegates to the full Process constructor,
699 // defaulting to using the Host's UnixSignals.
700}
701
702Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000703 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 UserID (LLDB_INVALID_PROCESS_ID),
Ilia K8a00a562015-03-17 16:54:52 +0000705 Broadcaster (&(target.GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707 m_public_state (eStateUnloaded),
708 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000709 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
710 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 m_private_state_listener ("lldb.process.internal_state_listener"),
712 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000713 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000714 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000716 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717 m_exit_status (-1),
718 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000719 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000720 m_thread_mutex (Mutex::eMutexTypeRecursive),
721 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000723 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000724 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000725 m_queue_list (this),
726 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000728 m_image_tokens (),
729 m_listener (listener),
730 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000731 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000732 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000733 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000734 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000735 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000736 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000737 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000738 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000739 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000740 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
741 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32 +0000742 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42 +0000743 m_memory_cache (*this),
744 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000745 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000746 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000747 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000748 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000749 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000750 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58 +0000751 m_finalizing (false),
752 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000753 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000754 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000755 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000756 m_destroy_in_process (false),
757 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000759 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000760
Greg Clayton5160ce52013-03-27 23:08:40 +0000761 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000763 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764
Todd Fiala4ceced32014-08-29 17:35:57 +0000765 if (!m_unix_signals_sp)
766 m_unix_signals_sp.reset (new UnixSignals ());
767
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000768 SetEventName (eBroadcastBitStateChanged, "state-changed");
769 SetEventName (eBroadcastBitInterrupt, "interrupt");
770 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
771 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000772 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000773
Greg Clayton35a4cc52012-10-29 20:52:08 +0000774 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
775 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
776 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
777
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778 listener.StartListeningForEvents (this,
779 eBroadcastBitStateChanged |
780 eBroadcastBitInterrupt |
781 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000782 eBroadcastBitSTDERR |
783 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784
785 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000786 eBroadcastBitStateChanged |
787 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788
789 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
790 eBroadcastInternalStateControlStop |
791 eBroadcastInternalStateControlPause |
792 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000793 // We need something valid here, even if just the default UnixSignalsSP.
794 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795}
796
797//----------------------------------------------------------------------
798// Destructor
799//----------------------------------------------------------------------
800Process::~Process()
801{
Greg Clayton5160ce52013-03-27 23:08:40 +0000802 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000804 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000806
807 // ThreadList::Clear() will try to acquire this process's mutex, so
808 // explicitly clear the thread list here to ensure that the mutex
809 // is not destroyed before the thread list.
810 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000811}
812
Greg Clayton67cc0632012-08-22 17:17:09 +0000813const ProcessPropertiesSP &
814Process::GetGlobalProperties()
815{
816 static ProcessPropertiesSP g_settings_sp;
817 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000818 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000819 return g_settings_sp;
820}
821
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822void
823Process::Finalize()
824{
Greg Claytonc00ca312015-04-02 18:44:58 +0000825 m_finalizing = true;
826
Ilia Kc7efd562015-03-26 07:40:40 +0000827 // Destroy this process if needed
828 switch (GetPrivateState())
829 {
830 case eStateConnected:
831 case eStateAttaching:
832 case eStateLaunching:
833 case eStateStopped:
834 case eStateRunning:
835 case eStateStepping:
836 case eStateCrashed:
837 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000838 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000839 break;
840
841 case eStateInvalid:
842 case eStateUnloaded:
843 case eStateDetached:
844 case eStateExited:
845 break;
846 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000847
Greg Clayton1ed54f52011-10-01 00:45:15 +0000848 // Clear our broadcaster before we proceed with destroying
849 Broadcaster::Clear();
850
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851 // Do any cleanup needed prior to being destructed... Subclasses
852 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000853
854 // We need to destroy the loader before the derived Process class gets destroyed
855 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000856 m_dynamic_checkers_ap.reset();
857 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000858 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000859 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000860 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000861 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000862 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000863 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000864 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000865 m_queue_list.Clear();
866 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000867 std::vector<Notifications> empty_notifications;
868 m_notifications.swap(empty_notifications);
869 m_image_tokens.clear();
870 m_memory_cache.Clear();
871 m_allocated_memory_cache.Clear();
872 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000873 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000874 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000875 m_stop_info_override_callback = NULL;
Greg Clayton08765fa2015-05-28 03:24:30 +0000876 // Clear the last natural stop ID since it has a strong
877 // reference to this process
878 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000879//#ifdef LLDB_CONFIGURATION_DEBUG
880// StreamFile s(stdout, false);
881// EventSP event_sp;
882// while (m_private_state_listener.GetNextEvent(event_sp))
883// {
884// event_sp->Dump (&s);
885// s.EOL();
886// }
887//#endif
888 // We have to be very careful here as the m_private_state_listener might
889 // contain events that have ProcessSP values in them which can keep this
890 // process around forever. These events need to be cleared out.
891 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000892 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
893 m_public_run_lock.SetStopped();
894 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
895 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000896 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897}
898
899void
900Process::RegisterNotificationCallbacks (const Notifications& callbacks)
901{
902 m_notifications.push_back(callbacks);
903 if (callbacks.initialize != NULL)
904 callbacks.initialize (callbacks.baton, this);
905}
906
907bool
908Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
909{
910 std::vector<Notifications>::iterator pos, end = m_notifications.end();
911 for (pos = m_notifications.begin(); pos != end; ++pos)
912 {
913 if (pos->baton == callbacks.baton &&
914 pos->initialize == callbacks.initialize &&
915 pos->process_state_changed == callbacks.process_state_changed)
916 {
917 m_notifications.erase(pos);
918 return true;
919 }
920 }
921 return false;
922}
923
924void
925Process::SynchronouslyNotifyStateChanged (StateType state)
926{
927 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
928 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
929 {
930 if (notification_pos->process_state_changed)
931 notification_pos->process_state_changed (notification_pos->baton, this, state);
932 }
933}
934
935// FIXME: We need to do some work on events before the general Listener sees them.
936// For instance if we are continuing from a breakpoint, we need to ensure that we do
937// the little "insert real insn, step & stop" trick. But we can't do that when the
938// event is delivered by the broadcaster - since that is done on the thread that is
939// waiting for new events, so if we needed more than one event for our handling, we would
940// stall. So instead we do it when we fetch the event off of the queue.
941//
942
943StateType
944Process::GetNextEvent (EventSP &event_sp)
945{
946 StateType state = eStateInvalid;
947
948 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
949 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
950
951 return state;
952}
953
Pavel Labath44464872015-05-27 12:40:32 +0000954void
955Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000956{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000957 // don't sync (potentially context switch) in case where there is no process IO
Pavel Labath44464872015-05-27 12:40:32 +0000958 if (! m_process_input_reader)
959 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000960
Pavel Labath44464872015-05-27 12:40:32 +0000961 TimeValue timeout = TimeValue::Now();
962 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
963 uint32_t new_iohandler_id = 0;
964 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000965
Pavel Labath44464872015-05-27 12:40:32 +0000966 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
967 if (log)
968 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 +0000969}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970
971StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000972Process::WaitForProcessToStop (const TimeValue *timeout,
973 EventSP *event_sp_ptr,
974 bool wait_always,
975 Listener *hijack_listener,
976 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977{
Jim Ingham4b536182011-08-09 02:12:22 +0000978 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
979 // We have to actually check each event, and in the case of a stopped event check the restarted flag
980 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000981 if (event_sp_ptr)
982 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000983 StateType state = GetState();
984 // If we are exited or detached, we won't ever get back to any
985 // other valid state...
986 if (state == eStateDetached || state == eStateExited)
987 return state;
988
Daniel Malea9e9919f2013-10-09 16:56:28 +0000989 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
990 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000991 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
992 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000993
994 if (!wait_always &&
995 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +0000996 StateIsStoppedState(GetPrivateState(), true))
997 {
Daniel Malea9e9919f2013-10-09 16:56:28 +0000998 if (log)
999 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1000 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001001 // We need to toggle the run lock as this won't get done in
1002 // SetPublicState() if the process is hijacked.
1003 if (hijack_listener)
1004 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001005 return state;
1006 }
1007
Jim Ingham4b536182011-08-09 02:12:22 +00001008 while (state != eStateInvalid)
1009 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001010 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001011 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001012 if (event_sp_ptr && event_sp)
1013 *event_sp_ptr = event_sp;
1014
Greg Claytondc6224e2014-10-21 01:00:42 +00001015 bool pop_process_io_handler = hijack_listener != NULL;
1016 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1017
Jim Ingham4b536182011-08-09 02:12:22 +00001018 switch (state)
1019 {
1020 case eStateCrashed:
1021 case eStateDetached:
1022 case eStateExited:
1023 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001024 // We need to toggle the run lock as this won't get done in
1025 // SetPublicState() if the process is hijacked.
1026 if (hijack_listener)
1027 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001028 return state;
1029 case eStateStopped:
1030 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1031 continue;
1032 else
Greg Clayton44d93782014-01-27 23:43:24 +00001033 {
1034 // We need to toggle the run lock as this won't get done in
1035 // SetPublicState() if the process is hijacked.
1036 if (hijack_listener)
1037 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001038 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001039 }
Jim Ingham4b536182011-08-09 02:12:22 +00001040 default:
1041 continue;
1042 }
1043 }
1044 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045}
1046
Greg Claytondc6224e2014-10-21 01:00:42 +00001047bool
1048Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1049 Stream *stream,
1050 bool &pop_process_io_handler)
1051{
1052 const bool handle_pop = pop_process_io_handler == true;
1053
1054 pop_process_io_handler = false;
1055 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1056
1057 if (!process_sp)
1058 return false;
1059
1060 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1061 if (event_state == eStateInvalid)
1062 return false;
1063
1064 switch (event_state)
1065 {
1066 case eStateInvalid:
1067 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001068 case eStateAttaching:
1069 case eStateLaunching:
1070 case eStateStepping:
1071 case eStateDetached:
1072 {
1073 if (stream)
1074 stream->Printf ("Process %" PRIu64 " %s\n",
1075 process_sp->GetID(),
1076 StateAsCString (event_state));
1077
1078 if (event_state == eStateDetached)
1079 pop_process_io_handler = true;
1080 }
1081 break;
1082
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001083 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001084 case eStateRunning:
1085 // Don't be chatty when we run...
1086 break;
1087
1088 case eStateExited:
1089 if (stream)
1090 process_sp->GetStatus(*stream);
1091 pop_process_io_handler = true;
1092 break;
1093
1094 case eStateStopped:
1095 case eStateCrashed:
1096 case eStateSuspended:
1097 // Make sure the program hasn't been auto-restarted:
1098 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1099 {
1100 if (stream)
1101 {
1102 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1103 if (num_reasons > 0)
1104 {
1105 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1106 if (num_reasons == 1)
1107 {
1108 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1109 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1110 process_sp->GetID(),
1111 reason ? reason : "<UNKNOWN REASON>");
1112 }
1113 else
1114 {
1115 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1116 process_sp->GetID());
1117
1118
1119 for (size_t i = 0; i < num_reasons; i++)
1120 {
1121 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1122 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1123 }
1124 }
1125 }
1126 }
1127 }
1128 else
1129 {
1130 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1131 {
1132 ThreadList &thread_list = process_sp->GetThreadList();
1133 Mutex::Locker locker (thread_list.GetMutex());
1134
1135 ThreadSP curr_thread (thread_list.GetSelectedThread());
1136 ThreadSP thread;
1137 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1138 if (curr_thread)
1139 curr_thread_stop_reason = curr_thread->GetStopReason();
1140 if (!curr_thread ||
1141 !curr_thread->IsValid() ||
1142 curr_thread_stop_reason == eStopReasonInvalid ||
1143 curr_thread_stop_reason == eStopReasonNone)
1144 {
1145 // Prefer a thread that has just completed its plan over another thread as current thread.
1146 ThreadSP plan_thread;
1147 ThreadSP other_thread;
1148 const size_t num_threads = thread_list.GetSize();
1149 size_t i;
1150 for (i = 0; i < num_threads; ++i)
1151 {
1152 thread = thread_list.GetThreadAtIndex(i);
1153 StopReason thread_stop_reason = thread->GetStopReason();
1154 switch (thread_stop_reason)
1155 {
1156 case eStopReasonInvalid:
1157 case eStopReasonNone:
1158 break;
1159
1160 case eStopReasonTrace:
1161 case eStopReasonBreakpoint:
1162 case eStopReasonWatchpoint:
1163 case eStopReasonSignal:
1164 case eStopReasonException:
1165 case eStopReasonExec:
1166 case eStopReasonThreadExiting:
1167 case eStopReasonInstrumentation:
1168 if (!other_thread)
1169 other_thread = thread;
1170 break;
1171 case eStopReasonPlanComplete:
1172 if (!plan_thread)
1173 plan_thread = thread;
1174 break;
1175 }
1176 }
1177 if (plan_thread)
1178 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1179 else if (other_thread)
1180 thread_list.SetSelectedThreadByID (other_thread->GetID());
1181 else
1182 {
1183 if (curr_thread && curr_thread->IsValid())
1184 thread = curr_thread;
1185 else
1186 thread = thread_list.GetThreadAtIndex(0);
1187
1188 if (thread)
1189 thread_list.SetSelectedThreadByID (thread->GetID());
1190 }
1191 }
1192 }
1193 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1194 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1195 // have a hard time restarting the process.
1196 if (stream)
1197 {
1198 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1199 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1200 {
1201 const bool only_threads_with_stop_reason = true;
1202 const uint32_t start_frame = 0;
1203 const uint32_t num_frames = 1;
1204 const uint32_t num_frames_with_source = 1;
1205 process_sp->GetStatus(*stream);
1206 process_sp->GetThreadStatus (*stream,
1207 only_threads_with_stop_reason,
1208 start_frame,
1209 num_frames,
1210 num_frames_with_source);
1211 }
1212 else
1213 {
1214 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1215 if (target_idx != UINT32_MAX)
1216 stream->Printf ("Target %d: (", target_idx);
1217 else
1218 stream->Printf ("Target <unknown index>: (");
1219 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1220 stream->Printf (") stopped.\n");
1221 }
1222 }
1223
1224 // Pop the process IO handler
1225 pop_process_io_handler = true;
1226 }
1227 break;
1228 }
1229
1230 if (handle_pop && pop_process_io_handler)
1231 process_sp->PopProcessIOHandler();
1232
1233 return true;
1234}
1235
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001236
1237StateType
1238Process::WaitForState
1239(
1240 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001241 const StateType *match_states,
1242 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001243)
1244{
1245 EventSP event_sp;
1246 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001247 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248 while (state != eStateInvalid)
1249 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001250 // If we are exited or detached, we won't ever get back to any
1251 // other valid state...
1252 if (state == eStateDetached || state == eStateExited)
1253 return state;
1254
Greg Clayton44d93782014-01-27 23:43:24 +00001255 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256
1257 for (i=0; i<num_match_states; ++i)
1258 {
1259 if (match_states[i] == state)
1260 return state;
1261 }
1262 }
1263 return state;
1264}
1265
Jim Ingham30f9b212010-10-11 23:53:14 +00001266bool
1267Process::HijackProcessEvents (Listener *listener)
1268{
1269 if (listener != NULL)
1270 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001271 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001272 }
1273 else
1274 return false;
1275}
1276
1277void
1278Process::RestoreProcessEvents ()
1279{
1280 RestoreBroadcaster();
1281}
1282
Jim Ingham0f16e732011-02-08 05:20:59 +00001283bool
1284Process::HijackPrivateProcessEvents (Listener *listener)
1285{
1286 if (listener != NULL)
1287 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001288 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001289 }
1290 else
1291 return false;
1292}
1293
1294void
1295Process::RestorePrivateProcessEvents ()
1296{
1297 m_private_state_broadcaster.RestoreBroadcaster();
1298}
1299
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001301Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302{
Greg Clayton5160ce52013-03-27 23:08:40 +00001303 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304
1305 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001306 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1307 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308
Greg Clayton44d93782014-01-27 23:43:24 +00001309 Listener *listener = hijack_listener;
1310 if (listener == NULL)
1311 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001314 if (listener->WaitForEventForBroadcasterWithType (timeout,
1315 this,
1316 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1317 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001318 {
1319 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1320 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1321 else if (log)
1322 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1323 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324
1325 if (log)
1326 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001327 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 StateAsCString(state));
1329 return state;
1330}
1331
1332Event *
1333Process::PeekAtStateChangedEvents ()
1334{
Greg Clayton5160ce52013-03-27 23:08:40 +00001335 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336
1337 if (log)
1338 log->Printf ("Process::%s...", __FUNCTION__);
1339
1340 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001341 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1342 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 if (log)
1344 {
1345 if (event_ptr)
1346 {
1347 log->Printf ("Process::%s (event_ptr) => %s",
1348 __FUNCTION__,
1349 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1350 }
1351 else
1352 {
1353 log->Printf ("Process::%s no events found",
1354 __FUNCTION__);
1355 }
1356 }
1357 return event_ptr;
1358}
1359
1360StateType
1361Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1362{
Greg Clayton5160ce52013-03-27 23:08:40 +00001363 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364
1365 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001366 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1367 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368
1369 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001370 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1371 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001372 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001373 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001374 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1375 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376
1377 // This is a bit of a hack, but when we wait here we could very well return
1378 // to the command-line, and that could disable the log, which would render the
1379 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001381 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1382 __FUNCTION__, static_cast<const void *>(timeout),
1383 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 return state;
1385}
1386
1387bool
1388Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1389{
Greg Clayton5160ce52013-03-27 23:08:40 +00001390 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391
1392 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001393 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1394 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395
1396 if (control_only)
1397 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1398 else
1399 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1400}
1401
1402bool
1403Process::IsRunning () const
1404{
1405 return StateIsRunningState (m_public_state.GetValue());
1406}
1407
1408int
1409Process::GetExitStatus ()
1410{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001411 Mutex::Locker locker (m_exit_status_mutex);
1412
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413 if (m_public_state.GetValue() == eStateExited)
1414 return m_exit_status;
1415 return -1;
1416}
1417
Greg Clayton85851dd2010-12-04 00:10:17 +00001418
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419const char *
1420Process::GetExitDescription ()
1421{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001422 Mutex::Locker locker (m_exit_status_mutex);
1423
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1425 return m_exit_string.c_str();
1426 return NULL;
1427}
1428
Greg Clayton6779606a2011-01-22 23:43:18 +00001429bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430Process::SetExitStatus (int status, const char *cstr)
1431{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001432 // Use a mutex to protect setting the exit status.
1433 Mutex::Locker locker (m_exit_status_mutex);
1434
Greg Clayton5160ce52013-03-27 23:08:40 +00001435 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001436 if (log)
1437 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1438 status, status,
1439 cstr ? "\"" : "",
1440 cstr ? cstr : "NULL",
1441 cstr ? "\"" : "");
1442
Greg Clayton6779606a2011-01-22 23:43:18 +00001443 // We were already in the exited state
1444 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001445 {
Greg Clayton385d6032011-01-26 23:47:29 +00001446 if (log)
1447 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001448 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001449 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001450
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001451 m_exit_status = status;
1452 if (cstr)
1453 m_exit_string = cstr;
1454 else
1455 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456
Greg Clayton5df78fa2015-05-23 03:54:53 +00001457 // When we exit, we no longer need to the communication channel
Greg Clayton5df78fa2015-05-23 03:54:53 +00001458 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00001459 m_stdio_communication.StopReadThread();
Greg Clayton5df78fa2015-05-23 03:54:53 +00001460 m_stdin_forward = false;
1461
1462 // And we don't need the input reader anymore as well
1463 if (m_process_input_reader)
1464 {
1465 m_process_input_reader->SetIsDone(true);
1466 m_process_input_reader->Cancel();
1467 m_process_input_reader.reset();
1468 }
Greg Clayton10177aa2010-12-08 05:08:21 +00001469
Greg Clayton08765fa2015-05-28 03:24:30 +00001470 // Clear the last natural stop ID since it has a strong
1471 // reference to this process
1472 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1473
Greg Clayton6779606a2011-01-22 23:43:18 +00001474 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001475
1476 // Allow subclasses to do some cleanup
1477 DidExit ();
1478
Greg Clayton6779606a2011-01-22 23:43:18 +00001479 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480}
1481
1482// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001483// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484// found in the global target list (we want to be completely sure that the
1485// lldb_private::Process doesn't go away before we can deliver the signal.
1486bool
Greg Claytone4e45922011-11-16 05:37:56 +00001487Process::SetProcessExitStatus (void *callback_baton,
1488 lldb::pid_t pid,
1489 bool exited,
1490 int signo, // Zero for no signal
1491 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492)
1493{
Greg Clayton5160ce52013-03-27 23:08:40 +00001494 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001495 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001496 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001497 callback_baton,
1498 pid,
1499 exited,
1500 signo,
1501 exit_status);
1502
1503 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 {
Greg Clayton66111032010-06-23 01:19:29 +00001505 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001506 if (target_sp)
1507 {
1508 ProcessSP process_sp (target_sp->GetProcessSP());
1509 if (process_sp)
1510 {
1511 const char *signal_cstr = NULL;
1512 if (signo)
1513 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1514
1515 process_sp->SetExitStatus (exit_status, signal_cstr);
1516 }
1517 }
1518 return true;
1519 }
1520 return false;
1521}
1522
1523
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001524void
1525Process::UpdateThreadListIfNeeded ()
1526{
1527 const uint32_t stop_id = GetStopID();
1528 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1529 {
Greg Clayton2637f822011-11-17 01:23:07 +00001530 const StateType state = GetPrivateState();
1531 if (StateIsStoppedState (state, true))
1532 {
1533 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001534 // m_thread_list does have its own mutex, but we need to
1535 // hold onto the mutex between the call to UpdateThreadList(...)
1536 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001537 ThreadList &old_thread_list = m_thread_list;
1538 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001539 ThreadList new_thread_list(this);
1540 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001541 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001542 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001543 {
Jim Ingham09437922013-03-01 20:04:25 +00001544 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1545 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1546 // shutting us down, causing a deadlock.
1547 if (!m_destroy_in_process)
1548 {
1549 OperatingSystem *os = GetOperatingSystem ();
1550 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001551 {
1552 // Clear any old backing threads where memory threads might have been
1553 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001554 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001555 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001556 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001557
Greg Clayton15484402015-05-15 18:40:24 +00001558 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1559 // can run an expression to determine if a SBValue is a dynamic type or not
1560 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1561 // that require running code...
1562
1563 Target &target = GetTarget();
1564 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1565 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1566 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1567
Greg Claytonb3ae8762013-04-12 20:07:46 +00001568 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001569
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001570 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1571 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1572 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 +00001573
1574 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1575 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001576 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001577 else
1578 {
1579 // No OS plug-in, the new thread list is the same as the real thread list
1580 new_thread_list = real_thread_list;
1581 }
Jim Ingham09437922013-03-01 20:04:25 +00001582 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001583
1584 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001585 m_thread_list.Update (new_thread_list);
1586 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001587
Jason Molenda4ff13262013-11-20 00:31:38 +00001588 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1589 {
1590 // Clear any extended threads that we may have accumulated previously
1591 m_extended_thread_list.Clear();
1592 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001593
1594 m_queue_list.Clear();
1595 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001596 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001597 }
Greg Clayton2637f822011-11-17 01:23:07 +00001598 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001599 }
1600}
1601
Jason Molenda5e8dce42013-12-13 00:29:16 +00001602void
1603Process::UpdateQueueListIfNeeded ()
1604{
1605 if (m_system_runtime_ap.get())
1606 {
1607 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1608 {
1609 const StateType state = GetPrivateState();
1610 if (StateIsStoppedState (state, true))
1611 {
1612 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1613 m_queue_list_stop_id = GetLastNaturalStopID();
1614 }
1615 }
1616 }
1617}
1618
Greg Claytona4d87472013-01-18 23:41:08 +00001619ThreadSP
1620Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1621{
1622 OperatingSystem *os = GetOperatingSystem ();
1623 if (os)
1624 return os->CreateThread(tid, context);
1625 return ThreadSP();
1626}
1627
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001628uint32_t
1629Process::GetNextThreadIndexID (uint64_t thread_id)
1630{
1631 return AssignIndexIDToThread(thread_id);
1632}
1633
1634bool
1635Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1636{
1637 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1638 if (iterator == m_thread_id_to_index_id_map.end())
1639 {
1640 return false;
1641 }
1642 else
1643 {
1644 return true;
1645 }
1646}
1647
1648uint32_t
1649Process::AssignIndexIDToThread(uint64_t thread_id)
1650{
1651 uint32_t result = 0;
1652 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1653 if (iterator == m_thread_id_to_index_id_map.end())
1654 {
1655 result = ++m_thread_index_id;
1656 m_thread_id_to_index_id_map[thread_id] = result;
1657 }
1658 else
1659 {
1660 result = iterator->second;
1661 }
1662
1663 return result;
1664}
1665
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666StateType
1667Process::GetState()
1668{
1669 // If any other threads access this we will need a mutex for it
1670 return m_public_state.GetValue ();
1671}
1672
Greg Claytondc6224e2014-10-21 01:00:42 +00001673bool
1674Process::StateChangedIsExternallyHijacked()
1675{
1676 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1677 {
1678 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1679 return true;
1680 }
1681 return false;
1682}
1683
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684void
Jim Ingham221d51c2013-05-08 00:35:16 +00001685Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686{
Greg Clayton5160ce52013-03-27 23:08:40 +00001687 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001689 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001690 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001691 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001692
1693 // On the transition from Run to Stopped, we unlock the writer end of the
1694 // run lock. The lock gets locked in Resume, which is the public API
1695 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001696 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001697 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001698 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001699 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001700 if (log)
1701 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001702 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001703 }
1704 else
1705 {
1706 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1707 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001708 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001709 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001710 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001711 {
1712 if (log)
1713 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001714 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001715 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001716 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001717 }
1718 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001719}
1720
Jim Ingham3b8285d2012-04-19 01:40:33 +00001721Error
1722Process::Resume ()
1723{
Greg Clayton5160ce52013-03-27 23:08:40 +00001724 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001725 if (log)
1726 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001727 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001728 {
1729 Error error("Resume request failed - process still running.");
1730 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001731 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001732 return error;
1733 }
1734 return PrivateResume();
1735}
1736
Greg Claytondc6224e2014-10-21 01:00:42 +00001737Error
1738Process::ResumeSynchronous (Stream *stream)
1739{
1740 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1741 if (log)
1742 log->Printf("Process::ResumeSynchronous -- locking run lock");
1743 if (!m_public_run_lock.TrySetRunning())
1744 {
1745 Error error("Resume request failed - process still running.");
1746 if (log)
1747 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1748 return error;
1749 }
1750
1751 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1752 HijackProcessEvents(listener_sp.get());
1753
1754 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001755 if (error.Success())
1756 {
1757 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1758 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1759 if (!StateIsStoppedState(state, must_be_alive))
1760 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1761 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001762
1763 // Undo the hijacking of process events...
1764 RestoreProcessEvents();
1765
Greg Claytondc6224e2014-10-21 01:00:42 +00001766 return error;
1767}
1768
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769StateType
1770Process::GetPrivateState ()
1771{
1772 return m_private_state.GetValue();
1773}
1774
1775void
1776Process::SetPrivateState (StateType new_state)
1777{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001778 if (m_finalize_called)
1779 return;
1780
Greg Clayton5160ce52013-03-27 23:08:40 +00001781 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001782 bool state_changed = false;
1783
1784 if (log)
1785 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1786
Andrew Kaylor29d65742013-05-10 17:19:04 +00001787 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001788 Mutex::Locker locker(m_private_state.GetMutex());
1789
1790 const StateType old_state = m_private_state.GetValueNoLock ();
1791 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001792
Greg Claytonaa49c832013-05-03 22:25:56 +00001793 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1794 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1795 if (old_state_is_stopped != new_state_is_stopped)
1796 {
1797 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001798 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001799 else
Ed Maste64fad602013-07-29 20:58:06 +00001800 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001801 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001802
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 if (state_changed)
1804 {
1805 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001806 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001807 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001809 // Note, this currently assumes that all threads in the list
1810 // stop when the process stops. In the future we will want to
1811 // support a debugging model where some threads continue to run
1812 // while others are stopped. When that happens we will either need
1813 // a way for the thread list to identify which threads are stopping
1814 // or create a special thread list containing only threads which
1815 // actually stopped.
1816 //
1817 // The process plugin is responsible for managing the actual
1818 // behavior of the threads and should have stopped any threads
1819 // that are going to stop before we get here.
1820 m_thread_list.DidStop();
1821
Jim Ingham4b536182011-08-09 02:12:22 +00001822 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001823 if (!m_mod_id.IsLastResumeForUserExpression())
1824 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001825 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001827 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 }
Ilia K38810f42015-05-20 10:15:47 +00001829
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001831 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:47 +00001832 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001833 else
Ilia K38810f42015-05-20 10:15:47 +00001834 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 }
1836 else
1837 {
1838 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001839 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001840 }
1841}
1842
Jim Ingham0faa43f2011-11-08 03:00:11 +00001843void
1844Process::SetRunningUserExpression (bool on)
1845{
1846 m_mod_id.SetRunningUserExpression (on);
1847}
1848
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849addr_t
1850Process::GetImageInfoAddress()
1851{
1852 return LLDB_INVALID_ADDRESS;
1853}
1854
Greg Clayton8f343b02010-11-04 01:54:29 +00001855//----------------------------------------------------------------------
1856// LoadImage
1857//
1858// This function provides a default implementation that works for most
1859// unix variants. Any Process subclasses that need to do shared library
1860// loading differently should override LoadImage and UnloadImage and
1861// do what is needed.
1862//----------------------------------------------------------------------
1863uint32_t
1864Process::LoadImage (const FileSpec &image_spec, Error &error)
1865{
Greg Claytonc00ca312015-04-02 18:44:58 +00001866 if (m_finalizing)
1867 {
1868 error.SetErrorString("process is tearing itself down");
1869 return LLDB_INVALID_IMAGE_TOKEN;
1870 }
1871
Greg Claytonac7a3db2012-04-18 00:05:19 +00001872 char path[PATH_MAX];
1873 image_spec.GetPath(path, sizeof(path));
1874
Greg Clayton8f343b02010-11-04 01:54:29 +00001875 DynamicLoader *loader = GetDynamicLoader();
1876 if (loader)
1877 {
1878 error = loader->CanLoadImage();
1879 if (error.Fail())
1880 return LLDB_INVALID_IMAGE_TOKEN;
1881 }
1882
1883 if (error.Success())
1884 {
1885 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001886
1887 if (thread_sp)
1888 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001889 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001890
1891 if (frame_sp)
1892 {
1893 ExecutionContext exe_ctx;
1894 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001895 EvaluateExpressionOptions expr_options;
1896 expr_options.SetUnwindOnError(true);
1897 expr_options.SetIgnoreBreakpoints(true);
1898 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001899 expr_options.SetResultIsInternal(true);
1900
Greg Clayton8f343b02010-11-04 01:54:29 +00001901 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001902 expr.Printf(R"(
1903 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1904 the_result.image_ptr = dlopen ("%s", 2);
1905 if (the_result.image_ptr == (void *) 0x0)
1906 {
1907 the_result.error_str = dlerror();
1908 }
1909 else
1910 {
1911 the_result.error_str = (const char *) 0x0;
1912 }
1913 the_result;
1914 )",
1915 path);
1916 const char *prefix = R"(
1917 extern "C" void* dlopen (const char *path, int mode);
1918 extern "C" const char *dlerror (void);
1919 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001920 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001921 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001922 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001923 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001924 expr.GetData(),
1925 prefix,
1926 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001927 expr_error);
1928 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001929 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001930 error = result_valobj_sp->GetError();
1931 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001932 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001933 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001934 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1935 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001936 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001937 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1938 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1939 {
1940 uint32_t image_token = m_image_tokens.size();
1941 m_image_tokens.push_back (image_ptr);
1942 return image_token;
1943 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001944 else if (image_ptr == 0)
1945 {
Jim Ingham6971b862014-07-19 00:37:06 +00001946 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1947 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001948 {
Jim Ingham6971b862014-07-19 00:37:06 +00001949 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001950 {
Enrico Granata2206b482014-10-30 18:27:31 +00001951 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1952 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001953 if (error.Success() && num_chars > 0)
1954 {
1955 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001956 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1957 }
1958 else
1959 {
1960 error.Clear();
1961 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001962 }
1963 }
1964 }
1965 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001966 }
1967 }
1968 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001969 else
1970 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001971 }
1972 }
1973 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001974 if (!error.AsCString())
1975 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001976 return LLDB_INVALID_IMAGE_TOKEN;
1977}
1978
1979//----------------------------------------------------------------------
1980// UnloadImage
1981//
1982// This function provides a default implementation that works for most
1983// unix variants. Any Process subclasses that need to do shared library
1984// loading differently should override LoadImage and UnloadImage and
1985// do what is needed.
1986//----------------------------------------------------------------------
1987Error
1988Process::UnloadImage (uint32_t image_token)
1989{
1990 Error error;
Greg Claytonc00ca312015-04-02 18:44:58 +00001991
1992 if (m_finalizing)
1993 {
1994 error.SetErrorString("process is tearing itself down");
1995 return error;
1996 }
1997
Greg Clayton8f343b02010-11-04 01:54:29 +00001998 if (image_token < m_image_tokens.size())
1999 {
2000 const addr_t image_addr = m_image_tokens[image_token];
2001 if (image_addr == LLDB_INVALID_ADDRESS)
2002 {
2003 error.SetErrorString("image already unloaded");
2004 }
2005 else
2006 {
2007 DynamicLoader *loader = GetDynamicLoader();
2008 if (loader)
2009 error = loader->CanLoadImage();
2010
2011 if (error.Success())
2012 {
2013 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00002014
2015 if (thread_sp)
2016 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002017 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00002018
2019 if (frame_sp)
2020 {
2021 ExecutionContext exe_ctx;
2022 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00002023 EvaluateExpressionOptions expr_options;
2024 expr_options.SetUnwindOnError(true);
2025 expr_options.SetIgnoreBreakpoints(true);
2026 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00002027 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00002028 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00002029 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00002030 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00002031 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00002032 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002033 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00002034 expr.GetData(),
2035 prefix,
2036 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002037 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002038 if (result_valobj_sp->GetError().Success())
2039 {
2040 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002041 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002042 {
2043 if (scalar.UInt(1))
2044 {
2045 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2046 }
2047 else
2048 {
2049 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2050 }
2051 }
2052 }
2053 else
2054 {
2055 error = result_valobj_sp->GetError();
2056 }
2057 }
2058 }
2059 }
2060 }
2061 }
2062 else
2063 {
2064 error.SetErrorString("invalid image token");
2065 }
2066 return error;
2067}
2068
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002069const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002070Process::GetABI()
2071{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002072 if (!m_abi_sp)
2073 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2074 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075}
2076
Jim Ingham22777012010-09-23 02:01:19 +00002077LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002078Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002079{
Greg Claytonc00ca312015-04-02 18:44:58 +00002080 if (m_finalizing)
2081 return nullptr;
2082
Jim Ingham22777012010-09-23 02:01:19 +00002083 LanguageRuntimeCollection::iterator pos;
2084 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002085 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002086 {
Jim Inghamab175242012-03-10 00:22:19 +00002087 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002088
Jim Inghamab175242012-03-10 00:22:19 +00002089 m_language_runtimes[language] = runtime_sp;
2090 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002091 }
2092 else
2093 return (*pos).second.get();
2094}
2095
2096CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002097Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002098{
Jim Inghamab175242012-03-10 00:22:19 +00002099 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002100 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2101 return static_cast<CPPLanguageRuntime *> (runtime);
2102 return NULL;
2103}
2104
2105ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002106Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002107{
Jim Inghamab175242012-03-10 00:22:19 +00002108 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002109 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2110 return static_cast<ObjCLanguageRuntime *> (runtime);
2111 return NULL;
2112}
2113
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002114bool
2115Process::IsPossibleDynamicValue (ValueObject& in_value)
2116{
Greg Claytonc00ca312015-04-02 18:44:58 +00002117 if (m_finalizing)
2118 return false;
2119
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002120 if (in_value.IsDynamic())
2121 return false;
2122 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2123
2124 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2125 {
2126 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2127 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2128 }
2129
2130 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2131 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2132 return true;
2133
2134 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2135 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2136}
2137
Zachary Turner93749ab2015-03-03 21:51:25 +00002138void
2139Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2140{
2141 m_dynamic_checkers_ap.reset(dynamic_checkers);
2142}
2143
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144BreakpointSiteList &
2145Process::GetBreakpointSiteList()
2146{
2147 return m_breakpoint_site_list;
2148}
2149
2150const BreakpointSiteList &
2151Process::GetBreakpointSiteList() const
2152{
2153 return m_breakpoint_site_list;
2154}
2155
2156
2157void
2158Process::DisableAllBreakpointSites ()
2159{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002160 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2161// bp_site->SetEnabled(true);
2162 DisableBreakpointSite(bp_site);
2163 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164}
2165
2166Error
2167Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2168{
2169 Error error (DisableBreakpointSiteByID (break_id));
2170
2171 if (error.Success())
2172 m_breakpoint_site_list.Remove(break_id);
2173
2174 return error;
2175}
2176
2177Error
2178Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2179{
2180 Error error;
2181 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2182 if (bp_site_sp)
2183 {
2184 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002185 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002186 }
2187 else
2188 {
Daniel Malead01b2952012-11-29 21:49:15 +00002189 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190 }
2191
2192 return error;
2193}
2194
2195Error
2196Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2197{
2198 Error error;
2199 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2200 if (bp_site_sp)
2201 {
2202 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002203 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204 }
2205 else
2206 {
Daniel Malead01b2952012-11-29 21:49:15 +00002207 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002208 }
2209 return error;
2210}
2211
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002212lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002213Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002215 addr_t load_addr = LLDB_INVALID_ADDRESS;
2216
2217 bool show_error = true;
2218 switch (GetState())
2219 {
2220 case eStateInvalid:
2221 case eStateUnloaded:
2222 case eStateConnected:
2223 case eStateAttaching:
2224 case eStateLaunching:
2225 case eStateDetached:
2226 case eStateExited:
2227 show_error = false;
2228 break;
2229
2230 case eStateStopped:
2231 case eStateRunning:
2232 case eStateStepping:
2233 case eStateCrashed:
2234 case eStateSuspended:
2235 show_error = IsAlive();
2236 break;
2237 }
2238
2239 // Reset the IsIndirect flag here, in case the location changes from
2240 // pointing to a indirect symbol to a regular symbol.
2241 owner->SetIsIndirect (false);
2242
2243 if (owner->ShouldResolveIndirectFunctions())
2244 {
2245 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2246 if (symbol && symbol->IsIndirect())
2247 {
2248 Error error;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002249 Address symbol_address = symbol->GetAddress();
2250 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:59 +00002251 if (!error.Success() && show_error)
2252 {
Greg Clayton44d93782014-01-27 23:43:24 +00002253 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 +00002254 symbol->GetLoadAddress(&m_target),
Greg Clayton44d93782014-01-27 23:43:24 +00002255 owner->GetBreakpoint().GetID(),
2256 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002257 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002258 return LLDB_INVALID_BREAK_ID;
2259 }
2260 Address resolved_address(load_addr);
2261 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2262 owner->SetIsIndirect(true);
2263 }
2264 else
2265 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2266 }
2267 else
2268 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2269
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270 if (load_addr != LLDB_INVALID_ADDRESS)
2271 {
2272 BreakpointSiteSP bp_site_sp;
2273
2274 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2275 // create a new breakpoint site and add it.
2276
2277 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2278
2279 if (bp_site_sp)
2280 {
2281 bp_site_sp->AddOwner (owner);
2282 owner->SetBreakpointSite (bp_site_sp);
2283 return bp_site_sp->GetID();
2284 }
2285 else
2286 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002287 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288 if (bp_site_sp)
2289 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002290 Error error = EnableBreakpointSite (bp_site_sp.get());
2291 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 {
2293 owner->SetBreakpointSite (bp_site_sp);
2294 return m_breakpoint_site_list.Add (bp_site_sp);
2295 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002296 else
2297 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002298 if (show_error)
2299 {
2300 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002301 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2302 load_addr,
2303 owner->GetBreakpoint().GetID(),
2304 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002305 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002306 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002307 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002308 }
2309 }
2310 }
2311 // We failed to enable the breakpoint
2312 return LLDB_INVALID_BREAK_ID;
2313
2314}
2315
2316void
2317Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2318{
2319 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2320 if (num_owners == 0)
2321 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002322 // Don't try to disable the site if we don't have a live process anymore.
2323 if (IsAlive())
2324 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2326 }
2327}
2328
2329
2330size_t
2331Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2332{
2333 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002334 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335
Jim Ingham20c77192011-06-29 19:42:28 +00002336 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002338 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2339 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002341 addr_t intersect_addr;
2342 size_t intersect_size;
2343 size_t opcode_offset;
2344 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002345 {
2346 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2347 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002348 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002349 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002350 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002351 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002353 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 }
2355 return bytes_removed;
2356}
2357
2358
Greg Claytonded470d2011-03-19 01:12:21 +00002359
2360size_t
2361Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2362{
2363 PlatformSP platform_sp (m_target.GetPlatform());
2364 if (platform_sp)
2365 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2366 return 0;
2367}
2368
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369Error
2370Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2371{
2372 Error error;
2373 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002374 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375 const addr_t bp_addr = bp_site->GetLoadAddress();
2376 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002377 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002378 if (bp_site->IsEnabled())
2379 {
2380 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002381 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 +00002382 return error;
2383 }
2384
2385 if (bp_addr == LLDB_INVALID_ADDRESS)
2386 {
2387 error.SetErrorString("BreakpointSite contains an invalid load address.");
2388 return error;
2389 }
2390 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2391 // trap for the breakpoint site
2392 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2393
2394 if (bp_opcode_size == 0)
2395 {
Daniel Malead01b2952012-11-29 21:49:15 +00002396 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002397 }
2398 else
2399 {
2400 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2401
2402 if (bp_opcode_bytes == NULL)
2403 {
2404 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2405 return error;
2406 }
2407
2408 // Save the original opcode by reading it
2409 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2410 {
2411 // Write a software breakpoint in place of the original opcode
2412 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2413 {
2414 uint8_t verify_bp_opcode_bytes[64];
2415 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2416 {
2417 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2418 {
2419 bp_site->SetEnabled(true);
2420 bp_site->SetType (BreakpointSite::eSoftware);
2421 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002422 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423 bp_site->GetID(),
2424 (uint64_t)bp_addr);
2425 }
2426 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002427 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 }
2429 else
2430 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2431 }
2432 else
2433 error.SetErrorString("Unable to write breakpoint trap to memory.");
2434 }
2435 else
2436 error.SetErrorString("Unable to read memory at breakpoint address.");
2437 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002438 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002439 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002440 bp_site->GetID(),
2441 (uint64_t)bp_addr,
2442 error.AsCString());
2443 return error;
2444}
2445
2446Error
2447Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2448{
2449 Error error;
2450 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002451 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002452 addr_t bp_addr = bp_site->GetLoadAddress();
2453 lldb::user_id_t breakID = bp_site->GetID();
2454 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002455 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456
2457 if (bp_site->IsHardware())
2458 {
2459 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2460 }
2461 else if (bp_site->IsEnabled())
2462 {
2463 const size_t break_op_size = bp_site->GetByteSize();
2464 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2465 if (break_op_size > 0)
2466 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002467 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002468 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002469 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470 bool break_op_found = false;
2471
2472 // Read the breakpoint opcode
2473 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2474 {
2475 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002476 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002477 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2478 {
2479 break_op_found = true;
2480 // We found a valid breakpoint opcode at this address, now restore
2481 // the saved opcode.
2482 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2483 {
2484 verify = true;
2485 }
2486 else
2487 error.SetErrorString("Memory write failed when restoring original opcode.");
2488 }
2489 else
2490 {
2491 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2492 // Set verify to true and so we can check if the original opcode has already been restored
2493 verify = true;
2494 }
2495
2496 if (verify)
2497 {
Greg Claytonc982c762010-07-09 20:39:50 +00002498 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002499 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 // Verify that our original opcode made it back to the inferior
2501 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2502 {
2503 // compare the memory we just read with the original opcode
2504 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2505 {
2506 // SUCCESS
2507 bp_site->SetEnabled(false);
2508 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002509 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 +00002510 return error;
2511 }
2512 else
2513 {
2514 if (break_op_found)
2515 error.SetErrorString("Failed to restore original opcode.");
2516 }
2517 }
2518 else
2519 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2520 }
2521 }
2522 else
2523 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2524 }
2525 }
2526 else
2527 {
2528 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002529 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 +00002530 return error;
2531 }
2532
2533 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002534 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002535 bp_site->GetID(),
2536 (uint64_t)bp_addr,
2537 error.AsCString());
2538 return error;
2539
2540}
2541
Greg Clayton58be07b2011-01-07 06:08:19 +00002542// Uncomment to verify memory caching works after making changes to caching code
2543//#define VERIFY_MEMORY_READS
2544
Sean Callanan64c0cf22012-06-07 22:26:42 +00002545size_t
2546Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2547{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002548 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002549 if (!GetDisableMemoryCache())
2550 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002551#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002552 // Memory caching is enabled, with debug verification
2553
2554 if (buf && size)
2555 {
2556 // Uncomment the line below to make sure memory caching is working.
2557 // I ran this through the test suite and got no assertions, so I am
2558 // pretty confident this is working well. If any changes are made to
2559 // memory caching, uncomment the line below and test your changes!
2560
2561 // Verify all memory reads by using the cache first, then redundantly
2562 // reading the same memory from the inferior and comparing to make sure
2563 // everything is exactly the same.
2564 std::string verify_buf (size, '\0');
2565 assert (verify_buf.size() == size);
2566 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2567 Error verify_error;
2568 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2569 assert (cache_bytes_read == verify_bytes_read);
2570 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2571 assert (verify_error.Success() == error.Success());
2572 return cache_bytes_read;
2573 }
2574 return 0;
2575#else // !defined(VERIFY_MEMORY_READS)
2576 // Memory caching is enabled, without debug verification
2577
2578 return m_memory_cache.Read (addr, buf, size, error);
2579#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002580 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002581 else
2582 {
2583 // Memory caching is disabled
2584
2585 return ReadMemoryFromInferior (addr, buf, size, error);
2586 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002587}
Greg Clayton58be07b2011-01-07 06:08:19 +00002588
Greg Clayton4c82d422012-05-18 23:20:01 +00002589size_t
2590Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2591{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002592 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002593 out_str.clear();
2594 addr_t curr_addr = addr;
2595 while (1)
2596 {
2597 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2598 if (length == 0)
2599 break;
2600 out_str.append(buf, length);
2601 // If we got "length - 1" bytes, we didn't get the whole C string, we
2602 // need to read some more characters
2603 if (length == sizeof(buf) - 1)
2604 curr_addr += length;
2605 else
2606 break;
2607 }
2608 return out_str.size();
2609}
2610
Greg Clayton58be07b2011-01-07 06:08:19 +00002611
2612size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002613Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2614 size_t type_width)
2615{
2616 size_t total_bytes_read = 0;
2617 if (dst && max_bytes && type_width && max_bytes >= type_width)
2618 {
2619 // Ensure a null terminator independent of the number of bytes that is read.
2620 memset (dst, 0, max_bytes);
2621 size_t bytes_left = max_bytes - type_width;
2622
2623 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2624 assert(sizeof(terminator) >= type_width &&
2625 "Attempting to validate a string with more than 4 bytes per character!");
2626
2627 addr_t curr_addr = addr;
2628 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2629 char *curr_dst = dst;
2630
2631 error.Clear();
2632 while (bytes_left > 0 && error.Success())
2633 {
2634 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2635 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2636 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2637
2638 if (bytes_read == 0)
2639 break;
2640
2641 // Search for a null terminator of correct size and alignment in bytes_read
2642 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2643 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2644 if (::strncmp(&dst[i], terminator, type_width) == 0)
2645 {
2646 error.Clear();
2647 return i;
2648 }
2649
2650 total_bytes_read += bytes_read;
2651 curr_dst += bytes_read;
2652 curr_addr += bytes_read;
2653 bytes_left -= bytes_read;
2654 }
2655 }
2656 else
2657 {
2658 if (max_bytes)
2659 error.SetErrorString("invalid arguments");
2660 }
2661 return total_bytes_read;
2662}
2663
2664// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2665// null terminators.
2666size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002667Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002668{
2669 size_t total_cstr_len = 0;
2670 if (dst && dst_max_len)
2671 {
Greg Claytone91b7952011-12-15 03:14:23 +00002672 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002673 // NULL out everything just to be safe
2674 memset (dst, 0, dst_max_len);
2675 Error error;
2676 addr_t curr_addr = addr;
2677 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2678 size_t bytes_left = dst_max_len - 1;
2679 char *curr_dst = dst;
2680
2681 while (bytes_left > 0)
2682 {
2683 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2684 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2685 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2686
2687 if (bytes_read == 0)
2688 {
Greg Claytone91b7952011-12-15 03:14:23 +00002689 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002690 dst[total_cstr_len] = '\0';
2691 break;
2692 }
2693 const size_t len = strlen(curr_dst);
2694
2695 total_cstr_len += len;
2696
2697 if (len < bytes_to_read)
2698 break;
2699
2700 curr_dst += bytes_read;
2701 curr_addr += bytes_read;
2702 bytes_left -= bytes_read;
2703 }
2704 }
Greg Claytone91b7952011-12-15 03:14:23 +00002705 else
2706 {
2707 if (dst == NULL)
2708 result_error.SetErrorString("invalid arguments");
2709 else
2710 result_error.Clear();
2711 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002712 return total_cstr_len;
2713}
2714
2715size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002716Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2717{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718 if (buf == NULL || size == 0)
2719 return 0;
2720
2721 size_t bytes_read = 0;
2722 uint8_t *bytes = (uint8_t *)buf;
2723
2724 while (bytes_read < size)
2725 {
2726 const size_t curr_size = size - bytes_read;
2727 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2728 bytes + bytes_read,
2729 curr_size,
2730 error);
2731 bytes_read += curr_bytes_read;
2732 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2733 break;
2734 }
2735
2736 // Replace any software breakpoint opcodes that fall into this range back
2737 // into "buf" before we return
2738 if (bytes_read > 0)
2739 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2740 return bytes_read;
2741}
2742
Greg Clayton58a4c462010-12-16 20:01:20 +00002743uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002744Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002745{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002746 Scalar scalar;
2747 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2748 return scalar.ULongLong(fail_value);
2749 return fail_value;
2750}
2751
2752addr_t
2753Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2754{
2755 Scalar scalar;
2756 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2757 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2758 return LLDB_INVALID_ADDRESS;
2759}
2760
2761
2762bool
2763Process::WritePointerToMemory (lldb::addr_t vm_addr,
2764 lldb::addr_t ptr_value,
2765 Error &error)
2766{
2767 Scalar scalar;
2768 const uint32_t addr_byte_size = GetAddressByteSize();
2769 if (addr_byte_size <= 4)
2770 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002771 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002772 scalar = ptr_value;
2773 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002774}
2775
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002776size_t
2777Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2778{
2779 size_t bytes_written = 0;
2780 const uint8_t *bytes = (const uint8_t *)buf;
2781
2782 while (bytes_written < size)
2783 {
2784 const size_t curr_size = size - bytes_written;
2785 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2786 bytes + bytes_written,
2787 curr_size,
2788 error);
2789 bytes_written += curr_bytes_written;
2790 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2791 break;
2792 }
2793 return bytes_written;
2794}
2795
2796size_t
2797Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2798{
Greg Clayton58be07b2011-01-07 06:08:19 +00002799#if defined (ENABLE_MEMORY_CACHING)
2800 m_memory_cache.Flush (addr, size);
2801#endif
2802
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803 if (buf == NULL || size == 0)
2804 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002805
Jim Ingham4b536182011-08-09 02:12:22 +00002806 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002807
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808 // We need to write any data that would go where any current software traps
2809 // (enabled software breakpoints) any software traps (breakpoints) that we
2810 // may have placed in our tasks memory.
2811
Greg Claytond8cf1a12013-06-12 00:46:38 +00002812 BreakpointSiteList bp_sites_in_range;
2813
2814 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002816 // No breakpoint sites overlap
2817 if (bp_sites_in_range.IsEmpty())
2818 return WriteMemoryPrivate (addr, buf, size, error);
2819 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002820 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002821 const uint8_t *ubuf = (const uint8_t *)buf;
2822 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823
Greg Claytond8cf1a12013-06-12 00:46:38 +00002824 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2825
2826 if (error.Success())
2827 {
2828 addr_t intersect_addr;
2829 size_t intersect_size;
2830 size_t opcode_offset;
2831 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2832 assert(intersects);
2833 assert(addr <= intersect_addr && intersect_addr < addr + size);
2834 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2835 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2836
2837 // Check for bytes before this breakpoint
2838 const addr_t curr_addr = addr + bytes_written;
2839 if (intersect_addr > curr_addr)
2840 {
2841 // There are some bytes before this breakpoint that we need to
2842 // just write to memory
2843 size_t curr_size = intersect_addr - curr_addr;
2844 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2845 ubuf + bytes_written,
2846 curr_size,
2847 error);
2848 bytes_written += curr_bytes_written;
2849 if (curr_bytes_written != curr_size)
2850 {
2851 // We weren't able to write all of the requested bytes, we
2852 // are done looping and will return the number of bytes that
2853 // we have written so far.
2854 if (error.Success())
2855 error.SetErrorToGenericError();
2856 }
2857 }
2858 // Now write any bytes that would cover up any software breakpoints
2859 // directly into the breakpoint opcode buffer
2860 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2861 bytes_written += intersect_size;
2862 }
2863 });
2864
2865 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002866 WriteMemoryPrivate (addr + bytes_written,
2867 ubuf + bytes_written,
2868 size - bytes_written,
2869 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002870 }
2871 }
2872 else
2873 {
2874 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875 }
2876
2877 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002878 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002879}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002880
2881size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002882Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002883{
2884 if (byte_size == UINT32_MAX)
2885 byte_size = scalar.GetByteSize();
2886 if (byte_size > 0)
2887 {
2888 uint8_t buf[32];
2889 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2890 if (mem_size > 0)
2891 return WriteMemory(addr, buf, mem_size, error);
2892 else
2893 error.SetErrorString ("failed to get scalar as memory data");
2894 }
2895 else
2896 {
2897 error.SetErrorString ("invalid scalar value");
2898 }
2899 return 0;
2900}
2901
2902size_t
2903Process::ReadScalarIntegerFromMemory (addr_t addr,
2904 uint32_t byte_size,
2905 bool is_signed,
2906 Scalar &scalar,
2907 Error &error)
2908{
Greg Clayton7060f892013-05-01 23:41:30 +00002909 uint64_t uval = 0;
2910 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002911 {
Greg Clayton7060f892013-05-01 23:41:30 +00002912 error.SetErrorString ("byte size is zero");
2913 }
2914 else if (byte_size & (byte_size - 1))
2915 {
2916 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2917 }
2918 else if (byte_size <= sizeof(uval))
2919 {
2920 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002921 if (bytes_read == byte_size)
2922 {
2923 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002924 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002925 if (byte_size <= 4)
2926 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002927 else
Greg Clayton7060f892013-05-01 23:41:30 +00002928 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002929 if (is_signed)
2930 scalar.SignExtend(byte_size * 8);
2931 return bytes_read;
2932 }
2933 }
2934 else
2935 {
2936 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2937 }
2938 return 0;
2939}
2940
Greg Claytond495c532011-05-17 03:37:42 +00002941#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942addr_t
2943Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2944{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002945 if (GetPrivateState() != eStateStopped)
2946 return LLDB_INVALID_ADDRESS;
2947
Greg Claytond495c532011-05-17 03:37:42 +00002948#if defined (USE_ALLOCATE_MEMORY_CACHE)
2949 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2950#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002951 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002952 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002953 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002954 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 +00002955 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002956 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002957 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002958 m_mod_id.GetStopID(),
2959 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002960 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002961#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002962}
2963
Sean Callanan90539452011-09-20 23:01:51 +00002964bool
2965Process::CanJIT ()
2966{
Sean Callanana7b443a2012-02-14 22:50:38 +00002967 if (m_can_jit == eCanJITDontKnow)
2968 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002969 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002970 Error err;
2971
2972 uint64_t allocated_memory = AllocateMemory(8,
2973 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2974 err);
2975
2976 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002977 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002978 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002979 if (log)
2980 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2981 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002982 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002983 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002984 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002985 if (log)
2986 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2987 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002988
2989 DeallocateMemory (allocated_memory);
2990 }
2991
Sean Callanan90539452011-09-20 23:01:51 +00002992 return m_can_jit == eCanJITYes;
2993}
2994
2995void
2996Process::SetCanJIT (bool can_jit)
2997{
2998 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2999}
3000
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001Error
3002Process::DeallocateMemory (addr_t ptr)
3003{
Greg Claytond495c532011-05-17 03:37:42 +00003004 Error error;
3005#if defined (USE_ALLOCATE_MEMORY_CACHE)
3006 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
3007 {
Daniel Malead01b2952012-11-29 21:49:15 +00003008 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00003009 }
3010#else
3011 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00003012
Greg Clayton5160ce52013-03-27 23:08:40 +00003013 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00003014 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003015 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 +00003016 ptr,
3017 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00003018 m_mod_id.GetStopID(),
3019 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00003020#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00003021 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022}
3023
Han Ming Ongc811d382012-11-17 00:33:14 +00003024
Greg Claytonc9660542012-02-05 02:38:54 +00003025ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00003026Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00003027 lldb::addr_t header_addr,
3028 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00003029{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003030 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00003031 if (module_sp)
3032 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003033 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00003034 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003035 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003036 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00003037 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003038 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00003039}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040
Zachary Turner93749ab2015-03-03 21:51:25 +00003041bool
3042Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3043{
3044 MemoryRegionInfo range_info;
3045 permissions = 0;
3046 Error error (GetMemoryRegionInfo (load_addr, range_info));
3047 if (!error.Success())
3048 return false;
3049 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3050 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3051 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3052 {
3053 return false;
3054 }
3055
3056 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3057 permissions |= lldb::ePermissionsReadable;
3058
3059 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3060 permissions |= lldb::ePermissionsWritable;
3061
3062 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3063 permissions |= lldb::ePermissionsExecutable;
3064
3065 return true;
3066}
3067
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003069Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003070{
3071 Error error;
3072 error.SetErrorString("watchpoints are not supported");
3073 return error;
3074}
3075
3076Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003077Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078{
3079 Error error;
3080 error.SetErrorString("watchpoints are not supported");
3081 return error;
3082}
3083
3084StateType
3085Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3086{
3087 StateType state;
3088 // Now wait for the process to launch and return control to us, and then
3089 // call DidLaunch:
3090 while (1)
3091 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003092 event_sp.reset();
3093 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3094
Greg Clayton2637f822011-11-17 01:23:07 +00003095 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003097
3098 // If state is invalid, then we timed out
3099 if (state == eStateInvalid)
3100 break;
3101
3102 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003103 HandlePrivateEvent (event_sp);
3104 }
3105 return state;
3106}
3107
Greg Clayton332e8b12015-01-13 21:13:08 +00003108void
3109Process::LoadOperatingSystemPlugin(bool flush)
3110{
3111 if (flush)
3112 m_thread_list.Clear();
3113 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3114 if (flush)
3115 Flush();
3116}
3117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003118Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003119Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003120{
3121 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003123 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003124 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003125 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003126 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003127 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003128 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129
Greg Claytonaa149cb2011-08-11 02:48:45 +00003130 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131 if (exe_module)
3132 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003133 char local_exec_file_path[PATH_MAX];
3134 char platform_exec_file_path[PATH_MAX];
3135 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3136 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 if (exe_module->GetFileSpec().Exists())
3138 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003139 // Install anything that might need to be installed prior to launching.
3140 // For host systems, this will do nothing, but if we are connected to a
3141 // remote platform it will install any needed binaries
3142 error = GetTarget().Install(&launch_info);
3143 if (error.Fail())
3144 return error;
3145
Greg Clayton71337622011-02-24 22:24:29 +00003146 if (PrivateStateThreadIsValid ())
3147 PausePrivateStateThread ();
3148
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003149 error = WillLaunch (exe_module);
3150 if (error.Success())
3151 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003152 const bool restarted = false;
3153 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003154 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155
Ed Maste64fad602013-07-29 20:58:06 +00003156 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003157 {
3158 // Now launch using these arguments.
3159 error = DoLaunch (exe_module, launch_info);
3160 }
3161 else
3162 {
3163 // This shouldn't happen
3164 error.SetErrorString("failed to acquire process run lock");
3165 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166
3167 if (error.Fail())
3168 {
3169 if (GetID() != LLDB_INVALID_PROCESS_ID)
3170 {
3171 SetID (LLDB_INVALID_PROCESS_ID);
3172 const char *error_string = error.AsCString();
3173 if (error_string == NULL)
3174 error_string = "launch failed";
3175 SetExitStatus (-1, error_string);
3176 }
3177 }
3178 else
3179 {
3180 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003181 TimeValue timeout_time;
3182 timeout_time = TimeValue::Now();
3183 timeout_time.OffsetWithSeconds(10);
3184 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003185
Greg Clayton1a38ea72011-06-22 01:42:17 +00003186 if (state == eStateInvalid || event_sp.get() == NULL)
3187 {
3188 // We were able to launch the process, but we failed to
3189 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003190 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003191 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003192 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003193 }
3194 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003196
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003197 DidLaunch ();
3198
Greg Claytonc859e2d2012-02-13 23:10:39 +00003199 DynamicLoader *dyld = GetDynamicLoader ();
3200 if (dyld)
3201 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003202
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003203 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003204
Jason Molendaeef51062013-11-05 03:57:19 +00003205 SystemRuntime *system_runtime = GetSystemRuntime ();
3206 if (system_runtime)
3207 system_runtime->DidLaunch();
3208
Greg Clayton332e8b12015-01-13 21:13:08 +00003209 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003210
3211 // Note, the stop event was consumed above, but not handled. This was done
3212 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3213 // Directly set the state. This is done to prevent a stop message with a bunch
3214 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3215 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003216
3217 if (PrivateStateThreadIsValid ())
3218 ResumePrivateStateThread ();
3219 else
3220 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003221
3222 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003223
3224 // Target was stopped at entry as was intended. Need to notify the listeners
3225 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003226 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003227 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 }
3229 else if (state == eStateExited)
3230 {
3231 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3232 // not likely to work, and return an invalid pid.
3233 HandlePrivateEvent (event_sp);
3234 }
3235 }
3236 }
3237 }
3238 else
3239 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003240 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003241 }
3242 }
3243 return error;
3244}
3245
Greg Claytonc3776bf2012-02-09 06:16:32 +00003246
3247Error
3248Process::LoadCore ()
3249{
3250 Error error = DoLoadCore();
3251 if (error.Success())
3252 {
Greg Clayton35824e32015-02-20 20:59:47 +00003253 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003254 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003255
Greg Claytonc3776bf2012-02-09 06:16:32 +00003256 if (PrivateStateThreadIsValid ())
3257 ResumePrivateStateThread ();
3258 else
3259 StartPrivateStateThread ();
3260
Greg Claytonc859e2d2012-02-13 23:10:39 +00003261 DynamicLoader *dyld = GetDynamicLoader ();
3262 if (dyld)
3263 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003264
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003265 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003266
Jason Molendaeef51062013-11-05 03:57:19 +00003267 SystemRuntime *system_runtime = GetSystemRuntime ();
3268 if (system_runtime)
3269 system_runtime->DidAttach();
3270
Greg Claytonc859e2d2012-02-13 23:10:39 +00003271 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003272 // We successfully loaded a core file, now pretend we stopped so we can
3273 // show all of the threads in the core file and explore the crashed
3274 // state.
3275 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003276
3277 // Wait indefinitely for a stopped event since we just posted one above...
3278 lldb::EventSP event_sp;
3279 listener.WaitForEvent (NULL, event_sp);
3280 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3281
3282 if (!StateIsStoppedState (state, false))
3283 {
3284 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3285 if (log)
3286 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3287 error.SetErrorString ("Did not get stopped event after loading the core file.");
3288 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003289 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003290 }
3291 return error;
3292}
3293
Greg Claytonc859e2d2012-02-13 23:10:39 +00003294DynamicLoader *
3295Process::GetDynamicLoader ()
3296{
3297 if (m_dyld_ap.get() == NULL)
3298 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3299 return m_dyld_ap.get();
3300}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003301
Todd Fialaaf245d12014-06-30 21:05:18 +00003302const lldb::DataBufferSP
3303Process::GetAuxvData()
3304{
3305 return DataBufferSP ();
3306}
3307
Andrew MacPherson17220c12014-03-05 10:12:43 +00003308JITLoaderList &
3309Process::GetJITLoaders ()
3310{
3311 if (!m_jit_loaders_ap)
3312 {
3313 m_jit_loaders_ap.reset(new JITLoaderList());
3314 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3315 }
3316 return *m_jit_loaders_ap;
3317}
3318
Jason Molendaeef51062013-11-05 03:57:19 +00003319SystemRuntime *
3320Process::GetSystemRuntime ()
3321{
3322 if (m_system_runtime_ap.get() == NULL)
3323 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3324 return m_system_runtime_ap.get();
3325}
3326
Todd Fiala76e0fc92014-08-27 22:58:26 +00003327Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3328 NextEventAction (process),
3329 m_exec_count (exec_count)
3330{
3331 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3332 if (log)
3333 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3334}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003335
Jim Inghambb3a2832011-01-29 01:49:25 +00003336Process::NextEventAction::EventActionResult
3337Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003338{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003339 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3340
Jim Inghambb3a2832011-01-29 01:49:25 +00003341 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003342 if (log)
3343 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3344
3345 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003346 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003347 case eStateAttaching:
3348 return eEventActionSuccess;
3349
Greg Clayton513c26c2011-01-29 07:10:55 +00003350 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003351 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003352 return eEventActionRetry;
3353
3354 case eStateStopped:
3355 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003356 {
3357 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003358 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003359 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003360 // We don't want these events to be reported, so go set the ShouldReportStop here:
3361 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3362
Greg Claytonc9ed4782011-11-12 02:10:56 +00003363 if (m_exec_count > 0)
3364 {
3365 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003366
3367 if (log)
3368 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3369
Jim Ingham221d51c2013-05-08 00:35:16 +00003370 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003371 return eEventActionRetry;
3372 }
3373 else
3374 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003375 if (log)
3376 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3377
Greg Claytonc9ed4782011-11-12 02:10:56 +00003378 m_process->CompleteAttach ();
3379 return eEventActionSuccess;
3380 }
3381 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003382 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003383
Greg Clayton513c26c2011-01-29 07:10:55 +00003384 default:
3385 case eStateExited:
3386 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003387 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003388 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003389
3390 m_exit_string.assign ("No valid Process");
3391 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003392}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393
Jim Inghambb3a2832011-01-29 01:49:25 +00003394Process::NextEventAction::EventActionResult
3395Process::AttachCompletionHandler::HandleBeingInterrupted()
3396{
3397 return eEventActionSuccess;
3398}
3399
3400const char *
3401Process::AttachCompletionHandler::GetExitString ()
3402{
3403 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404}
3405
Greg Clayton8012cad2014-11-17 19:39:20 +00003406Listener &
3407ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3408{
3409 if (m_listener_sp)
3410 return *m_listener_sp;
3411 else
3412 return debugger.GetListener();
3413}
3414
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003416Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003417{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003418 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003419 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003420 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003421 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003422 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003423 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003424 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003425
Greg Clayton144f3a92011-11-15 03:53:30 +00003426 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003427 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003428 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003429 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003430 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003431
Greg Clayton144f3a92011-11-15 03:53:30 +00003432 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003433 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003434 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3435
3436 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003438 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3439 if (error.Success())
3440 {
Ed Maste64fad602013-07-29 20:58:06 +00003441 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003442 {
3443 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003444 const bool restarted = false;
3445 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003446 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003447 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003448 }
3449 else
3450 {
3451 // This shouldn't happen
3452 error.SetErrorString("failed to acquire process run lock");
3453 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003454
Greg Clayton144f3a92011-11-15 03:53:30 +00003455 if (error.Fail())
3456 {
3457 if (GetID() != LLDB_INVALID_PROCESS_ID)
3458 {
3459 SetID (LLDB_INVALID_PROCESS_ID);
3460 if (error.AsCString() == NULL)
3461 error.SetErrorString("attach failed");
3462
3463 SetExitStatus(-1, error.AsCString());
3464 }
3465 }
3466 else
3467 {
3468 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3469 StartPrivateStateThread();
3470 }
3471 return error;
3472 }
Greg Claytone996fd32011-03-08 22:40:15 +00003473 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003474 else
Greg Claytone996fd32011-03-08 22:40:15 +00003475 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003476 ProcessInstanceInfoList process_infos;
3477 PlatformSP platform_sp (m_target.GetPlatform ());
3478
3479 if (platform_sp)
3480 {
3481 ProcessInstanceInfoMatch match_info;
3482 match_info.GetProcessInfo() = attach_info;
3483 match_info.SetNameMatchType (eNameMatchEquals);
3484 platform_sp->FindProcesses (match_info, process_infos);
3485 const uint32_t num_matches = process_infos.GetSize();
3486 if (num_matches == 1)
3487 {
3488 attach_pid = process_infos.GetProcessIDAtIndex(0);
3489 // Fall through and attach using the above process ID
3490 }
3491 else
3492 {
3493 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3494 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003495 {
3496 StreamString s;
3497 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3498 for (size_t i = 0; i < num_matches; i++)
3499 {
3500 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3501 }
3502 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3503 process_name,
3504 s.GetData());
3505 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003506 else
3507 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3508 }
3509 }
3510 else
3511 {
3512 error.SetErrorString ("invalid platform, can't find processes by name");
3513 return error;
3514 }
Greg Claytone996fd32011-03-08 22:40:15 +00003515 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003516 }
3517 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003518 {
3519 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003520 }
3521 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003522
3523 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003524 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003525 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003526 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003527 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003528
Ed Maste64fad602013-07-29 20:58:06 +00003529 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003530 {
3531 // Now attach using these arguments.
3532 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003533 const bool restarted = false;
3534 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003535 error = DoAttachToProcessWithID (attach_pid, attach_info);
3536 }
3537 else
3538 {
3539 // This shouldn't happen
3540 error.SetErrorString("failed to acquire process run lock");
3541 }
3542
Greg Clayton144f3a92011-11-15 03:53:30 +00003543 if (error.Success())
3544 {
3545
3546 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3547 StartPrivateStateThread();
3548 }
3549 else
Greg Claytone996fd32011-03-08 22:40:15 +00003550 {
3551 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003552 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003553
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003554 const char *error_string = error.AsCString();
3555 if (error_string == NULL)
3556 error_string = "attach failed";
3557
3558 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003559 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560 }
3561 }
3562 return error;
3563}
3564
Greg Clayton93d3c8332011-02-16 04:46:07 +00003565void
3566Process::CompleteAttach ()
3567{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003568 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3569 if (log)
3570 log->Printf ("Process::%s()", __FUNCTION__);
3571
Greg Clayton93d3c8332011-02-16 04:46:07 +00003572 // Let the process subclass figure out at much as it can about the process
3573 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003574 ArchSpec process_arch;
3575 DidAttach(process_arch);
3576
3577 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003578 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003579 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003580 if (log)
3581 {
3582 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3583 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3584 __FUNCTION__,
3585 triple_str ? triple_str : "<null>");
3586 }
3587 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003588
Jim Ingham4299fdb2011-09-15 01:10:17 +00003589 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3590 // the same as the one we've already set, switch architectures.
3591 PlatformSP platform_sp (m_target.GetPlatform ());
3592 assert (platform_sp.get());
3593 if (platform_sp)
3594 {
Greg Clayton70512312012-05-08 01:45:38 +00003595 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003596 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003597 {
3598 ArchSpec platform_arch;
3599 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3600 if (platform_sp)
3601 {
3602 m_target.SetPlatform (platform_sp);
3603 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003604 if (log)
3605 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 +00003606 }
3607 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003608 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003609 {
3610 ProcessInstanceInfo process_info;
3611 platform_sp->GetProcessInfo (GetID(), process_info);
3612 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003613 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003614 {
Greg Clayton70512312012-05-08 01:45:38 +00003615 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003616 if (log)
3617 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 ());
3618 }
Greg Clayton70512312012-05-08 01:45:38 +00003619 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003620 }
3621
3622 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003623 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003624 DynamicLoader *dyld = GetDynamicLoader ();
3625 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003626 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003627 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003628 if (log)
3629 {
3630 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3631 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3632 __FUNCTION__,
3633 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3634 dyld->GetPluginName().AsCString ("<unnamed>"));
3635 }
3636 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003637
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003638 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003639
Jason Molendaeef51062013-11-05 03:57:19 +00003640 SystemRuntime *system_runtime = GetSystemRuntime ();
3641 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003642 {
Jason Molendaeef51062013-11-05 03:57:19 +00003643 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003644 if (log)
3645 {
3646 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3647 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3648 __FUNCTION__,
3649 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3650 system_runtime->GetPluginName().AsCString("<unnamed>"));
3651 }
3652 }
Jason Molendaeef51062013-11-05 03:57:19 +00003653
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003654 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003655 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003656 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003657 Mutex::Locker modules_locker(target_modules.GetMutex());
3658 size_t num_modules = target_modules.GetSize();
3659 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003660
Andy Gibbsa297a972013-06-19 19:04:53 +00003661 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003662 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003663 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003664 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003665 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003666 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003667 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003668 break;
3669 }
3670 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003671 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003672 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003673 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003674 if (log)
3675 {
3676 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3677 log->Printf ("Process::%s after looping through modules, target executable is %s",
3678 __FUNCTION__,
3679 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3680 }
3681 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003682
3683 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003684}
3685
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003686Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003687Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003688{
Greg Claytonb766a732011-02-04 01:58:07 +00003689 m_abi_sp.reset();
3690 m_process_input_reader.reset();
3691
3692 // Find the process and its architecture. Make sure it matches the architecture
3693 // of the current Target, and if not adjust it.
3694
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003695 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003696 if (error.Success())
3697 {
Greg Clayton71337622011-02-24 22:24:29 +00003698 if (GetID() != LLDB_INVALID_PROCESS_ID)
3699 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003700 EventSP event_sp;
3701 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3702
3703 if (state == eStateStopped || state == eStateCrashed)
3704 {
3705 // If we attached and actually have a process on the other end, then
3706 // this ended up being the equivalent of an attach.
3707 CompleteAttach ();
3708
3709 // This delays passing the stopped event to listeners till
3710 // CompleteAttach gets a chance to complete...
3711 HandlePrivateEvent (event_sp);
3712
3713 }
Greg Clayton71337622011-02-24 22:24:29 +00003714 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003715
3716 if (PrivateStateThreadIsValid ())
3717 ResumePrivateStateThread ();
3718 else
3719 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003720 }
3721 return error;
3722}
3723
3724
3725Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003726Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003727{
Greg Clayton5160ce52013-03-27 23:08:40 +00003728 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003730 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003731 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003732 StateAsCString(m_public_state.GetValue()),
3733 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003734
3735 Error error (WillResume());
3736 // Tell the process it is about to resume before the thread list
3737 if (error.Success())
3738 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003739 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003740 // can let all of our threads know that they are about to be
3741 // resumed. Threads will each be called with
3742 // Thread::WillResume(StateType) where StateType contains the state
3743 // that they are supposed to have when the process is resumed
3744 // (suspended/running/stepping). Threads should also check
3745 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003746 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747 if (m_thread_list.WillResume())
3748 {
Jim Ingham372787f2012-04-07 00:00:41 +00003749 // Last thing, do the PreResumeActions.
3750 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003751 {
Jim Ingham0161b492013-02-09 01:29:05 +00003752 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003753 }
3754 else
3755 {
3756 m_mod_id.BumpResumeID();
3757 error = DoResume();
3758 if (error.Success())
3759 {
3760 DidResume();
3761 m_thread_list.DidResume();
3762 if (log)
3763 log->Printf ("Process thinks the process has resumed.");
3764 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 }
3766 }
3767 else
3768 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003769 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3770 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003771 // and let the world handle them.
3772 if (log)
3773 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3774
3775 SetPrivateState(eStateRunning);
3776 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777 }
3778 }
Jim Ingham444586b2011-01-24 06:34:17 +00003779 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003780 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003781 return error;
3782}
3783
3784Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003785Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003786{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003787 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3788 // in case it was already set and some thread plan logic calls halt on its
3789 // own.
3790 m_clear_thread_plans_on_stop |= clear_thread_plans;
3791
Jim Inghamaacc3182012-06-06 00:29:30 +00003792 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3793 // we could just straightaway get another event. It just narrows the window...
3794 m_currently_handling_event.WaitForValueEqualTo(false);
3795
3796
Jim Inghambb3a2832011-01-29 01:49:25 +00003797 // Pause our private state thread so we can ensure no one else eats
3798 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003799 Listener halt_listener ("lldb.process.halt_listener");
3800 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003801
Jim Inghambb3a2832011-01-29 01:49:25 +00003802 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003803 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003804
Greg Clayton06357c92014-07-30 17:38:47 +00003805 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003806 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003807 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003808
Greg Clayton513c26c2011-01-29 07:10:55 +00003809 bool caused_stop = false;
3810
3811 // Ask the process subclass to actually halt our process
3812 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003813 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003814 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003815 if (m_public_state.GetValue() == eStateAttaching)
3816 {
Greg Clayton06357c92014-07-30 17:38:47 +00003817 // Don't hijack and eat the eStateExited as the code that was doing
3818 // the attach will be waiting for this event...
3819 RestorePrivateProcessEvents();
3820 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003821 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:58 +00003822 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:55 +00003823 }
3824 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003825 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003826 // If "caused_stop" is true, then DoHalt stopped the process. If
3827 // "caused_stop" is false, the process was already stopped.
3828 // If the DoHalt caused the process to stop, then we want to catch
3829 // this event and set the interrupted bool to true before we pass
3830 // this along so clients know that the process was interrupted by
3831 // a halt command.
3832 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003833 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003834 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003835 TimeValue timeout_time;
3836 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003837 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003838 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3839 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003840
Jim Ingham0f16e732011-02-08 05:20:59 +00003841 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003842 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003843 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003844 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003845 }
3846 else
3847 {
Greg Clayton2637f822011-11-17 01:23:07 +00003848 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003849 {
3850 // We caused the process to interrupt itself, so mark this
3851 // as such in the stop event so clients can tell an interrupted
3852 // process from a natural stop
3853 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3854 }
3855 else
3856 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003857 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003858 if (log)
3859 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3860 error.SetErrorString ("Did not get stopped event after halt.");
3861 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003862 }
3863 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003864 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003865 }
3866 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003868 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003869 if (!restored_process_events)
3870 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003871
3872 // Post any event we might have consumed. If all goes well, we will have
3873 // stopped the process, intercepted the event and set the interrupted
3874 // bool in the event. Post it to the private event queue and that will end up
3875 // correctly setting the state.
3876 if (event_sp)
3877 m_private_state_broadcaster.BroadcastEvent(event_sp);
3878
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879 return error;
3880}
3881
3882Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003883Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3884{
3885 Error error;
3886 if (m_public_state.GetValue() == eStateRunning)
3887 {
3888 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3889 if (log)
3890 log->Printf("Process::Destroy() About to halt.");
3891 error = Halt();
3892 if (error.Success())
3893 {
3894 // Consume the halt event.
3895 TimeValue timeout (TimeValue::Now());
3896 timeout.OffsetWithSeconds(1);
3897 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3898
3899 // If the process exited while we were waiting for it to stop, put the exited event into
3900 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3901 // they don't have a process anymore...
3902
3903 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3904 {
3905 if (log)
3906 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3907 return error;
3908 }
3909 else
3910 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3911
3912 if (state != eStateStopped)
3913 {
3914 if (log)
3915 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3916 // If we really couldn't stop the process then we should just error out here, but if the
3917 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3918 StateType private_state = m_private_state.GetValue();
3919 if (private_state != eStateStopped)
3920 {
3921 return error;
3922 }
3923 }
3924 }
3925 else
3926 {
3927 if (log)
3928 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3929 }
3930 }
3931 return error;
3932}
3933
3934Error
Jim Inghamacff8952013-05-02 00:27:30 +00003935Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003936{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003937 EventSP exit_event_sp;
3938 Error error;
3939 m_destroy_in_process = true;
3940
3941 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003942
3943 if (error.Success())
3944 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003945 if (DetachRequiresHalt())
3946 {
3947 error = HaltForDestroyOrDetach (exit_event_sp);
3948 if (!error.Success())
3949 {
3950 m_destroy_in_process = false;
3951 return error;
3952 }
3953 else if (exit_event_sp)
3954 {
3955 // We shouldn't need to do anything else here. There's no process left to detach from...
3956 StopPrivateStateThread();
3957 m_destroy_in_process = false;
3958 return error;
3959 }
3960 }
3961
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003962 m_thread_list.DiscardThreadPlans();
3963 DisableAllBreakpointSites();
3964
Jim Inghamacff8952013-05-02 00:27:30 +00003965 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003966 if (error.Success())
3967 {
3968 DidDetach();
3969 StopPrivateStateThread();
3970 }
Jim Inghamacff8952013-05-02 00:27:30 +00003971 else
3972 {
3973 return error;
3974 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003975 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003976 m_destroy_in_process = false;
3977
3978 // If we exited when we were waiting for a process to stop, then
3979 // forward the event here so we don't lose the event
3980 if (exit_event_sp)
3981 {
3982 // Directly broadcast our exited event because we shut down our
3983 // private state thread above
3984 BroadcastEvent(exit_event_sp);
3985 }
3986
3987 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3988 // the last events through the event system, in which case we might strand the write lock. Unlock
3989 // it here so when we do to tear down the process we don't get an error destroying the lock.
3990
Ed Maste64fad602013-07-29 20:58:06 +00003991 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003992 return error;
3993}
3994
3995Error
Jason Molendaede31932015-04-17 05:01:58 +00003996Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003997{
Jim Ingham09437922013-03-01 20:04:25 +00003998
3999 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
4000 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
4001 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00004002
4003 if (force_kill)
4004 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00004005
Ilia Kfcc89a02015-03-26 07:08:47 +00004006 if (GetShouldDetach())
4007 {
4008 // FIXME: This will have to be a process setting:
4009 bool keep_stopped = false;
4010 Detach(keep_stopped);
4011 }
4012
Jim Ingham09437922013-03-01 20:04:25 +00004013 m_destroy_in_process = true;
4014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004015 Error error (WillDestroy());
4016 if (error.Success())
4017 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00004018 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004019 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00004020 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004021 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00004022 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004023
Jim Inghamaacc3182012-06-06 00:29:30 +00004024 if (m_public_state.GetValue() != eStateRunning)
4025 {
4026 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4027 // kill it, we don't want it hitting a breakpoint...
4028 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4029 // we're not going to have much luck doing this now.
4030 m_thread_list.DiscardThreadPlans();
4031 DisableAllBreakpointSites();
4032 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004033
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004034 error = DoDestroy();
4035 if (error.Success())
4036 {
4037 DidDestroy();
4038 StopPrivateStateThread();
4039 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004040 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00004041 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:04 +00004042 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00004043
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004044 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00004045 {
4046 m_process_input_reader->SetIsDone(true);
4047 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004048 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00004049 }
4050
Greg Clayton85fb1b92012-09-11 02:33:37 +00004051 // If we exited when we were waiting for a process to stop, then
4052 // forward the event here so we don't lose the event
4053 if (exit_event_sp)
4054 {
4055 // Directly broadcast our exited event because we shut down our
4056 // private state thread above
4057 BroadcastEvent(exit_event_sp);
4058 }
4059
Jim Inghamb1e2e842012-04-12 18:49:31 +00004060 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4061 // the last events through the event system, in which case we might strand the write lock. Unlock
4062 // 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 +00004063 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004064 }
Jim Ingham09437922013-03-01 20:04:25 +00004065
4066 m_destroy_in_process = false;
4067
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004068 return error;
4069}
4070
4071Error
4072Process::Signal (int signal)
4073{
4074 Error error (WillSignal());
4075 if (error.Success())
4076 {
4077 error = DoSignal(signal);
4078 if (error.Success())
4079 DidSignal();
4080 }
4081 return error;
4082}
4083
Zachary Turner93749ab2015-03-03 21:51:25 +00004084void
4085Process::SetUnixSignals (const UnixSignalsSP &signals_sp)
4086{
4087 assert (signals_sp && "null signals_sp");
4088 m_unix_signals_sp = signals_sp;
4089}
4090
4091UnixSignals &
4092Process::GetUnixSignals ()
4093{
4094 assert (m_unix_signals_sp && "null m_unix_signals_sp");
4095 return *m_unix_signals_sp;
4096}
4097
Greg Clayton514487e2011-02-15 21:59:32 +00004098lldb::ByteOrder
4099Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100{
Greg Clayton514487e2011-02-15 21:59:32 +00004101 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102}
4103
4104uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00004105Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004106{
Greg Clayton514487e2011-02-15 21:59:32 +00004107 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004108}
4109
Greg Clayton514487e2011-02-15 21:59:32 +00004110
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004111bool
4112Process::ShouldBroadcastEvent (Event *event_ptr)
4113{
4114 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4115 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00004116 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00004117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004118 switch (state)
4119 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004120 case eStateDetached:
4121 case eStateExited:
4122 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00004123 m_stdio_communication.SynchronizeWithReadThread();
4124 // fall-through
4125 case eStateConnected:
4126 case eStateAttaching:
4127 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128 // These events indicate changes in the state of the debugging session, always report them.
4129 return_value = true;
4130 break;
4131 case eStateInvalid:
4132 // We stopped for no apparent reason, don't report it.
4133 return_value = false;
4134 break;
4135 case eStateRunning:
4136 case eStateStepping:
4137 // If we've started the target running, we handle the cases where we
4138 // are already running and where there is a transition from stopped to
4139 // running differently.
4140 // running -> running: Automatically suppress extra running events
4141 // stopped -> running: Report except when there is one or more no votes
4142 // and no yes votes.
4143 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004144 if (m_force_next_event_delivery)
4145 return_value = true;
4146 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004148 switch (m_last_broadcast_state)
4149 {
4150 case eStateRunning:
4151 case eStateStepping:
4152 // We always suppress multiple runnings with no PUBLIC stop in between.
4153 return_value = false;
4154 break;
4155 default:
4156 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004157 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004158 // events. If I run the lldb/test/thread/a.out file and
4159 // break at main.cpp:58, run and hit the breakpoints on
4160 // multiple threads, then somehow during the stepping over
4161 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004162
Jim Ingham1460e4b2014-01-10 23:46:59 +00004163 // This is a transition from stop to run.
4164 switch (m_thread_list.ShouldReportRun (event_ptr))
4165 {
4166 case eVoteYes:
4167 case eVoteNoOpinion:
4168 return_value = true;
4169 break;
4170 case eVoteNo:
4171 return_value = false;
4172 break;
4173 }
4174 break;
4175 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004176 }
4177 break;
4178 case eStateStopped:
4179 case eStateCrashed:
4180 case eStateSuspended:
4181 {
4182 // We've stopped. First see if we're going to restart the target.
4183 // If we are going to stop, then we always broadcast the event.
4184 // 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 +00004185 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004186
Pavel Labath3f5df532015-03-12 10:12:41 +00004187 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00004188 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004189 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004190 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004191 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004192 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004193 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004194 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004195 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4196 // so they can properly set their state.
4197 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004198 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004199 }
4200 else
4201 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004202 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4203 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004204
Jim Ingham0161b492013-02-09 01:29:05 +00004205 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4206 // Asking the thread list is also not likely to go well, since we are running again.
4207 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004208
Jim Ingham0161b492013-02-09 01:29:05 +00004209 if (!was_restarted)
4210 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004211
Jim Ingham221d51c2013-05-08 00:35:16 +00004212 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213 {
Jim Ingham0161b492013-02-09 01:29:05 +00004214 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4215 if (log)
4216 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004217 should_resume, StateAsCString(state),
4218 was_restarted, stop_vote);
4219
Jim Ingham0161b492013-02-09 01:29:05 +00004220 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004221 {
4222 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004223 return_value = true;
4224 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004226 case eVoteNo:
4227 return_value = false;
4228 break;
4229 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004230
Jim Inghamcb95f342012-09-05 21:13:56 +00004231 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004232 {
4233 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004234 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4235 static_cast<void*>(event_ptr),
4236 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004237 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004238 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004239 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004240
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004241 }
4242 else
4243 {
4244 return_value = true;
4245 SynchronouslyNotifyStateChanged (state);
4246 }
4247 }
4248 }
Jim Ingham0161b492013-02-09 01:29:05 +00004249 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004250 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004251
Jim Ingham1460e4b2014-01-10 23:46:59 +00004252 // Forcing the next event delivery is a one shot deal. So reset it here.
4253 m_force_next_event_delivery = false;
4254
Jim Ingham0161b492013-02-09 01:29:05 +00004255 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4256 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4257 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4258 // because the PublicState reflects the last event pulled off the queue, and there may be several
4259 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4260 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004261
Jim Ingham0161b492013-02-09 01:29:05 +00004262 if (return_value)
4263 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004264
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004265 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004266 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004267 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004268 StateAsCString(m_last_broadcast_state),
4269 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004270 return return_value;
4271}
4272
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004273
4274bool
Jim Ingham60c915e2015-06-23 21:02:45 +00004275Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004276{
Greg Clayton5160ce52013-03-27 23:08:40 +00004277 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278
Greg Clayton8b82f082011-04-12 05:54:46 +00004279 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004280 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004281 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4282
Jim Ingham60c915e2015-06-23 21:02:45 +00004283 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004284 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004285
4286 // Create a thread that watches our internal state and controls which
4287 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004288 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004289
Zachary Turner39de3112014-09-09 20:54:56 +00004290 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004291 {
Zachary Turner39de3112014-09-09 20:54:56 +00004292 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4293 if (already_running)
4294 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4295 else
4296 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004297 }
Jim Ingham372787f2012-04-07 00:00:41 +00004298 else
Todd Fiala17096d72014-07-16 19:03:16 +00004299 {
4300 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004301 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004302 else
Zachary Turner39de3112014-09-09 20:54:56 +00004303 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004304 }
4305
Jim Ingham076b3042012-04-10 01:21:57 +00004306 // Create the private state thread, and start it running.
Jim Ingham60c915e2015-06-23 21:02:45 +00004307 PrivateStateThreadArgs args = {this, is_secondary_thread};
4308 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) &args, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004309 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004310 {
4311 ResumePrivateStateThread();
4312 return true;
4313 }
4314 else
4315 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004316}
4317
4318void
4319Process::PausePrivateStateThread ()
4320{
4321 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4322}
4323
4324void
4325Process::ResumePrivateStateThread ()
4326{
4327 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4328}
4329
4330void
4331Process::StopPrivateStateThread ()
4332{
Greg Clayton8b82f082011-04-12 05:54:46 +00004333 if (PrivateStateThreadIsValid ())
4334 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004335 else
4336 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004337 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004338 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004339 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004340 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004341}
4342
4343void
4344Process::ControlPrivateStateThread (uint32_t signal)
4345{
Greg Clayton5160ce52013-03-27 23:08:40 +00004346 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004347
4348 assert (signal == eBroadcastInternalStateControlStop ||
4349 signal == eBroadcastInternalStateControlPause ||
4350 signal == eBroadcastInternalStateControlResume);
4351
4352 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004353 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004354
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004355 // Signal the private state thread. First we should copy this is case the
4356 // thread starts exiting since the private state thread will NULL this out
4357 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004358 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004359 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004360 {
4361 TimeValue timeout_time;
4362 bool timed_out;
4363
4364 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4365
4366 timeout_time = TimeValue::Now();
4367 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004368 if (log)
4369 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004370 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4371 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4372
4373 if (signal == eBroadcastInternalStateControlStop)
4374 {
4375 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004376 {
Zachary Turner39de3112014-09-09 20:54:56 +00004377 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004378 if (log)
4379 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4380 }
4381 else
4382 {
4383 if (log)
4384 log->Printf ("The control event killed the private state thread without having to cancel.");
4385 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004386
4387 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004388 private_state_thread.Join(&result);
4389 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004390 }
4391 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004392 else
4393 {
4394 if (log)
4395 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4396 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004397}
4398
4399void
Jim Inghamcfc09352012-07-27 23:57:19 +00004400Process::SendAsyncInterrupt ()
4401{
4402 if (PrivateStateThreadIsValid())
4403 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4404 else
4405 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4406}
4407
4408void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004409Process::HandlePrivateEvent (EventSP &event_sp)
4410{
Greg Clayton5160ce52013-03-27 23:08:40 +00004411 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004412 m_resume_requested = false;
4413
Jim Inghamaacc3182012-06-06 00:29:30 +00004414 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004415
Greg Clayton414f5d32011-01-25 02:58:48 +00004416 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004417
4418 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004419 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004420 {
Jim Ingham754ab982011-01-29 04:05:41 +00004421 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004422 if (log)
4423 log->Printf ("Ran next event action, result was %d.", action_result);
4424
Jim Inghambb3a2832011-01-29 01:49:25 +00004425 switch (action_result)
4426 {
4427 case NextEventAction::eEventActionSuccess:
4428 SetNextEventAction(NULL);
4429 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004430
Jim Inghambb3a2832011-01-29 01:49:25 +00004431 case NextEventAction::eEventActionRetry:
4432 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004433
Jim Inghambb3a2832011-01-29 01:49:25 +00004434 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004435 // Handle Exiting Here. If we already got an exited event,
4436 // we should just propagate it. Otherwise, swallow this event,
4437 // and set our state to exit so the next event will kill us.
4438 if (new_state != eStateExited)
4439 {
4440 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004441 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004442 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004443 SetNextEventAction(NULL);
4444 return;
4445 }
4446 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004447 break;
4448 }
4449 }
4450
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004451 // See if we should broadcast this state to external clients?
4452 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004453
4454 if (should_broadcast)
4455 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004456 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004457 if (log)
4458 {
Daniel Malead01b2952012-11-29 21:49:15 +00004459 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004460 __FUNCTION__,
4461 GetID(),
4462 StateAsCString(new_state),
4463 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004464 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004465 }
Jim Ingham9575d842011-03-11 03:53:59 +00004466 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004467 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004468 {
4469 // Only push the input handler if we aren't fowarding events,
4470 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004471 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004472 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4473 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004474 {
Greg Clayton44d93782014-01-27 23:43:24 +00004475 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004476 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4477 if (log)
4478 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4479 }
Greg Clayton44d93782014-01-27 23:43:24 +00004480 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004481 else if (StateIsStoppedState(new_state, false))
4482 {
4483 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4484 {
4485 // If the lldb_private::Debugger is handling the events, we don't
4486 // want to pop the process IOHandler here, we want to do it when
4487 // we receive the stopped event so we can carefully control when
4488 // the process IOHandler is popped because when we stop we want to
4489 // display some text stating how and why we stopped, then maybe some
4490 // process/thread/frame info, and then we want the "(lldb) " prompt
4491 // to show up. If we pop the process IOHandler here, then we will
4492 // cause the command interpreter to become the top IOHandler after
4493 // the process pops off and it will update its prompt right away...
4494 // See the Debugger.cpp file where it calls the function as
4495 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4496 // Otherwise we end up getting overlapping "(lldb) " prompts and
4497 // garbled output.
4498 //
4499 // If we aren't handling the events in the debugger (which is indicated
4500 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4501 // are hijacked, then we always pop the process IO handler manually.
4502 // Hijacking happens when the internal process state thread is running
4503 // thread plans, or when commands want to run in synchronous mode
4504 // and they call "process->WaitForProcessToStop()". An example of something
4505 // that will hijack the events is a simple expression:
4506 //
4507 // (lldb) expr (int)puts("hello")
4508 //
4509 // This will cause the internal process state thread to resume and halt
4510 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4511 // events) and we do need the IO handler to be pushed and popped
4512 // correctly.
4513
4514 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4515 PopProcessIOHandler ();
4516 }
4517 }
Jim Ingham9575d842011-03-11 03:53:59 +00004518
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004519 BroadcastEvent (event_sp);
4520 }
4521 else
4522 {
4523 if (log)
4524 {
Daniel Malead01b2952012-11-29 21:49:15 +00004525 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004526 __FUNCTION__,
4527 GetID(),
4528 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004529 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004530 }
4531 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004532 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004533}
4534
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004535thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004536Process::PrivateStateThread (void *arg)
4537{
Jim Ingham60c915e2015-06-23 21:02:45 +00004538 PrivateStateThreadArgs *real_args = static_cast<PrivateStateThreadArgs *> (arg);
4539 thread_result_t result = real_args->process->RunPrivateStateThread(real_args->is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004540 return result;
4541}
4542
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004543thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004544Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004545{
Jim Ingham076b3042012-04-10 01:21:57 +00004546 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004547 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004548
Greg Clayton5160ce52013-03-27 23:08:40 +00004549 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004550 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004551 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4552 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004553
4554 bool exit_now = false;
4555 while (!exit_now)
4556 {
4557 EventSP event_sp;
4558 WaitForEventsPrivate (NULL, event_sp, control_only);
4559 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4560 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004561 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004562 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4563 __FUNCTION__, static_cast<void*>(this), GetID(),
4564 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004565
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004566 switch (event_sp->GetType())
4567 {
4568 case eBroadcastInternalStateControlStop:
4569 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004570 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004571
4572 case eBroadcastInternalStateControlPause:
4573 control_only = true;
4574 break;
4575
4576 case eBroadcastInternalStateControlResume:
4577 control_only = false;
4578 break;
4579 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004580
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004581 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004582 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004583 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004584 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4585 {
4586 if (m_public_state.GetValue() == eStateAttaching)
4587 {
4588 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004589 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4590 __FUNCTION__, static_cast<void*>(this),
4591 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004592 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4593 }
4594 else
4595 {
4596 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004597 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4598 __FUNCTION__, static_cast<void*>(this),
4599 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004600 Halt();
4601 }
4602 continue;
4603 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004604
4605 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4606
4607 if (internal_state != eStateInvalid)
4608 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004609 if (m_clear_thread_plans_on_stop &&
4610 StateIsStoppedState(internal_state, true))
4611 {
4612 m_clear_thread_plans_on_stop = false;
4613 m_thread_list.DiscardThreadPlans();
4614 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004615 HandlePrivateEvent (event_sp);
4616 }
4617
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004618 if (internal_state == eStateInvalid ||
4619 internal_state == eStateExited ||
4620 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004621 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004622 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004623 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4624 __FUNCTION__, static_cast<void*>(this), GetID(),
4625 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004626
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004627 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004628 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004629 }
4630
Caroline Tice20ad3c42010-10-29 21:48:37 +00004631 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004632 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004633 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4634 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004635
Jim Ingham60c915e2015-06-23 21:02:45 +00004636 // If we are a secondary thread, then the primary thread we are working for will have already
4637 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4638 // try to change it on the way out.
4639 if (!is_secondary_thread)
4640 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004641 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004642 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004643 return NULL;
4644}
4645
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004646//------------------------------------------------------------------
4647// Process Event Data
4648//------------------------------------------------------------------
4649
4650Process::ProcessEventData::ProcessEventData () :
4651 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004652 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004653 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004654 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004655 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004656 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004657{
4658}
4659
4660Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4661 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004662 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004663 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004664 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004665 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004666 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004667{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004668 if (process_sp)
4669 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004670}
4671
4672Process::ProcessEventData::~ProcessEventData()
4673{
4674}
4675
4676const ConstString &
4677Process::ProcessEventData::GetFlavorString ()
4678{
4679 static ConstString g_flavor ("Process::ProcessEventData");
4680 return g_flavor;
4681}
4682
4683const ConstString &
4684Process::ProcessEventData::GetFlavor () const
4685{
4686 return ProcessEventData::GetFlavorString ();
4687}
4688
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004689void
4690Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4691{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004692 ProcessSP process_sp(m_process_wp.lock());
4693
4694 if (!process_sp)
4695 return;
4696
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004697 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004698 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4699 // the public event queue, then other times when we're pretending that this is where we stopped at the
4700 // end of expression evaluation. m_update_state is used to distinguish these
4701 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004702 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004703 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004704 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004705
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004706 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004707
4708 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4709 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4710 // end up restarting the process.
4711 if (m_interrupted)
4712 return;
4713
4714 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004715 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004716 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004717 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004718 uint32_t num_threads = curr_thread_list.GetSize();
4719 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004720
Jim Ingham4b536182011-08-09 02:12:22 +00004721 // The actions might change one of the thread's stop_info's opinions about whether we should
4722 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004723
4724 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4725 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4726 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4727 // 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
4728 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004729 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004730 for (idx = 0; idx < num_threads; ++idx)
4731 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4732
Jim Inghamc7078c22012-12-13 22:24:15 +00004733 // Use this to track whether we should continue from here. We will only continue the target running if
4734 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4735 // then it doesn't matter what the other threads say...
4736
4737 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004738
Jim Ingham0ad7e052013-04-25 02:04:59 +00004739 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4740 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4741 // thing to do is, and it's better to let the user decide than continue behind their backs.
4742
4743 bool does_anybody_have_an_opinion = false;
4744
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004745 for (idx = 0; idx < num_threads; ++idx)
4746 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004747 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004748 if (curr_thread_list.GetSize() != num_threads)
4749 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004750 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004751 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004752 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 +00004753 break;
4754 }
4755
4756 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4757
4758 if (thread_sp->GetIndexID() != thread_index_array[idx])
4759 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004760 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004761 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004762 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004763 idx,
4764 thread_index_array[idx],
4765 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004766 break;
4767 }
4768
Jim Inghamb15bfc72010-10-20 00:39:53 +00004769 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004770 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004771 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004772 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004773 bool this_thread_wants_to_stop;
4774 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004775 {
Jim Ingham0161b492013-02-09 01:29:05 +00004776 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4777 }
4778 else
4779 {
4780 stop_info_sp->PerformAction(event_ptr);
4781 // The stop action might restart the target. If it does, then we want to mark that in the
4782 // event so that whoever is receiving it will know to wait for the running event and reflect
4783 // that state appropriately.
4784 // We also need to stop processing actions, since they aren't expecting the target to be running.
4785
4786 // FIXME: we might have run.
4787 if (stop_info_sp->HasTargetRunSinceMe())
4788 {
4789 SetRestarted (true);
4790 break;
4791 }
4792
4793 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004794 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004795
Jim Inghamc7078c22012-12-13 22:24:15 +00004796 if (still_should_stop == false)
4797 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004798 }
4799 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004800
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004801
Jim Inghama8ca6e22013-05-03 23:04:37 +00004802 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004803 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004804 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004805 {
4806 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004807 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004808 // Use the public resume method here, since this is just
4809 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004810 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004811 }
4812 else
4813 {
4814 // If we didn't restart, run the Stop Hooks here:
4815 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004816 process_sp->GetTarget().RunStopHooks();
4817 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004818 SetRestarted(true);
4819 }
Jim Ingham9575d842011-03-11 03:53:59 +00004820 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004821 }
4822}
4823
4824void
4825Process::ProcessEventData::Dump (Stream *s) const
4826{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004827 ProcessSP process_sp(m_process_wp.lock());
4828
4829 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004830 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004831 static_cast<void*>(process_sp.get()), process_sp->GetID());
4832 else
4833 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004834
Greg Clayton8b82f082011-04-12 05:54:46 +00004835 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004836}
4837
4838const Process::ProcessEventData *
4839Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4840{
4841 if (event_ptr)
4842 {
4843 const EventData *event_data = event_ptr->GetData();
4844 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4845 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4846 }
4847 return NULL;
4848}
4849
4850ProcessSP
4851Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4852{
4853 ProcessSP process_sp;
4854 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4855 if (data)
4856 process_sp = data->GetProcessSP();
4857 return process_sp;
4858}
4859
4860StateType
4861Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4862{
4863 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4864 if (data == NULL)
4865 return eStateInvalid;
4866 else
4867 return data->GetState();
4868}
4869
4870bool
4871Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4872{
4873 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4874 if (data == NULL)
4875 return false;
4876 else
4877 return data->GetRestarted();
4878}
4879
4880void
4881Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4882{
4883 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4884 if (data != NULL)
4885 data->SetRestarted(new_value);
4886}
4887
Jim Ingham0161b492013-02-09 01:29:05 +00004888size_t
4889Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4890{
4891 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4892 if (data != NULL)
4893 return data->GetNumRestartedReasons();
4894 else
4895 return 0;
4896}
4897
4898const char *
4899Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4900{
4901 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4902 if (data != NULL)
4903 return data->GetRestartedReasonAtIndex(idx);
4904 else
4905 return NULL;
4906}
4907
4908void
4909Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4910{
4911 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4912 if (data != NULL)
4913 data->AddRestartedReason(reason);
4914}
4915
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004916bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004917Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4918{
4919 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4920 if (data == NULL)
4921 return false;
4922 else
4923 return data->GetInterrupted ();
4924}
4925
4926void
4927Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4928{
4929 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4930 if (data != NULL)
4931 data->SetInterrupted(new_value);
4932}
4933
4934bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004935Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4936{
4937 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4938 if (data)
4939 {
4940 data->SetUpdateStateOnRemoval();
4941 return true;
4942 }
4943 return false;
4944}
4945
Greg Claytond9e416c2012-02-18 05:35:26 +00004946lldb::TargetSP
4947Process::CalculateTarget ()
4948{
4949 return m_target.shared_from_this();
4950}
4951
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004952void
Greg Clayton0603aa92010-10-04 01:05:56 +00004953Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004954{
Greg Claytonc14ee322011-09-22 04:58:26 +00004955 exe_ctx.SetTargetPtr (&m_target);
4956 exe_ctx.SetProcessPtr (this);
4957 exe_ctx.SetThreadPtr(NULL);
4958 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004959}
4960
Greg Claytone996fd32011-03-08 22:40:15 +00004961//uint32_t
4962//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4963//{
4964// return 0;
4965//}
4966//
4967//ArchSpec
4968//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4969//{
4970// return Host::GetArchSpecForExistingProcess (pid);
4971//}
4972//
4973//ArchSpec
4974//Process::GetArchSpecForExistingProcess (const char *process_name)
4975//{
4976// return Host::GetArchSpecForExistingProcess (process_name);
4977//}
4978//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004979void
4980Process::AppendSTDOUT (const char * s, size_t len)
4981{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004982 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004983 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004984 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004985}
4986
4987void
Greg Clayton93e86192011-11-13 04:45:22 +00004988Process::AppendSTDERR (const char * s, size_t len)
4989{
4990 Mutex::Locker locker (m_stdio_communication_mutex);
4991 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004992 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004993}
4994
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004995void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004996Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004997{
4998 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004999 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005000 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
5001}
5002
5003size_t
5004Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
5005{
5006 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005007 if (m_profile_data.empty())
5008 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005009
5010 std::string &one_profile_data = m_profile_data.front();
5011 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005012 if (bytes_available > 0)
5013 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005014 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005015 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005016 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5017 static_cast<void*>(buf),
5018 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005019 if (bytes_available > buf_size)
5020 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005021 memcpy(buf, one_profile_data.c_str(), buf_size);
5022 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005023 bytes_available = buf_size;
5024 }
5025 else
5026 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005027 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005028 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005029 }
5030 }
5031 return bytes_available;
5032}
5033
5034
Greg Clayton93e86192011-11-13 04:45:22 +00005035//------------------------------------------------------------------
5036// Process STDIO
5037//------------------------------------------------------------------
5038
5039size_t
5040Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5041{
5042 Mutex::Locker locker(m_stdio_communication_mutex);
5043 size_t bytes_available = m_stdout_data.size();
5044 if (bytes_available > 0)
5045 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005046 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005047 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005048 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5049 static_cast<void*>(buf),
5050 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005051 if (bytes_available > buf_size)
5052 {
5053 memcpy(buf, m_stdout_data.c_str(), buf_size);
5054 m_stdout_data.erase(0, buf_size);
5055 bytes_available = buf_size;
5056 }
5057 else
5058 {
5059 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5060 m_stdout_data.clear();
5061 }
5062 }
5063 return bytes_available;
5064}
5065
5066
5067size_t
5068Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5069{
5070 Mutex::Locker locker(m_stdio_communication_mutex);
5071 size_t bytes_available = m_stderr_data.size();
5072 if (bytes_available > 0)
5073 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005074 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005075 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005076 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5077 static_cast<void*>(buf),
5078 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005079 if (bytes_available > buf_size)
5080 {
5081 memcpy(buf, m_stderr_data.c_str(), buf_size);
5082 m_stderr_data.erase(0, buf_size);
5083 bytes_available = buf_size;
5084 }
5085 else
5086 {
5087 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5088 m_stderr_data.clear();
5089 }
5090 }
5091 return bytes_available;
5092}
5093
5094void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005095Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5096{
5097 Process *process = (Process *) baton;
5098 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5099}
5100
Greg Clayton44d93782014-01-27 23:43:24 +00005101class IOHandlerProcessSTDIO :
5102 public IOHandler
5103{
5104public:
5105 IOHandlerProcessSTDIO (Process *process,
5106 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005107 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005108 m_process (process),
5109 m_read_file (),
5110 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005111 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005112 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005113 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00005114 m_read_file.SetDescriptor(GetInputFD(), false);
5115 }
5116
5117 virtual
5118 ~IOHandlerProcessSTDIO ()
5119 {
5120
5121 }
5122
Greg Clayton44d93782014-01-27 23:43:24 +00005123 // Each IOHandler gets to run until it is done. It should read data
5124 // from the "in" and place output into "out" and "err and return
5125 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00005126 void
5127 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00005128 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005129 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005130 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005131 SetIsDone(true);
5132 return;
5133 }
5134
5135 SetIsDone(false);
5136 const int read_fd = m_read_file.GetDescriptor();
5137 TerminalState terminal_state;
5138 terminal_state.Save (read_fd, false);
5139 Terminal terminal(read_fd);
5140 terminal.SetCanonical(false);
5141 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005142// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005143#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005144 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5145 while (!GetIsDone())
5146 {
5147 fd_set read_fdset;
5148 FD_ZERO (&read_fdset);
5149 FD_SET (read_fd, &read_fdset);
5150 FD_SET (pipe_read_fd, &read_fdset);
5151 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5152 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5153 if (num_set_fds < 0)
5154 {
5155 const int select_errno = errno;
5156
5157 if (select_errno != EINTR)
5158 SetIsDone(true);
5159 }
5160 else if (num_set_fds > 0)
5161 {
5162 char ch = 0;
5163 size_t n;
5164 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00005165 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005166 n = 1;
5167 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005168 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005169 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005170 SetIsDone(true);
5171 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005172 else
5173 SetIsDone(true);
5174 }
5175 if (FD_ISSET (pipe_read_fd, &read_fdset))
5176 {
5177 size_t bytes_read;
5178 // Consume the interrupt byte
5179 Error error = m_pipe.Read(&ch, 1, bytes_read);
5180 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00005181 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005182 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00005183 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005184 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00005185 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005186 break;
5187 case 'i':
5188 if (StateIsRunningState(m_process->GetState()))
5189 m_process->Halt();
5190 break;
Greg Clayton44d93782014-01-27 23:43:24 +00005191 }
5192 }
5193 }
Greg Clayton44d93782014-01-27 23:43:24 +00005194 }
Greg Clayton44d93782014-01-27 23:43:24 +00005195 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005196#endif
5197 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005198 }
5199
Pavel Labath44464872015-05-27 12:40:32 +00005200 void
5201 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005202 {
Greg Clayton19e11352014-02-26 22:47:33 +00005203 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005204 size_t bytes_written = 0;
5205 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005206 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005207
Pavel Labath44464872015-05-27 12:40:32 +00005208 bool
5209 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005210 {
Greg Clayton19e11352014-02-26 22:47:33 +00005211 // Do only things that are safe to do in an interrupt context (like in
5212 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5213 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5214 // that was written to the pipe and then call m_process->Halt() from a
5215 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005216 if (m_active)
5217 {
5218 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005219 size_t bytes_written = 0;
5220 Error result = m_pipe.Write(&ch, 1, bytes_written);
5221 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005222 }
5223 else
5224 {
5225 // This IOHandler might be pushed on the stack, but not being run currently
5226 // so do the right thing if we aren't actively watching for STDIN by sending
5227 // the interrupt to the process. Otherwise the write to the pipe above would
5228 // do nothing. This can happen when the command interpreter is running and
5229 // gets a "expression ...". It will be on the IOHandler thread and sending
5230 // the input is complete to the delegate which will cause the expression to
5231 // run, which will push the process IO handler, but not run it.
5232
5233 if (StateIsRunningState(m_process->GetState()))
5234 {
5235 m_process->SendAsyncInterrupt();
5236 return true;
5237 }
5238 }
5239 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005240 }
Greg Clayton44d93782014-01-27 23:43:24 +00005241
Pavel Labath44464872015-05-27 12:40:32 +00005242 void
5243 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005244 {
5245
5246 }
5247
5248protected:
5249 Process *m_process;
5250 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5251 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005252 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005253};
5254
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005255void
Greg Clayton44d93782014-01-27 23:43:24 +00005256Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005257{
5258 // First set up the Read Thread for reading/handling process I/O
5259
Greg Clayton44d93782014-01-27 23:43:24 +00005260 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005261
5262 if (conn_ap.get())
5263 {
5264 m_stdio_communication.SetConnection (conn_ap.release());
5265 if (m_stdio_communication.IsConnected())
5266 {
5267 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5268 m_stdio_communication.StartReadThread();
5269
5270 // Now read thread is set up, set up input reader.
5271
5272 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005273 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005274 }
5275 }
5276}
5277
Greg Claytonb4874f12014-02-28 18:22:24 +00005278bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005279Process::ProcessIOHandlerIsActive ()
5280{
5281 IOHandlerSP io_handler_sp (m_process_input_reader);
5282 if (io_handler_sp)
5283 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5284 return false;
5285}
5286bool
Greg Clayton44d93782014-01-27 23:43:24 +00005287Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005288{
Greg Clayton44d93782014-01-27 23:43:24 +00005289 IOHandlerSP io_handler_sp (m_process_input_reader);
5290 if (io_handler_sp)
5291 {
Pavel Labath44464872015-05-27 12:40:32 +00005292 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5293 if (log)
5294 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5295
Greg Clayton44d93782014-01-27 23:43:24 +00005296 io_handler_sp->SetIsDone(false);
5297 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005298 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005299 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005300 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005301}
5302
Greg Claytonb4874f12014-02-28 18:22:24 +00005303bool
Greg Clayton44d93782014-01-27 23:43:24 +00005304Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005305{
Greg Clayton44d93782014-01-27 23:43:24 +00005306 IOHandlerSP io_handler_sp (m_process_input_reader);
5307 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005308 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5309 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005310}
5311
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005312// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005313void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005314Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005315{
Greg Clayton6920b522012-08-22 18:39:03 +00005316 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005317}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005318
Greg Clayton99d0faf2010-11-18 23:32:35 +00005319void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005320Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005321{
Greg Clayton6920b522012-08-22 18:39:03 +00005322 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005323}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005324
Jim Ingham1624a2d2014-05-05 02:26:40 +00005325ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005326Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005327 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005328 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005329 Stream &errors)
5330{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005331 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005332
Jim Ingham77787032011-01-20 02:03:18 +00005333 if (thread_plan_sp.get() == NULL)
5334 {
5335 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005336 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005337 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005338
Jim Ingham7d7931d2013-03-28 00:05:34 +00005339 if (!thread_plan_sp->ValidatePlan(NULL))
5340 {
5341 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005342 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005343 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005344
Greg Claytonc14ee322011-09-22 04:58:26 +00005345 if (exe_ctx.GetProcessPtr() != this)
5346 {
5347 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005348 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005349 }
5350
5351 Thread *thread = exe_ctx.GetThreadPtr();
5352 if (thread == NULL)
5353 {
5354 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005355 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005356 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005357
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005358 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5359 // For that to be true the plan can't be private - since private plans suppress themselves in the
5360 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005361
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005362 bool orig_plan_private = thread_plan_sp->GetPrivate();
5363 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005364
Jim Ingham444586b2011-01-24 06:34:17 +00005365 if (m_private_state.GetValue() != eStateStopped)
5366 {
5367 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005368 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005369 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005370
Jim Ingham66243842011-08-13 00:56:10 +00005371 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005372 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005373 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005374 if (!selected_frame_sp)
5375 {
5376 thread->SetSelectedFrame(0);
5377 selected_frame_sp = thread->GetSelectedFrame();
5378 if (!selected_frame_sp)
5379 {
5380 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005381 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005382 }
5383 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005384
Jim Ingham11b0e052013-02-19 23:22:45 +00005385 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005386
5387 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5388 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005389
Greg Claytonc14ee322011-09-22 04:58:26 +00005390 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005391
Jim Ingham66243842011-08-13 00:56:10 +00005392 uint32_t selected_tid;
5393 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005394 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005395 {
5396 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005397 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005398 }
5399 else
5400 {
5401 selected_tid = LLDB_INVALID_THREAD_ID;
5402 }
5403
Zachary Turner39de3112014-09-09 20:54:56 +00005404 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005405 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005406 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005407
Greg Clayton5160ce52013-03-27 23:08:40 +00005408 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005409 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005410 {
Jim Ingham076b3042012-04-10 01:21:57 +00005411 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5412 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005413 // 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 +00005414 // we are fielding public events here.
5415 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005416 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 +00005417
Jim Ingham372787f2012-04-07 00:00:41 +00005418 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005419
5420 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5421 // returning control here.
5422 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5423 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5424 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5425 // do just what we want.
5426 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5427 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5428 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5429 old_state = m_public_state.GetValue();
5430 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005431
Jim Ingham076b3042012-04-10 01:21:57 +00005432 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005433 StartPrivateStateThread(true);
5434 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005435
Jim Ingham372787f2012-04-07 00:00:41 +00005436 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005437
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005438 if (options.GetDebug())
5439 {
5440 // In this case, we aren't actually going to run, we just want to stop right away.
5441 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5442 // FIXME: To make this prettier we should invent some stop reason for this, but that
5443 // is only cosmetic, and this functionality is only of use to lldb developers who can
5444 // live with not pretty...
5445 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005446 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005447 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005448
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005449 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005450
Sean Callanana46ec452012-07-11 21:31:24 +00005451 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005452
Jim Ingham77787032011-01-20 02:03:18 +00005453 {
Sean Callanana46ec452012-07-11 21:31:24 +00005454 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5455 // restored on exit to the function.
5456 //
5457 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5458 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005459
Sean Callanana46ec452012-07-11 21:31:24 +00005460 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005461
Jim Inghamf48169b2010-11-30 02:22:11 +00005462 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005463 {
5464 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005465 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005466 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005467 thread->GetIndexID(),
5468 thread->GetID(),
5469 s.GetData());
5470 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005471
Sean Callanana46ec452012-07-11 21:31:24 +00005472 bool got_event;
5473 lldb::EventSP event_sp;
5474 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005475
Sean Callanana46ec452012-07-11 21:31:24 +00005476 TimeValue* timeout_ptr = NULL;
5477 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005478
Jim Ingham0161b492013-02-09 01:29:05 +00005479 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 +00005480 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005481 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005482 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005483
Jim Ingham0161b492013-02-09 01:29:05 +00005484 // This is just for accounting:
5485 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005486
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005487 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005488 uint32_t one_thread_timeout_usec;
5489 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005490
5491 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5492 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5493 // first timeout already.
5494
5495 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005496 {
5497 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005498 one_thread_timeout_usec = 0;
5499 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005500 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005501 else
Jim Ingham0161b492013-02-09 01:29:05 +00005502 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005503 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005504
Jim Ingham914f4e72014-03-28 21:58:28 +00005505 // If the overall wait is forever, then we only need to set the one thread timeout:
5506 if (timeout_usec == 0)
5507 {
Ed Maste801335c2014-03-31 19:28:14 +00005508 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005509 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005510 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005511 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005512 }
Jim Ingham0161b492013-02-09 01:29:05 +00005513 else
5514 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005515 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5516 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5517 uint64_t computed_one_thread_timeout;
5518 if (option_one_thread_timeout != 0)
5519 {
5520 if (timeout_usec < option_one_thread_timeout)
5521 {
5522 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005523 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005524 }
5525 computed_one_thread_timeout = option_one_thread_timeout;
5526 }
5527 else
5528 {
5529 computed_one_thread_timeout = timeout_usec / 2;
5530 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5531 computed_one_thread_timeout = default_one_thread_timeout_usec;
5532 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005533 one_thread_timeout_usec = computed_one_thread_timeout;
5534 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5535
Jim Ingham0161b492013-02-09 01:29:05 +00005536 }
Jim Ingham0161b492013-02-09 01:29:05 +00005537 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005538
5539 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005540 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 +00005541 options.GetStopOthers(),
5542 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005543 before_first_timeout,
5544 one_thread_timeout_usec,
5545 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005546
Jim Ingham1460e4b2014-01-10 23:46:59 +00005547 // This isn't going to work if there are unfetched events on the queue.
5548 // Are there cases where we might want to run the remaining events here, and then try to
5549 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005550
Jim Ingham1460e4b2014-01-10 23:46:59 +00005551 Event *other_events = listener.PeekAtNextEvent();
5552 if (other_events != NULL)
5553 {
5554 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005555 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005556 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005557
Jim Ingham1460e4b2014-01-10 23:46:59 +00005558 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5559 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5560 // event coalescing to cause us to lose OUR running event...
5561 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005562
Jim Ingham8559a352012-11-26 23:52:18 +00005563 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5564 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005565
5566#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5567 // It's pretty much impossible to write test cases for things like:
5568 // One thread timeout expires, I go to halt, but the process already stopped
5569 // on the function call stop breakpoint. Turning on this define will make us not
5570 // fetch the first event till after the halt. So if you run a quick function, it will have
5571 // completed, and the completion event will be waiting, when you interrupt for halt.
5572 // The expression evaluation should still succeed.
5573 bool miss_first_event = true;
5574#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005575 TimeValue one_thread_timeout;
5576 TimeValue final_timeout;
5577
Jim Ingham35878c42014-04-08 21:33:21 +00005578
Sean Callanana46ec452012-07-11 21:31:24 +00005579 while (1)
5580 {
5581 // We usually want to resume the process if we get to the top of the loop.
5582 // The only exception is if we get two running events with no intervening
5583 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005584 if (log)
5585 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5586 do_resume,
5587 handle_running_event,
5588 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005589
Jim Ingham184e9812013-01-15 02:47:48 +00005590 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005591 {
5592 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005593
Jim Ingham184e9812013-01-15 02:47:48 +00005594 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005595 {
Jim Ingham0161b492013-02-09 01:29:05 +00005596 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005597 Error resume_error = PrivateResume ();
5598 if (!resume_error.Success())
5599 {
Jim Ingham0161b492013-02-09 01:29:05 +00005600 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5601 num_resumes,
5602 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005603 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005604 break;
5605 }
Sean Callanana46ec452012-07-11 21:31:24 +00005606 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005607
Jim Ingham0161b492013-02-09 01:29:05 +00005608 TimeValue resume_timeout = TimeValue::Now();
5609 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005610
Jim Ingham0161b492013-02-09 01:29:05 +00005611 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005612 if (!got_event)
5613 {
5614 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005615 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5616 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005617
Jim Ingham0161b492013-02-09 01:29:05 +00005618 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005619 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005620 break;
5621 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005622
Sean Callanana46ec452012-07-11 21:31:24 +00005623 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005624
Sean Callanana46ec452012-07-11 21:31:24 +00005625 if (stop_state != eStateRunning)
5626 {
Jim Ingham0161b492013-02-09 01:29:05 +00005627 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005628
Jim Ingham0161b492013-02-09 01:29:05 +00005629 if (stop_state == eStateStopped)
5630 {
5631 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5632 if (log)
5633 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5634 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5635 num_resumes,
5636 StateAsCString(stop_state),
5637 restarted,
5638 do_resume,
5639 handle_running_event);
5640 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005641
Jim Ingham0161b492013-02-09 01:29:05 +00005642 if (restarted)
5643 {
5644 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5645 // event here. But if I do, the best thing is to Halt and then get out of here.
5646 Halt();
5647 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005648
Jim Ingham35e1bda2012-10-16 21:41:58 +00005649 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5650 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005651 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005652 break;
5653 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005654
Sean Callanana46ec452012-07-11 21:31:24 +00005655 if (log)
5656 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5657 // We need to call the function synchronously, so spin waiting for it to return.
5658 // If we get interrupted while executing, we're going to lose our context, and
5659 // won't be able to gather the result at this point.
5660 // We set the timeout AFTER the resume, since the resume takes some time and we
5661 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005662 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005663 else
5664 {
Sean Callanana46ec452012-07-11 21:31:24 +00005665 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005666 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005667 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005668
Jim Ingham0161b492013-02-09 01:29:05 +00005669 if (before_first_timeout)
5670 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005671 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005672 {
5673 one_thread_timeout = TimeValue::Now();
5674 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005675 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005676 }
Jim Ingham0161b492013-02-09 01:29:05 +00005677 else
5678 {
5679 if (timeout_usec == 0)
5680 timeout_ptr = NULL;
5681 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005682 {
5683 final_timeout = TimeValue::Now();
5684 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005685 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005686 }
Jim Ingham0161b492013-02-09 01:29:05 +00005687 }
5688 }
5689 else
5690 {
5691 if (timeout_usec == 0)
5692 timeout_ptr = NULL;
5693 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005694 {
5695 final_timeout = TimeValue::Now();
5696 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005697 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005698 }
Jim Ingham0161b492013-02-09 01:29:05 +00005699 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005700
Jim Ingham0161b492013-02-09 01:29:05 +00005701 do_resume = true;
5702 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005703
Sean Callanana46ec452012-07-11 21:31:24 +00005704 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005705 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005706
Jim Ingham0f16e732011-02-08 05:20:59 +00005707 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005708 {
Sean Callanana46ec452012-07-11 21:31:24 +00005709 if (timeout_ptr)
5710 {
Matt Kopec676a4872013-02-21 23:55:31 +00005711 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005712 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5713 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005714 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005715 else
Sean Callanana46ec452012-07-11 21:31:24 +00005716 {
5717 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5718 }
5719 }
Jim Ingham35878c42014-04-08 21:33:21 +00005720
5721#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5722 // See comment above...
5723 if (miss_first_event)
5724 {
5725 usleep(1000);
5726 miss_first_event = false;
5727 got_event = false;
5728 }
5729 else
5730#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005731 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005732
Sean Callanana46ec452012-07-11 21:31:24 +00005733 if (got_event)
5734 {
5735 if (event_sp.get())
5736 {
5737 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005738 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005739 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005740 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005741 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005742 errors.Printf ("Execution halted by user interrupt.");
5743 if (log)
5744 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005745 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005746 }
5747 else
5748 {
5749 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5750 if (log)
5751 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005752
Jim Inghamcfc09352012-07-27 23:57:19 +00005753 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005754 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005755 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005756 {
Jim Ingham0161b492013-02-09 01:29:05 +00005757 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005758 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5759 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005760 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005761 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005762 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005763 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005764 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005765 }
5766 else
5767 {
Jim Ingham0161b492013-02-09 01:29:05 +00005768 // If we were restarted, we just need to go back up to fetch another event.
5769 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005770 {
5771 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005772 {
5773 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5774 }
5775 keep_going = true;
5776 do_resume = false;
5777 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005778
Jim Inghamcfc09352012-07-27 23:57:19 +00005779 }
5780 else
5781 {
Jim Ingham0161b492013-02-09 01:29:05 +00005782 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5783 StopReason stop_reason = eStopReasonInvalid;
5784 if (stop_info_sp)
5785 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005786
Jim Ingham0161b492013-02-09 01:29:05 +00005787 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5788 // it is OUR plan that is complete?
5789 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005790 {
5791 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005792 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5793 // Now mark this plan as private so it doesn't get reported as the stop reason
5794 // after this point.
5795 if (thread_plan_sp)
5796 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005797 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005798 }
5799 else
5800 {
Jim Ingham0161b492013-02-09 01:29:05 +00005801 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005802 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005803 {
5804 if (log)
5805 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005806 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005807 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005808 {
5809 event_to_broadcast_sp = event_sp;
5810 }
Jim Ingham0161b492013-02-09 01:29:05 +00005811 }
Jim Ingham184e9812013-01-15 02:47:48 +00005812 else
Jim Ingham0161b492013-02-09 01:29:05 +00005813 {
5814 if (log)
5815 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005816 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005817 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005818 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005819 }
Jim Ingham184e9812013-01-15 02:47:48 +00005820 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005821 }
Sean Callanana46ec452012-07-11 21:31:24 +00005822 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005823 }
5824 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005825
Jim Inghamcfc09352012-07-27 23:57:19 +00005826 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005827 // This shouldn't really happen, but sometimes we do get two running events without an
5828 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005829 do_resume = false;
5830 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005831 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005832 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005833
Jim Inghamcfc09352012-07-27 23:57:19 +00005834 default:
5835 if (log)
5836 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005837
Jim Inghamcfc09352012-07-27 23:57:19 +00005838 if (stop_state == eStateExited)
5839 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005840
Sean Callananbf154da2012-08-08 17:35:10 +00005841 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005842 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005843 break;
5844 }
Sean Callanana46ec452012-07-11 21:31:24 +00005845 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005846
Sean Callanana46ec452012-07-11 21:31:24 +00005847 if (keep_going)
5848 continue;
5849 else
5850 break;
5851 }
5852 else
5853 {
5854 if (log)
5855 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005856 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005857 break;
5858 }
5859 }
5860 else
5861 {
5862 // If we didn't get an event that means we've timed out...
5863 // We will interrupt the process here. Depending on what we were asked to do we will
5864 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005865
Sean Callanana46ec452012-07-11 21:31:24 +00005866 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005867 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005868 {
Jim Ingham0161b492013-02-09 01:29:05 +00005869 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005870 {
5871 if (timeout_usec != 0)
5872 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005873 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005874 "running for %" PRIu32 " usec with all threads enabled.",
5875 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005876 }
5877 else
5878 {
5879 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005880 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005881 }
5882 }
Sean Callanana46ec452012-07-11 21:31:24 +00005883 else
5884 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005885 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005886 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005887 }
5888 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005889 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005890 "abandoning execution.",
5891 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005892 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005893
Jim Ingham0161b492013-02-09 01:29:05 +00005894 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5895 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5896 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5897 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5898 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005899
Jim Ingham0161b492013-02-09 01:29:05 +00005900 bool back_to_top = true;
5901 uint32_t try_halt_again = 0;
5902 bool do_halt = true;
5903 const uint32_t num_retries = 5;
5904 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005905 {
Jim Ingham0161b492013-02-09 01:29:05 +00005906 Error halt_error;
5907 if (do_halt)
5908 {
5909 if (log)
5910 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5911 halt_error = Halt();
5912 }
5913 if (halt_error.Success())
5914 {
5915 if (log)
5916 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005917
Jim Ingham0161b492013-02-09 01:29:05 +00005918 real_timeout = TimeValue::Now();
5919 real_timeout.OffsetWithMicroSeconds(500000);
5920
5921 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005922
Jim Ingham0161b492013-02-09 01:29:05 +00005923 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005924 {
Jim Ingham0161b492013-02-09 01:29:05 +00005925 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5926 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005927 {
Jim Ingham0161b492013-02-09 01:29:05 +00005928 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5929 if (stop_state == lldb::eStateStopped
5930 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5931 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005932 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005933
Jim Ingham0161b492013-02-09 01:29:05 +00005934 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005935 {
Jim Ingham0161b492013-02-09 01:29:05 +00005936 // Between the time we initiated the Halt and the time we delivered it, the process could have
5937 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005938
Jim Ingham0161b492013-02-09 01:29:05 +00005939 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5940 {
5941 if (log)
5942 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5943 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005944 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005945 back_to_top = false;
5946 break;
5947 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005948
Jim Ingham0161b492013-02-09 01:29:05 +00005949 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5950 {
5951 if (log)
5952 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5953 "Exiting wait loop.");
5954 try_halt_again++;
5955 do_halt = false;
5956 continue;
5957 }
Sean Callanana46ec452012-07-11 21:31:24 +00005958
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005959 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005960 {
5961 if (log)
5962 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005963 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005964 back_to_top = false;
5965 break;
5966 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005967
Jim Ingham0161b492013-02-09 01:29:05 +00005968 if (before_first_timeout)
5969 {
5970 // Set all the other threads to run, and return to the top of the loop, which will continue;
5971 before_first_timeout = false;
5972 thread_plan_sp->SetStopOthers (false);
5973 if (log)
5974 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005975
Jim Ingham0161b492013-02-09 01:29:05 +00005976 back_to_top = true;
5977 break;
5978 }
5979 else
5980 {
5981 // Running all threads failed, so return Interrupted.
5982 if (log)
5983 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005984 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005985 back_to_top = false;
5986 break;
5987 }
Sean Callanana46ec452012-07-11 21:31:24 +00005988 }
5989 }
5990 else
Jim Ingham0161b492013-02-09 01:29:05 +00005991 { if (log)
5992 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5993 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005994 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005995 back_to_top = false;
5996 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005997 }
5998 }
Jim Ingham0161b492013-02-09 01:29:05 +00005999 else
6000 {
6001 try_halt_again++;
6002 continue;
6003 }
Sean Callanana46ec452012-07-11 21:31:24 +00006004 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006005
Jim Ingham0161b492013-02-09 01:29:05 +00006006 if (!back_to_top || try_halt_again > num_retries)
6007 break;
6008 else
6009 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006010 }
Sean Callanana46ec452012-07-11 21:31:24 +00006011 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006012
Sean Callanana46ec452012-07-11 21:31:24 +00006013 // 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 +00006014 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006015 {
6016 StopPrivateStateThread();
6017 Error error;
6018 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006019 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006020 {
6021 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6022 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006023 if (old_state != eStateInvalid)
6024 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006025 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006026
Jim Ingham184e9812013-01-15 02:47:48 +00006027 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6028 // could happen:
6029 // 1) The execution successfully completed
6030 // 2) We hit a breakpoint, and ignore_breakpoints was true
6031 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006032 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6033 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006034
Jim Ingham8646d3c2014-05-05 02:47:44 +00006035 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006036 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006037 {
6038 thread_plan_sp->RestoreThreadState();
6039 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006040
Sean Callanana46ec452012-07-11 21:31:24 +00006041 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006042 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006043 {
6044 if (log)
6045 {
6046 StreamString s;
6047 if (event_sp)
6048 event_sp->Dump (&s);
6049 else
6050 {
6051 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6052 }
6053
6054 StreamString ts;
6055
6056 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006057
Sean Callanana46ec452012-07-11 21:31:24 +00006058 do
6059 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006060 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006061 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006062 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006063 break;
6064 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006065 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006066 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006067 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006068 break;
6069 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006070 else
Sean Callanana46ec452012-07-11 21:31:24 +00006071 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006072 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6073
6074 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006075 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006076 event_explanation = "<no event data>";
6077 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006078 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006079
Jim Inghamcfc09352012-07-27 23:57:19 +00006080 Process *process = event_data->GetProcessSP().get();
6081
6082 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006083 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006084 event_explanation = "<no process>";
6085 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006086 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006087
Jim Inghamcfc09352012-07-27 23:57:19 +00006088 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006089
Jim Inghamcfc09352012-07-27 23:57:19 +00006090 uint32_t num_threads = thread_list.GetSize();
6091 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006092
Jim Inghamcfc09352012-07-27 23:57:19 +00006093 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006094
Jim Inghamcfc09352012-07-27 23:57:19 +00006095 for (thread_index = 0;
6096 thread_index < num_threads;
6097 ++thread_index)
6098 {
6099 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006100
Jim Inghamcfc09352012-07-27 23:57:19 +00006101 if (!thread)
6102 {
6103 ts.Printf("<?> ");
6104 continue;
6105 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006106
Daniel Malead01b2952012-11-29 21:49:15 +00006107 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006108 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006109
Jim Inghamcfc09352012-07-27 23:57:19 +00006110 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006111 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006112 else
6113 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006114
Jim Inghamcfc09352012-07-27 23:57:19 +00006115 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6116 if (stop_info_sp)
6117 {
6118 const char *stop_desc = stop_info_sp->GetDescription();
6119 if (stop_desc)
6120 ts.PutCString (stop_desc);
6121 }
6122 ts.Printf(">");
6123 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006124
Jim Inghamcfc09352012-07-27 23:57:19 +00006125 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006126 }
Sean Callanana46ec452012-07-11 21:31:24 +00006127 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006128
Jim Inghamcfc09352012-07-27 23:57:19 +00006129 if (event_explanation)
6130 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006131 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006132 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6133 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006134
Jim Inghame4483cf2013-09-27 01:13:01 +00006135 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006136 {
6137 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006138 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6139 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006140 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6141 thread_plan_sp->SetPrivate (orig_plan_private);
6142 }
6143 else
6144 {
6145 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006146 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6147 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006148 }
6149 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006150 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006151 {
6152 if (log)
6153 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006154
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006155 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006156 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006157 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006158 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006159 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006160 }
6161 else
6162 {
Sean Callanana46ec452012-07-11 21:31:24 +00006163 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006164 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006165 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006166 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006167 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006168 }
6169 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6170 {
6171 if (log)
6172 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006173 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006174 }
6175 else
6176 {
6177 if (log)
6178 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006179 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006180 {
6181 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006182 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006183 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6184 thread_plan_sp->SetPrivate (orig_plan_private);
6185 }
6186 }
6187 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006188
Sean Callanana46ec452012-07-11 21:31:24 +00006189 // Thread we ran the function in may have gone away because we ran the target
6190 // Check that it's still there, and if it is put it back in the context. Also restore the
6191 // frame in the context if it is still present.
6192 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6193 if (thread)
6194 {
6195 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6196 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006197
Sean Callanana46ec452012-07-11 21:31:24 +00006198 // Also restore the current process'es selected frame & thread, since this function calling may
6199 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006200
Sean Callanana46ec452012-07-11 21:31:24 +00006201 if (selected_tid != LLDB_INVALID_THREAD_ID)
6202 {
6203 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6204 {
6205 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006206 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006207 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006208 if (old_frame_sp)
6209 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006210 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006211 }
6212 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006213
Sean Callanana46ec452012-07-11 21:31:24 +00006214 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006215
Sean Callanana46ec452012-07-11 21:31:24 +00006216 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006217 {
Sean Callanana46ec452012-07-11 21:31:24 +00006218 if (log)
6219 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6220 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006221 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006222
Jim Inghamf48169b2010-11-30 02:22:11 +00006223 return return_value;
6224}
6225
6226const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006227Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006228{
6229 const char *result_name;
6230
6231 switch (result)
6232 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006233 case eExpressionCompleted:
6234 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006235 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006236 case eExpressionDiscarded:
6237 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006238 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006239 case eExpressionInterrupted:
6240 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006241 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006242 case eExpressionHitBreakpoint:
6243 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006244 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006245 case eExpressionSetupError:
6246 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006247 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006248 case eExpressionParseError:
6249 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006250 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006251 case eExpressionResultUnavailable:
6252 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006253 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006254 case eExpressionTimedOut:
6255 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006256 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006257 case eExpressionStoppedForDebug:
6258 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006259 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006260 }
6261 return result_name;
6262}
6263
Greg Clayton7260f622011-04-18 08:33:37 +00006264void
6265Process::GetStatus (Stream &strm)
6266{
6267 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006268 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006269 {
6270 if (state == eStateExited)
6271 {
6272 int exit_status = GetExitStatus();
6273 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006274 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006275 GetID(),
6276 exit_status,
6277 exit_status,
6278 exit_description ? exit_description : "");
6279 }
6280 else
6281 {
6282 if (state == eStateConnected)
6283 strm.Printf ("Connected to remote target.\n");
6284 else
Daniel Malead01b2952012-11-29 21:49:15 +00006285 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006286 }
6287 }
6288 else
6289 {
Daniel Malead01b2952012-11-29 21:49:15 +00006290 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006291 }
6292}
6293
6294size_t
6295Process::GetThreadStatus (Stream &strm,
6296 bool only_threads_with_stop_reason,
6297 uint32_t start_frame,
6298 uint32_t num_frames,
6299 uint32_t num_frames_with_source)
6300{
6301 size_t num_thread_infos_dumped = 0;
6302
Jim Ingham4a65fb12014-03-07 11:20:03 +00006303 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6304 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6305 // ID's, and look them up one by one:
6306
6307 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006308 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006309 //Scope for thread list locker;
6310 {
6311 Mutex::Locker locker (GetThreadList().GetMutex());
6312 ThreadList &curr_thread_list = GetThreadList();
6313 num_threads = curr_thread_list.GetSize();
6314 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006315 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006316 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006317 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006318 }
6319
Greg Clayton7260f622011-04-18 08:33:37 +00006320 for (uint32_t i = 0; i < num_threads; i++)
6321 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006322 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006323 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006324 {
6325 if (only_threads_with_stop_reason)
6326 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006327 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006328 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006329 continue;
6330 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006331 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006332 start_frame,
6333 num_frames,
6334 num_frames_with_source);
6335 ++num_thread_infos_dumped;
6336 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006337 else
6338 {
6339 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6340 if (log)
6341 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6342
6343 }
Greg Clayton7260f622011-04-18 08:33:37 +00006344 }
6345 return num_thread_infos_dumped;
6346}
6347
Greg Claytona9f40ad2012-02-22 04:37:26 +00006348void
6349Process::AddInvalidMemoryRegion (const LoadRange &region)
6350{
6351 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6352}
6353
6354bool
6355Process::RemoveInvalidMemoryRange (const LoadRange &region)
6356{
6357 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6358}
6359
Jim Ingham372787f2012-04-07 00:00:41 +00006360void
6361Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6362{
6363 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6364}
6365
6366bool
6367Process::RunPreResumeActions ()
6368{
6369 bool result = true;
6370 while (!m_pre_resume_actions.empty())
6371 {
6372 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6373 m_pre_resume_actions.pop_back();
6374 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006375 if (result == true)
6376 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006377 }
6378 return result;
6379}
6380
6381void
6382Process::ClearPreResumeActions ()
6383{
6384 m_pre_resume_actions.clear();
6385}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006386
Zachary Turner93749ab2015-03-03 21:51:25 +00006387ProcessRunLock &
6388Process::GetRunLock()
6389{
6390 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6391 return m_private_run_lock;
6392 else
6393 return m_public_run_lock;
6394}
6395
Greg Claytonfa559e52012-05-18 02:38:05 +00006396void
6397Process::Flush ()
6398{
6399 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006400 m_extended_thread_list.Flush();
6401 m_extended_thread_stop_id = 0;
6402 m_queue_list.Clear();
6403 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006404}
Greg Clayton90ba8112012-12-05 00:16:59 +00006405
6406void
6407Process::DidExec ()
6408{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006409 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6410 if (log)
6411 log->Printf ("Process::%s()", __FUNCTION__);
6412
Greg Clayton90ba8112012-12-05 00:16:59 +00006413 Target &target = GetTarget();
6414 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006415 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006416 m_dynamic_checkers_ap.reset();
6417 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006418 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006419 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006420 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006421 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006422 m_image_tokens.clear();
6423 m_allocated_memory_cache.Clear();
6424 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006425 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006426 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006427 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006428 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006429 DoDidExec();
6430 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006431 // Flush the process (threads and all stack frames) after running CompleteAttach()
6432 // in case the dynamic loader loaded things in new locations.
6433 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006434
6435 // After we figure out what was loaded/unloaded in CompleteAttach,
6436 // we need to let the target know so it can do any cleanup it needs to.
6437 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006438}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006439
Jim Ingham1460e4b2014-01-10 23:46:59 +00006440addr_t
6441Process::ResolveIndirectFunction(const Address *address, Error &error)
6442{
6443 if (address == nullptr)
6444 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006445 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006446 return LLDB_INVALID_ADDRESS;
6447 }
6448
6449 addr_t function_addr = LLDB_INVALID_ADDRESS;
6450
6451 addr_t addr = address->GetLoadAddress(&GetTarget());
6452 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6453 if (iter != m_resolved_indirect_addresses.end())
6454 {
6455 function_addr = (*iter).second;
6456 }
6457 else
6458 {
6459 if (!InferiorCall(this, address, function_addr))
6460 {
6461 Symbol *symbol = address->CalculateSymbolContextSymbol();
6462 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6463 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6464 function_addr = LLDB_INVALID_ADDRESS;
6465 }
6466 else
6467 {
6468 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6469 }
6470 }
6471 return function_addr;
6472}
6473
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006474void
6475Process::ModulesDidLoad (ModuleList &module_list)
6476{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006477 SystemRuntime *sys_runtime = GetSystemRuntime();
6478 if (sys_runtime)
6479 {
6480 sys_runtime->ModulesDidLoad (module_list);
6481 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006482
Kuba Breckaafdf8422014-10-10 23:43:03 +00006483 GetJITLoaders().ModulesDidLoad (module_list);
6484
6485 // Give runtimes a chance to be created.
6486 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6487
6488 // Tell runtimes about new modules.
6489 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6490 {
6491 InstrumentationRuntimeSP runtime = pos->second;
6492 runtime->ModulesDidLoad(module_list);
6493 }
6494
Greg Clayton35ca64b2015-04-16 17:13:34 +00006495 // Let any language runtimes we have already created know
6496 // about the modules that loaded.
6497
6498 // Iterate over a copy of this language runtime list in case
6499 // the language runtime ModulesDidLoad somehow causes the language
6500 // riuntime to be unloaded.
6501 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6502 for (const auto &pair: language_runtimes)
6503 {
6504 // We must check language_runtime_sp to make sure it is not
6505 // NULL as we might cache the fact that we didn't have a
6506 // language runtime for a language.
6507 LanguageRuntimeSP language_runtime_sp = pair.second;
6508 if (language_runtime_sp)
6509 language_runtime_sp->ModulesDidLoad(module_list);
6510 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006511}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006512
6513ThreadCollectionSP
6514Process::GetHistoryThreads(lldb::addr_t addr)
6515{
6516 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006517
Kuba Breckaa51ea382014-09-06 01:33:13 +00006518 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6519
6520 if (! memory_history.get()) {
6521 return threads;
6522 }
6523
6524 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6525
6526 return threads;
6527}
Kuba Brecka63927542014-10-11 01:59:32 +00006528
6529InstrumentationRuntimeSP
6530Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6531{
6532 InstrumentationRuntimeCollection::iterator pos;
6533 pos = m_instrumentation_runtimes.find (type);
6534 if (pos == m_instrumentation_runtimes.end())
6535 {
6536 return InstrumentationRuntimeSP();
6537 }
6538 else
6539 return (*pos).second;
6540}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006541
6542bool
6543Process::GetModuleSpec(const FileSpec& module_file_spec,
6544 const ArchSpec& arch,
6545 ModuleSpec& module_spec)
6546{
6547 module_spec.Clear();
6548 return false;
6549}