blob: cc3b8761f0a010869f43867040ccc7461c04f6c0 [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
1458 m_stdio_communication.StopReadThread();
1459 m_stdio_communication.Disconnect();
1460 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;
2249 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2250 if (!error.Success() && show_error)
2251 {
Greg Clayton44d93782014-01-27 23:43:24 +00002252 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2253 symbol->GetAddress().GetLoadAddress(&m_target),
2254 owner->GetBreakpoint().GetID(),
2255 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002256 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002257 return LLDB_INVALID_BREAK_ID;
2258 }
2259 Address resolved_address(load_addr);
2260 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2261 owner->SetIsIndirect(true);
2262 }
2263 else
2264 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2265 }
2266 else
2267 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2268
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 if (load_addr != LLDB_INVALID_ADDRESS)
2270 {
2271 BreakpointSiteSP bp_site_sp;
2272
2273 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2274 // create a new breakpoint site and add it.
2275
2276 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2277
2278 if (bp_site_sp)
2279 {
2280 bp_site_sp->AddOwner (owner);
2281 owner->SetBreakpointSite (bp_site_sp);
2282 return bp_site_sp->GetID();
2283 }
2284 else
2285 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002286 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002287 if (bp_site_sp)
2288 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002289 Error error = EnableBreakpointSite (bp_site_sp.get());
2290 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291 {
2292 owner->SetBreakpointSite (bp_site_sp);
2293 return m_breakpoint_site_list.Add (bp_site_sp);
2294 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002295 else
2296 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002297 if (show_error)
2298 {
2299 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002300 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2301 load_addr,
2302 owner->GetBreakpoint().GetID(),
2303 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002304 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002305 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002306 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 }
2308 }
2309 }
2310 // We failed to enable the breakpoint
2311 return LLDB_INVALID_BREAK_ID;
2312
2313}
2314
2315void
2316Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2317{
2318 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2319 if (num_owners == 0)
2320 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002321 // Don't try to disable the site if we don't have a live process anymore.
2322 if (IsAlive())
2323 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2325 }
2326}
2327
2328
2329size_t
2330Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2331{
2332 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002333 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334
Jim Ingham20c77192011-06-29 19:42:28 +00002335 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002336 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002337 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2338 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002340 addr_t intersect_addr;
2341 size_t intersect_size;
2342 size_t opcode_offset;
2343 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002344 {
2345 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2346 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002347 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002348 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002349 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002350 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002352 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353 }
2354 return bytes_removed;
2355}
2356
2357
Greg Claytonded470d2011-03-19 01:12:21 +00002358
2359size_t
2360Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2361{
2362 PlatformSP platform_sp (m_target.GetPlatform());
2363 if (platform_sp)
2364 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2365 return 0;
2366}
2367
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002368Error
2369Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2370{
2371 Error error;
2372 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002373 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374 const addr_t bp_addr = bp_site->GetLoadAddress();
2375 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002376 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 if (bp_site->IsEnabled())
2378 {
2379 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002380 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 +00002381 return error;
2382 }
2383
2384 if (bp_addr == LLDB_INVALID_ADDRESS)
2385 {
2386 error.SetErrorString("BreakpointSite contains an invalid load address.");
2387 return error;
2388 }
2389 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2390 // trap for the breakpoint site
2391 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2392
2393 if (bp_opcode_size == 0)
2394 {
Daniel Malead01b2952012-11-29 21:49:15 +00002395 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002396 }
2397 else
2398 {
2399 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2400
2401 if (bp_opcode_bytes == NULL)
2402 {
2403 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2404 return error;
2405 }
2406
2407 // Save the original opcode by reading it
2408 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2409 {
2410 // Write a software breakpoint in place of the original opcode
2411 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2412 {
2413 uint8_t verify_bp_opcode_bytes[64];
2414 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2415 {
2416 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2417 {
2418 bp_site->SetEnabled(true);
2419 bp_site->SetType (BreakpointSite::eSoftware);
2420 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002421 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 bp_site->GetID(),
2423 (uint64_t)bp_addr);
2424 }
2425 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002426 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002427 }
2428 else
2429 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2430 }
2431 else
2432 error.SetErrorString("Unable to write breakpoint trap to memory.");
2433 }
2434 else
2435 error.SetErrorString("Unable to read memory at breakpoint address.");
2436 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002437 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002438 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439 bp_site->GetID(),
2440 (uint64_t)bp_addr,
2441 error.AsCString());
2442 return error;
2443}
2444
2445Error
2446Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2447{
2448 Error error;
2449 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002450 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451 addr_t bp_addr = bp_site->GetLoadAddress();
2452 lldb::user_id_t breakID = bp_site->GetID();
2453 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002454 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455
2456 if (bp_site->IsHardware())
2457 {
2458 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2459 }
2460 else if (bp_site->IsEnabled())
2461 {
2462 const size_t break_op_size = bp_site->GetByteSize();
2463 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2464 if (break_op_size > 0)
2465 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002466 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002467 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002468 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002469 bool break_op_found = false;
2470
2471 // Read the breakpoint opcode
2472 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2473 {
2474 bool verify = false;
2475 // Make sure we have the a breakpoint opcode exists at this address
2476 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2477 {
2478 break_op_found = true;
2479 // We found a valid breakpoint opcode at this address, now restore
2480 // the saved opcode.
2481 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2482 {
2483 verify = true;
2484 }
2485 else
2486 error.SetErrorString("Memory write failed when restoring original opcode.");
2487 }
2488 else
2489 {
2490 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2491 // Set verify to true and so we can check if the original opcode has already been restored
2492 verify = true;
2493 }
2494
2495 if (verify)
2496 {
Greg Claytonc982c762010-07-09 20:39:50 +00002497 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002498 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499 // Verify that our original opcode made it back to the inferior
2500 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2501 {
2502 // compare the memory we just read with the original opcode
2503 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2504 {
2505 // SUCCESS
2506 bp_site->SetEnabled(false);
2507 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002508 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 +00002509 return error;
2510 }
2511 else
2512 {
2513 if (break_op_found)
2514 error.SetErrorString("Failed to restore original opcode.");
2515 }
2516 }
2517 else
2518 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2519 }
2520 }
2521 else
2522 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2523 }
2524 }
2525 else
2526 {
2527 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002528 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 +00002529 return error;
2530 }
2531
2532 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002533 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002534 bp_site->GetID(),
2535 (uint64_t)bp_addr,
2536 error.AsCString());
2537 return error;
2538
2539}
2540
Greg Clayton58be07b2011-01-07 06:08:19 +00002541// Uncomment to verify memory caching works after making changes to caching code
2542//#define VERIFY_MEMORY_READS
2543
Sean Callanan64c0cf22012-06-07 22:26:42 +00002544size_t
2545Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2546{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002547 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002548 if (!GetDisableMemoryCache())
2549 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002550#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002551 // Memory caching is enabled, with debug verification
2552
2553 if (buf && size)
2554 {
2555 // Uncomment the line below to make sure memory caching is working.
2556 // I ran this through the test suite and got no assertions, so I am
2557 // pretty confident this is working well. If any changes are made to
2558 // memory caching, uncomment the line below and test your changes!
2559
2560 // Verify all memory reads by using the cache first, then redundantly
2561 // reading the same memory from the inferior and comparing to make sure
2562 // everything is exactly the same.
2563 std::string verify_buf (size, '\0');
2564 assert (verify_buf.size() == size);
2565 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2566 Error verify_error;
2567 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2568 assert (cache_bytes_read == verify_bytes_read);
2569 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2570 assert (verify_error.Success() == error.Success());
2571 return cache_bytes_read;
2572 }
2573 return 0;
2574#else // !defined(VERIFY_MEMORY_READS)
2575 // Memory caching is enabled, without debug verification
2576
2577 return m_memory_cache.Read (addr, buf, size, error);
2578#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002579 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002580 else
2581 {
2582 // Memory caching is disabled
2583
2584 return ReadMemoryFromInferior (addr, buf, size, error);
2585 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002586}
Greg Clayton58be07b2011-01-07 06:08:19 +00002587
Greg Clayton4c82d422012-05-18 23:20:01 +00002588size_t
2589Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2590{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002591 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002592 out_str.clear();
2593 addr_t curr_addr = addr;
2594 while (1)
2595 {
2596 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2597 if (length == 0)
2598 break;
2599 out_str.append(buf, length);
2600 // If we got "length - 1" bytes, we didn't get the whole C string, we
2601 // need to read some more characters
2602 if (length == sizeof(buf) - 1)
2603 curr_addr += length;
2604 else
2605 break;
2606 }
2607 return out_str.size();
2608}
2609
Greg Clayton58be07b2011-01-07 06:08:19 +00002610
2611size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002612Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2613 size_t type_width)
2614{
2615 size_t total_bytes_read = 0;
2616 if (dst && max_bytes && type_width && max_bytes >= type_width)
2617 {
2618 // Ensure a null terminator independent of the number of bytes that is read.
2619 memset (dst, 0, max_bytes);
2620 size_t bytes_left = max_bytes - type_width;
2621
2622 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2623 assert(sizeof(terminator) >= type_width &&
2624 "Attempting to validate a string with more than 4 bytes per character!");
2625
2626 addr_t curr_addr = addr;
2627 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2628 char *curr_dst = dst;
2629
2630 error.Clear();
2631 while (bytes_left > 0 && error.Success())
2632 {
2633 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2634 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2635 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2636
2637 if (bytes_read == 0)
2638 break;
2639
2640 // Search for a null terminator of correct size and alignment in bytes_read
2641 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2642 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2643 if (::strncmp(&dst[i], terminator, type_width) == 0)
2644 {
2645 error.Clear();
2646 return i;
2647 }
2648
2649 total_bytes_read += bytes_read;
2650 curr_dst += bytes_read;
2651 curr_addr += bytes_read;
2652 bytes_left -= bytes_read;
2653 }
2654 }
2655 else
2656 {
2657 if (max_bytes)
2658 error.SetErrorString("invalid arguments");
2659 }
2660 return total_bytes_read;
2661}
2662
2663// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2664// null terminators.
2665size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002666Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002667{
2668 size_t total_cstr_len = 0;
2669 if (dst && dst_max_len)
2670 {
Greg Claytone91b7952011-12-15 03:14:23 +00002671 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002672 // NULL out everything just to be safe
2673 memset (dst, 0, dst_max_len);
2674 Error error;
2675 addr_t curr_addr = addr;
2676 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2677 size_t bytes_left = dst_max_len - 1;
2678 char *curr_dst = dst;
2679
2680 while (bytes_left > 0)
2681 {
2682 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2683 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2684 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2685
2686 if (bytes_read == 0)
2687 {
Greg Claytone91b7952011-12-15 03:14:23 +00002688 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002689 dst[total_cstr_len] = '\0';
2690 break;
2691 }
2692 const size_t len = strlen(curr_dst);
2693
2694 total_cstr_len += len;
2695
2696 if (len < bytes_to_read)
2697 break;
2698
2699 curr_dst += bytes_read;
2700 curr_addr += bytes_read;
2701 bytes_left -= bytes_read;
2702 }
2703 }
Greg Claytone91b7952011-12-15 03:14:23 +00002704 else
2705 {
2706 if (dst == NULL)
2707 result_error.SetErrorString("invalid arguments");
2708 else
2709 result_error.Clear();
2710 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002711 return total_cstr_len;
2712}
2713
2714size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002715Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2716{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 if (buf == NULL || size == 0)
2718 return 0;
2719
2720 size_t bytes_read = 0;
2721 uint8_t *bytes = (uint8_t *)buf;
2722
2723 while (bytes_read < size)
2724 {
2725 const size_t curr_size = size - bytes_read;
2726 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2727 bytes + bytes_read,
2728 curr_size,
2729 error);
2730 bytes_read += curr_bytes_read;
2731 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2732 break;
2733 }
2734
2735 // Replace any software breakpoint opcodes that fall into this range back
2736 // into "buf" before we return
2737 if (bytes_read > 0)
2738 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2739 return bytes_read;
2740}
2741
Greg Clayton58a4c462010-12-16 20:01:20 +00002742uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002743Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002744{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002745 Scalar scalar;
2746 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2747 return scalar.ULongLong(fail_value);
2748 return fail_value;
2749}
2750
2751addr_t
2752Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2753{
2754 Scalar scalar;
2755 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2756 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2757 return LLDB_INVALID_ADDRESS;
2758}
2759
2760
2761bool
2762Process::WritePointerToMemory (lldb::addr_t vm_addr,
2763 lldb::addr_t ptr_value,
2764 Error &error)
2765{
2766 Scalar scalar;
2767 const uint32_t addr_byte_size = GetAddressByteSize();
2768 if (addr_byte_size <= 4)
2769 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002770 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002771 scalar = ptr_value;
2772 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002773}
2774
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775size_t
2776Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2777{
2778 size_t bytes_written = 0;
2779 const uint8_t *bytes = (const uint8_t *)buf;
2780
2781 while (bytes_written < size)
2782 {
2783 const size_t curr_size = size - bytes_written;
2784 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2785 bytes + bytes_written,
2786 curr_size,
2787 error);
2788 bytes_written += curr_bytes_written;
2789 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2790 break;
2791 }
2792 return bytes_written;
2793}
2794
2795size_t
2796Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2797{
Greg Clayton58be07b2011-01-07 06:08:19 +00002798#if defined (ENABLE_MEMORY_CACHING)
2799 m_memory_cache.Flush (addr, size);
2800#endif
2801
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002802 if (buf == NULL || size == 0)
2803 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002804
Jim Ingham4b536182011-08-09 02:12:22 +00002805 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002806
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807 // We need to write any data that would go where any current software traps
2808 // (enabled software breakpoints) any software traps (breakpoints) that we
2809 // may have placed in our tasks memory.
2810
Greg Claytond8cf1a12013-06-12 00:46:38 +00002811 BreakpointSiteList bp_sites_in_range;
2812
2813 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002814 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002815 // No breakpoint sites overlap
2816 if (bp_sites_in_range.IsEmpty())
2817 return WriteMemoryPrivate (addr, buf, size, error);
2818 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002820 const uint8_t *ubuf = (const uint8_t *)buf;
2821 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002822
Greg Claytond8cf1a12013-06-12 00:46:38 +00002823 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2824
2825 if (error.Success())
2826 {
2827 addr_t intersect_addr;
2828 size_t intersect_size;
2829 size_t opcode_offset;
2830 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2831 assert(intersects);
2832 assert(addr <= intersect_addr && intersect_addr < addr + size);
2833 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2834 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2835
2836 // Check for bytes before this breakpoint
2837 const addr_t curr_addr = addr + bytes_written;
2838 if (intersect_addr > curr_addr)
2839 {
2840 // There are some bytes before this breakpoint that we need to
2841 // just write to memory
2842 size_t curr_size = intersect_addr - curr_addr;
2843 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2844 ubuf + bytes_written,
2845 curr_size,
2846 error);
2847 bytes_written += curr_bytes_written;
2848 if (curr_bytes_written != curr_size)
2849 {
2850 // We weren't able to write all of the requested bytes, we
2851 // are done looping and will return the number of bytes that
2852 // we have written so far.
2853 if (error.Success())
2854 error.SetErrorToGenericError();
2855 }
2856 }
2857 // Now write any bytes that would cover up any software breakpoints
2858 // directly into the breakpoint opcode buffer
2859 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2860 bytes_written += intersect_size;
2861 }
2862 });
2863
2864 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002865 WriteMemoryPrivate (addr + bytes_written,
2866 ubuf + bytes_written,
2867 size - bytes_written,
2868 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002869 }
2870 }
2871 else
2872 {
2873 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002874 }
2875
2876 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002877 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002879
2880size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002881Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002882{
2883 if (byte_size == UINT32_MAX)
2884 byte_size = scalar.GetByteSize();
2885 if (byte_size > 0)
2886 {
2887 uint8_t buf[32];
2888 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2889 if (mem_size > 0)
2890 return WriteMemory(addr, buf, mem_size, error);
2891 else
2892 error.SetErrorString ("failed to get scalar as memory data");
2893 }
2894 else
2895 {
2896 error.SetErrorString ("invalid scalar value");
2897 }
2898 return 0;
2899}
2900
2901size_t
2902Process::ReadScalarIntegerFromMemory (addr_t addr,
2903 uint32_t byte_size,
2904 bool is_signed,
2905 Scalar &scalar,
2906 Error &error)
2907{
Greg Clayton7060f892013-05-01 23:41:30 +00002908 uint64_t uval = 0;
2909 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002910 {
Greg Clayton7060f892013-05-01 23:41:30 +00002911 error.SetErrorString ("byte size is zero");
2912 }
2913 else if (byte_size & (byte_size - 1))
2914 {
2915 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2916 }
2917 else if (byte_size <= sizeof(uval))
2918 {
2919 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002920 if (bytes_read == byte_size)
2921 {
2922 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002923 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002924 if (byte_size <= 4)
2925 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002926 else
Greg Clayton7060f892013-05-01 23:41:30 +00002927 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002928 if (is_signed)
2929 scalar.SignExtend(byte_size * 8);
2930 return bytes_read;
2931 }
2932 }
2933 else
2934 {
2935 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2936 }
2937 return 0;
2938}
2939
Greg Claytond495c532011-05-17 03:37:42 +00002940#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941addr_t
2942Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2943{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002944 if (GetPrivateState() != eStateStopped)
2945 return LLDB_INVALID_ADDRESS;
2946
Greg Claytond495c532011-05-17 03:37:42 +00002947#if defined (USE_ALLOCATE_MEMORY_CACHE)
2948 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2949#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002950 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002951 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002952 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002953 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 +00002954 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002955 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002956 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002957 m_mod_id.GetStopID(),
2958 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002959 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002960#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002961}
2962
Sean Callanan90539452011-09-20 23:01:51 +00002963bool
2964Process::CanJIT ()
2965{
Sean Callanana7b443a2012-02-14 22:50:38 +00002966 if (m_can_jit == eCanJITDontKnow)
2967 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002968 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002969 Error err;
2970
2971 uint64_t allocated_memory = AllocateMemory(8,
2972 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2973 err);
2974
2975 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002976 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002977 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002978 if (log)
2979 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2980 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002981 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002982 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002983 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002984 if (log)
2985 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2986 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002987
2988 DeallocateMemory (allocated_memory);
2989 }
2990
Sean Callanan90539452011-09-20 23:01:51 +00002991 return m_can_jit == eCanJITYes;
2992}
2993
2994void
2995Process::SetCanJIT (bool can_jit)
2996{
2997 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2998}
2999
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003000Error
3001Process::DeallocateMemory (addr_t ptr)
3002{
Greg Claytond495c532011-05-17 03:37:42 +00003003 Error error;
3004#if defined (USE_ALLOCATE_MEMORY_CACHE)
3005 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
3006 {
Daniel Malead01b2952012-11-29 21:49:15 +00003007 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00003008 }
3009#else
3010 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00003011
Greg Clayton5160ce52013-03-27 23:08:40 +00003012 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00003013 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003014 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 +00003015 ptr,
3016 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00003017 m_mod_id.GetStopID(),
3018 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00003019#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00003020 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021}
3022
Han Ming Ongc811d382012-11-17 00:33:14 +00003023
Greg Claytonc9660542012-02-05 02:38:54 +00003024ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00003025Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00003026 lldb::addr_t header_addr,
3027 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00003028{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003029 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00003030 if (module_sp)
3031 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003032 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00003033 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003034 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003035 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00003036 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003037 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00003038}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003039
Zachary Turner93749ab2015-03-03 21:51:25 +00003040bool
3041Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3042{
3043 MemoryRegionInfo range_info;
3044 permissions = 0;
3045 Error error (GetMemoryRegionInfo (load_addr, range_info));
3046 if (!error.Success())
3047 return false;
3048 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3049 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3050 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3051 {
3052 return false;
3053 }
3054
3055 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3056 permissions |= lldb::ePermissionsReadable;
3057
3058 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3059 permissions |= lldb::ePermissionsWritable;
3060
3061 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3062 permissions |= lldb::ePermissionsExecutable;
3063
3064 return true;
3065}
3066
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003068Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069{
3070 Error error;
3071 error.SetErrorString("watchpoints are not supported");
3072 return error;
3073}
3074
3075Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003076Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077{
3078 Error error;
3079 error.SetErrorString("watchpoints are not supported");
3080 return error;
3081}
3082
3083StateType
3084Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3085{
3086 StateType state;
3087 // Now wait for the process to launch and return control to us, and then
3088 // call DidLaunch:
3089 while (1)
3090 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003091 event_sp.reset();
3092 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3093
Greg Clayton2637f822011-11-17 01:23:07 +00003094 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003095 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003096
3097 // If state is invalid, then we timed out
3098 if (state == eStateInvalid)
3099 break;
3100
3101 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 HandlePrivateEvent (event_sp);
3103 }
3104 return state;
3105}
3106
Greg Clayton332e8b12015-01-13 21:13:08 +00003107void
3108Process::LoadOperatingSystemPlugin(bool flush)
3109{
3110 if (flush)
3111 m_thread_list.Clear();
3112 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3113 if (flush)
3114 Flush();
3115}
3116
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003118Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003119{
3120 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003122 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003123 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003124 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003125 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003126 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003127 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003128
Greg Claytonaa149cb2011-08-11 02:48:45 +00003129 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130 if (exe_module)
3131 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003132 char local_exec_file_path[PATH_MAX];
3133 char platform_exec_file_path[PATH_MAX];
3134 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3135 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136 if (exe_module->GetFileSpec().Exists())
3137 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003138 // Install anything that might need to be installed prior to launching.
3139 // For host systems, this will do nothing, but if we are connected to a
3140 // remote platform it will install any needed binaries
3141 error = GetTarget().Install(&launch_info);
3142 if (error.Fail())
3143 return error;
3144
Greg Clayton71337622011-02-24 22:24:29 +00003145 if (PrivateStateThreadIsValid ())
3146 PausePrivateStateThread ();
3147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148 error = WillLaunch (exe_module);
3149 if (error.Success())
3150 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003151 const bool restarted = false;
3152 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003153 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154
Ed Maste64fad602013-07-29 20:58:06 +00003155 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003156 {
3157 // Now launch using these arguments.
3158 error = DoLaunch (exe_module, launch_info);
3159 }
3160 else
3161 {
3162 // This shouldn't happen
3163 error.SetErrorString("failed to acquire process run lock");
3164 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165
3166 if (error.Fail())
3167 {
3168 if (GetID() != LLDB_INVALID_PROCESS_ID)
3169 {
3170 SetID (LLDB_INVALID_PROCESS_ID);
3171 const char *error_string = error.AsCString();
3172 if (error_string == NULL)
3173 error_string = "launch failed";
3174 SetExitStatus (-1, error_string);
3175 }
3176 }
3177 else
3178 {
3179 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003180 TimeValue timeout_time;
3181 timeout_time = TimeValue::Now();
3182 timeout_time.OffsetWithSeconds(10);
3183 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003184
Greg Clayton1a38ea72011-06-22 01:42:17 +00003185 if (state == eStateInvalid || event_sp.get() == NULL)
3186 {
3187 // We were able to launch the process, but we failed to
3188 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003189 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003190 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003191 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003192 }
3193 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003194 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003195
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003196 DidLaunch ();
3197
Greg Claytonc859e2d2012-02-13 23:10:39 +00003198 DynamicLoader *dyld = GetDynamicLoader ();
3199 if (dyld)
3200 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003201
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003202 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003203
Jason Molendaeef51062013-11-05 03:57:19 +00003204 SystemRuntime *system_runtime = GetSystemRuntime ();
3205 if (system_runtime)
3206 system_runtime->DidLaunch();
3207
Greg Clayton332e8b12015-01-13 21:13:08 +00003208 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003209
3210 // Note, the stop event was consumed above, but not handled. This was done
3211 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3212 // Directly set the state. This is done to prevent a stop message with a bunch
3213 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3214 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003215
3216 if (PrivateStateThreadIsValid ())
3217 ResumePrivateStateThread ();
3218 else
3219 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003220
3221 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003222
3223 // Target was stopped at entry as was intended. Need to notify the listeners
3224 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003225 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003226 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003227 }
3228 else if (state == eStateExited)
3229 {
3230 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3231 // not likely to work, and return an invalid pid.
3232 HandlePrivateEvent (event_sp);
3233 }
3234 }
3235 }
3236 }
3237 else
3238 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003239 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003240 }
3241 }
3242 return error;
3243}
3244
Greg Claytonc3776bf2012-02-09 06:16:32 +00003245
3246Error
3247Process::LoadCore ()
3248{
3249 Error error = DoLoadCore();
3250 if (error.Success())
3251 {
Greg Clayton35824e32015-02-20 20:59:47 +00003252 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003253 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003254
Greg Claytonc3776bf2012-02-09 06:16:32 +00003255 if (PrivateStateThreadIsValid ())
3256 ResumePrivateStateThread ();
3257 else
3258 StartPrivateStateThread ();
3259
Greg Claytonc859e2d2012-02-13 23:10:39 +00003260 DynamicLoader *dyld = GetDynamicLoader ();
3261 if (dyld)
3262 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003263
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003264 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003265
Jason Molendaeef51062013-11-05 03:57:19 +00003266 SystemRuntime *system_runtime = GetSystemRuntime ();
3267 if (system_runtime)
3268 system_runtime->DidAttach();
3269
Greg Claytonc859e2d2012-02-13 23:10:39 +00003270 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003271 // We successfully loaded a core file, now pretend we stopped so we can
3272 // show all of the threads in the core file and explore the crashed
3273 // state.
3274 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003275
3276 // Wait indefinitely for a stopped event since we just posted one above...
3277 lldb::EventSP event_sp;
3278 listener.WaitForEvent (NULL, event_sp);
3279 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3280
3281 if (!StateIsStoppedState (state, false))
3282 {
3283 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3284 if (log)
3285 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3286 error.SetErrorString ("Did not get stopped event after loading the core file.");
3287 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003288 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003289 }
3290 return error;
3291}
3292
Greg Claytonc859e2d2012-02-13 23:10:39 +00003293DynamicLoader *
3294Process::GetDynamicLoader ()
3295{
3296 if (m_dyld_ap.get() == NULL)
3297 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3298 return m_dyld_ap.get();
3299}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003300
Todd Fialaaf245d12014-06-30 21:05:18 +00003301const lldb::DataBufferSP
3302Process::GetAuxvData()
3303{
3304 return DataBufferSP ();
3305}
3306
Andrew MacPherson17220c12014-03-05 10:12:43 +00003307JITLoaderList &
3308Process::GetJITLoaders ()
3309{
3310 if (!m_jit_loaders_ap)
3311 {
3312 m_jit_loaders_ap.reset(new JITLoaderList());
3313 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3314 }
3315 return *m_jit_loaders_ap;
3316}
3317
Jason Molendaeef51062013-11-05 03:57:19 +00003318SystemRuntime *
3319Process::GetSystemRuntime ()
3320{
3321 if (m_system_runtime_ap.get() == NULL)
3322 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3323 return m_system_runtime_ap.get();
3324}
3325
Todd Fiala76e0fc92014-08-27 22:58:26 +00003326Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3327 NextEventAction (process),
3328 m_exec_count (exec_count)
3329{
3330 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3331 if (log)
3332 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3333}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003334
Jim Inghambb3a2832011-01-29 01:49:25 +00003335Process::NextEventAction::EventActionResult
3336Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003337{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003338 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3339
Jim Inghambb3a2832011-01-29 01:49:25 +00003340 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003341 if (log)
3342 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3343
3344 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003345 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003346 case eStateAttaching:
3347 return eEventActionSuccess;
3348
Greg Clayton513c26c2011-01-29 07:10:55 +00003349 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003350 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003351 return eEventActionRetry;
3352
3353 case eStateStopped:
3354 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003355 {
3356 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003357 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003358 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003359 // We don't want these events to be reported, so go set the ShouldReportStop here:
3360 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3361
Greg Claytonc9ed4782011-11-12 02:10:56 +00003362 if (m_exec_count > 0)
3363 {
3364 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003365
3366 if (log)
3367 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3368
Jim Ingham221d51c2013-05-08 00:35:16 +00003369 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003370 return eEventActionRetry;
3371 }
3372 else
3373 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003374 if (log)
3375 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3376
Greg Claytonc9ed4782011-11-12 02:10:56 +00003377 m_process->CompleteAttach ();
3378 return eEventActionSuccess;
3379 }
3380 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003381 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003382
Greg Clayton513c26c2011-01-29 07:10:55 +00003383 default:
3384 case eStateExited:
3385 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003386 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003387 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003388
3389 m_exit_string.assign ("No valid Process");
3390 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003391}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392
Jim Inghambb3a2832011-01-29 01:49:25 +00003393Process::NextEventAction::EventActionResult
3394Process::AttachCompletionHandler::HandleBeingInterrupted()
3395{
3396 return eEventActionSuccess;
3397}
3398
3399const char *
3400Process::AttachCompletionHandler::GetExitString ()
3401{
3402 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003403}
3404
Greg Clayton8012cad2014-11-17 19:39:20 +00003405Listener &
3406ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3407{
3408 if (m_listener_sp)
3409 return *m_listener_sp;
3410 else
3411 return debugger.GetListener();
3412}
3413
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003414Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003415Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003416{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003417 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003418 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003419 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003420 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003421 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003422 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003423 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003424
Greg Clayton144f3a92011-11-15 03:53:30 +00003425 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003426 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003427 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003428 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003429 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003430
Greg Clayton144f3a92011-11-15 03:53:30 +00003431 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003432 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003433 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3434
3435 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003436 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003437 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3438 if (error.Success())
3439 {
Ed Maste64fad602013-07-29 20:58:06 +00003440 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003441 {
3442 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003443 const bool restarted = false;
3444 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003445 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003446 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003447 }
3448 else
3449 {
3450 // This shouldn't happen
3451 error.SetErrorString("failed to acquire process run lock");
3452 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003453
Greg Clayton144f3a92011-11-15 03:53:30 +00003454 if (error.Fail())
3455 {
3456 if (GetID() != LLDB_INVALID_PROCESS_ID)
3457 {
3458 SetID (LLDB_INVALID_PROCESS_ID);
3459 if (error.AsCString() == NULL)
3460 error.SetErrorString("attach failed");
3461
3462 SetExitStatus(-1, error.AsCString());
3463 }
3464 }
3465 else
3466 {
3467 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3468 StartPrivateStateThread();
3469 }
3470 return error;
3471 }
Greg Claytone996fd32011-03-08 22:40:15 +00003472 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003473 else
Greg Claytone996fd32011-03-08 22:40:15 +00003474 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003475 ProcessInstanceInfoList process_infos;
3476 PlatformSP platform_sp (m_target.GetPlatform ());
3477
3478 if (platform_sp)
3479 {
3480 ProcessInstanceInfoMatch match_info;
3481 match_info.GetProcessInfo() = attach_info;
3482 match_info.SetNameMatchType (eNameMatchEquals);
3483 platform_sp->FindProcesses (match_info, process_infos);
3484 const uint32_t num_matches = process_infos.GetSize();
3485 if (num_matches == 1)
3486 {
3487 attach_pid = process_infos.GetProcessIDAtIndex(0);
3488 // Fall through and attach using the above process ID
3489 }
3490 else
3491 {
3492 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3493 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003494 {
3495 StreamString s;
3496 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3497 for (size_t i = 0; i < num_matches; i++)
3498 {
3499 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3500 }
3501 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3502 process_name,
3503 s.GetData());
3504 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003505 else
3506 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3507 }
3508 }
3509 else
3510 {
3511 error.SetErrorString ("invalid platform, can't find processes by name");
3512 return error;
3513 }
Greg Claytone996fd32011-03-08 22:40:15 +00003514 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003515 }
3516 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003517 {
3518 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003519 }
3520 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003521
3522 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003523 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003524 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003525 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003526 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003527
Ed Maste64fad602013-07-29 20:58:06 +00003528 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003529 {
3530 // Now attach using these arguments.
3531 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003532 const bool restarted = false;
3533 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003534 error = DoAttachToProcessWithID (attach_pid, attach_info);
3535 }
3536 else
3537 {
3538 // This shouldn't happen
3539 error.SetErrorString("failed to acquire process run lock");
3540 }
3541
Greg Clayton144f3a92011-11-15 03:53:30 +00003542 if (error.Success())
3543 {
3544
3545 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3546 StartPrivateStateThread();
3547 }
3548 else
Greg Claytone996fd32011-03-08 22:40:15 +00003549 {
3550 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003551 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003552
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003553 const char *error_string = error.AsCString();
3554 if (error_string == NULL)
3555 error_string = "attach failed";
3556
3557 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003558 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559 }
3560 }
3561 return error;
3562}
3563
Greg Clayton93d3c8332011-02-16 04:46:07 +00003564void
3565Process::CompleteAttach ()
3566{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003567 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3568 if (log)
3569 log->Printf ("Process::%s()", __FUNCTION__);
3570
Greg Clayton93d3c8332011-02-16 04:46:07 +00003571 // Let the process subclass figure out at much as it can about the process
3572 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003573 ArchSpec process_arch;
3574 DidAttach(process_arch);
3575
3576 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003577 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003578 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003579 if (log)
3580 {
3581 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3582 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3583 __FUNCTION__,
3584 triple_str ? triple_str : "<null>");
3585 }
3586 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003587
Jim Ingham4299fdb2011-09-15 01:10:17 +00003588 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3589 // the same as the one we've already set, switch architectures.
3590 PlatformSP platform_sp (m_target.GetPlatform ());
3591 assert (platform_sp.get());
3592 if (platform_sp)
3593 {
Greg Clayton70512312012-05-08 01:45:38 +00003594 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003595 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003596 {
3597 ArchSpec platform_arch;
3598 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3599 if (platform_sp)
3600 {
3601 m_target.SetPlatform (platform_sp);
3602 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003603 if (log)
3604 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 +00003605 }
3606 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003607 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003608 {
3609 ProcessInstanceInfo process_info;
3610 platform_sp->GetProcessInfo (GetID(), process_info);
3611 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003612 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003613 {
Greg Clayton70512312012-05-08 01:45:38 +00003614 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003615 if (log)
3616 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 ());
3617 }
Greg Clayton70512312012-05-08 01:45:38 +00003618 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003619 }
3620
3621 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003622 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003623 DynamicLoader *dyld = GetDynamicLoader ();
3624 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003625 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003626 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003627 if (log)
3628 {
3629 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3630 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3631 __FUNCTION__,
3632 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3633 dyld->GetPluginName().AsCString ("<unnamed>"));
3634 }
3635 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003636
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003637 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003638
Jason Molendaeef51062013-11-05 03:57:19 +00003639 SystemRuntime *system_runtime = GetSystemRuntime ();
3640 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003641 {
Jason Molendaeef51062013-11-05 03:57:19 +00003642 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003643 if (log)
3644 {
3645 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3646 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3647 __FUNCTION__,
3648 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3649 system_runtime->GetPluginName().AsCString("<unnamed>"));
3650 }
3651 }
Jason Molendaeef51062013-11-05 03:57:19 +00003652
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003653 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003654 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003655 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003656 Mutex::Locker modules_locker(target_modules.GetMutex());
3657 size_t num_modules = target_modules.GetSize();
3658 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003659
Andy Gibbsa297a972013-06-19 19:04:53 +00003660 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003661 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003662 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003663 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003664 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003665 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003666 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003667 break;
3668 }
3669 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003670 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003671 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003672 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003673 if (log)
3674 {
3675 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3676 log->Printf ("Process::%s after looping through modules, target executable is %s",
3677 __FUNCTION__,
3678 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3679 }
3680 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003681
3682 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003683}
3684
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003685Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003686Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003687{
Greg Claytonb766a732011-02-04 01:58:07 +00003688 m_abi_sp.reset();
3689 m_process_input_reader.reset();
3690
3691 // Find the process and its architecture. Make sure it matches the architecture
3692 // of the current Target, and if not adjust it.
3693
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003694 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003695 if (error.Success())
3696 {
Greg Clayton71337622011-02-24 22:24:29 +00003697 if (GetID() != LLDB_INVALID_PROCESS_ID)
3698 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003699 EventSP event_sp;
3700 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3701
3702 if (state == eStateStopped || state == eStateCrashed)
3703 {
3704 // If we attached and actually have a process on the other end, then
3705 // this ended up being the equivalent of an attach.
3706 CompleteAttach ();
3707
3708 // This delays passing the stopped event to listeners till
3709 // CompleteAttach gets a chance to complete...
3710 HandlePrivateEvent (event_sp);
3711
3712 }
Greg Clayton71337622011-02-24 22:24:29 +00003713 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003714
3715 if (PrivateStateThreadIsValid ())
3716 ResumePrivateStateThread ();
3717 else
3718 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003719 }
3720 return error;
3721}
3722
3723
3724Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003725Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726{
Greg Clayton5160ce52013-03-27 23:08:40 +00003727 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003729 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003730 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003731 StateAsCString(m_public_state.GetValue()),
3732 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733
3734 Error error (WillResume());
3735 // Tell the process it is about to resume before the thread list
3736 if (error.Success())
3737 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003738 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739 // can let all of our threads know that they are about to be
3740 // resumed. Threads will each be called with
3741 // Thread::WillResume(StateType) where StateType contains the state
3742 // that they are supposed to have when the process is resumed
3743 // (suspended/running/stepping). Threads should also check
3744 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003745 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003746 if (m_thread_list.WillResume())
3747 {
Jim Ingham372787f2012-04-07 00:00:41 +00003748 // Last thing, do the PreResumeActions.
3749 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003750 {
Jim Ingham0161b492013-02-09 01:29:05 +00003751 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003752 }
3753 else
3754 {
3755 m_mod_id.BumpResumeID();
3756 error = DoResume();
3757 if (error.Success())
3758 {
3759 DidResume();
3760 m_thread_list.DidResume();
3761 if (log)
3762 log->Printf ("Process thinks the process has resumed.");
3763 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764 }
3765 }
3766 else
3767 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003768 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3769 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003770 // and let the world handle them.
3771 if (log)
3772 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3773
3774 SetPrivateState(eStateRunning);
3775 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003776 }
3777 }
Jim Ingham444586b2011-01-24 06:34:17 +00003778 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003779 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780 return error;
3781}
3782
3783Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003784Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003786 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3787 // in case it was already set and some thread plan logic calls halt on its
3788 // own.
3789 m_clear_thread_plans_on_stop |= clear_thread_plans;
3790
Jim Inghamaacc3182012-06-06 00:29:30 +00003791 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3792 // we could just straightaway get another event. It just narrows the window...
3793 m_currently_handling_event.WaitForValueEqualTo(false);
3794
3795
Jim Inghambb3a2832011-01-29 01:49:25 +00003796 // Pause our private state thread so we can ensure no one else eats
3797 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003798 Listener halt_listener ("lldb.process.halt_listener");
3799 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003800
Jim Inghambb3a2832011-01-29 01:49:25 +00003801 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003802 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003803
Greg Clayton06357c92014-07-30 17:38:47 +00003804 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003805 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003806 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003807
Greg Clayton513c26c2011-01-29 07:10:55 +00003808 bool caused_stop = false;
3809
3810 // Ask the process subclass to actually halt our process
3811 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003812 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003813 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003814 if (m_public_state.GetValue() == eStateAttaching)
3815 {
Greg Clayton06357c92014-07-30 17:38:47 +00003816 // Don't hijack and eat the eStateExited as the code that was doing
3817 // the attach will be waiting for this event...
3818 RestorePrivateProcessEvents();
3819 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003820 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:58 +00003821 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:55 +00003822 }
3823 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003824 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003825 // If "caused_stop" is true, then DoHalt stopped the process. If
3826 // "caused_stop" is false, the process was already stopped.
3827 // If the DoHalt caused the process to stop, then we want to catch
3828 // this event and set the interrupted bool to true before we pass
3829 // this along so clients know that the process was interrupted by
3830 // a halt command.
3831 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003832 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003833 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003834 TimeValue timeout_time;
3835 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003836 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003837 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3838 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003839
Jim Ingham0f16e732011-02-08 05:20:59 +00003840 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003841 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003842 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003843 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003844 }
3845 else
3846 {
Greg Clayton2637f822011-11-17 01:23:07 +00003847 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003848 {
3849 // We caused the process to interrupt itself, so mark this
3850 // as such in the stop event so clients can tell an interrupted
3851 // process from a natural stop
3852 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3853 }
3854 else
3855 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003856 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003857 if (log)
3858 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3859 error.SetErrorString ("Did not get stopped event after halt.");
3860 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003861 }
3862 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003863 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003864 }
3865 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003867 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003868 if (!restored_process_events)
3869 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003870
3871 // Post any event we might have consumed. If all goes well, we will have
3872 // stopped the process, intercepted the event and set the interrupted
3873 // bool in the event. Post it to the private event queue and that will end up
3874 // correctly setting the state.
3875 if (event_sp)
3876 m_private_state_broadcaster.BroadcastEvent(event_sp);
3877
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003878 return error;
3879}
3880
3881Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003882Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3883{
3884 Error error;
3885 if (m_public_state.GetValue() == eStateRunning)
3886 {
3887 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3888 if (log)
3889 log->Printf("Process::Destroy() About to halt.");
3890 error = Halt();
3891 if (error.Success())
3892 {
3893 // Consume the halt event.
3894 TimeValue timeout (TimeValue::Now());
3895 timeout.OffsetWithSeconds(1);
3896 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3897
3898 // If the process exited while we were waiting for it to stop, put the exited event into
3899 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3900 // they don't have a process anymore...
3901
3902 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3903 {
3904 if (log)
3905 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3906 return error;
3907 }
3908 else
3909 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3910
3911 if (state != eStateStopped)
3912 {
3913 if (log)
3914 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3915 // If we really couldn't stop the process then we should just error out here, but if the
3916 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3917 StateType private_state = m_private_state.GetValue();
3918 if (private_state != eStateStopped)
3919 {
3920 return error;
3921 }
3922 }
3923 }
3924 else
3925 {
3926 if (log)
3927 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3928 }
3929 }
3930 return error;
3931}
3932
3933Error
Jim Inghamacff8952013-05-02 00:27:30 +00003934Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003935{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003936 EventSP exit_event_sp;
3937 Error error;
3938 m_destroy_in_process = true;
3939
3940 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003941
3942 if (error.Success())
3943 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003944 if (DetachRequiresHalt())
3945 {
3946 error = HaltForDestroyOrDetach (exit_event_sp);
3947 if (!error.Success())
3948 {
3949 m_destroy_in_process = false;
3950 return error;
3951 }
3952 else if (exit_event_sp)
3953 {
3954 // We shouldn't need to do anything else here. There's no process left to detach from...
3955 StopPrivateStateThread();
3956 m_destroy_in_process = false;
3957 return error;
3958 }
3959 }
3960
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003961 m_thread_list.DiscardThreadPlans();
3962 DisableAllBreakpointSites();
3963
Jim Inghamacff8952013-05-02 00:27:30 +00003964 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003965 if (error.Success())
3966 {
3967 DidDetach();
3968 StopPrivateStateThread();
3969 }
Jim Inghamacff8952013-05-02 00:27:30 +00003970 else
3971 {
3972 return error;
3973 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003974 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003975 m_destroy_in_process = false;
3976
3977 // If we exited when we were waiting for a process to stop, then
3978 // forward the event here so we don't lose the event
3979 if (exit_event_sp)
3980 {
3981 // Directly broadcast our exited event because we shut down our
3982 // private state thread above
3983 BroadcastEvent(exit_event_sp);
3984 }
3985
3986 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3987 // the last events through the event system, in which case we might strand the write lock. Unlock
3988 // it here so when we do to tear down the process we don't get an error destroying the lock.
3989
Ed Maste64fad602013-07-29 20:58:06 +00003990 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991 return error;
3992}
3993
3994Error
Jason Molendaede31932015-04-17 05:01:58 +00003995Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003996{
Jim Ingham09437922013-03-01 20:04:25 +00003997
3998 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3999 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
4000 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00004001
4002 if (force_kill)
4003 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00004004
Ilia Kfcc89a02015-03-26 07:08:47 +00004005 if (GetShouldDetach())
4006 {
4007 // FIXME: This will have to be a process setting:
4008 bool keep_stopped = false;
4009 Detach(keep_stopped);
4010 }
4011
Jim Ingham09437922013-03-01 20:04:25 +00004012 m_destroy_in_process = true;
4013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004014 Error error (WillDestroy());
4015 if (error.Success())
4016 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00004017 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004018 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00004019 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004020 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00004021 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004022
Jim Inghamaacc3182012-06-06 00:29:30 +00004023 if (m_public_state.GetValue() != eStateRunning)
4024 {
4025 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4026 // kill it, we don't want it hitting a breakpoint...
4027 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4028 // we're not going to have much luck doing this now.
4029 m_thread_list.DiscardThreadPlans();
4030 DisableAllBreakpointSites();
4031 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004032
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004033 error = DoDestroy();
4034 if (error.Success())
4035 {
4036 DidDestroy();
4037 StopPrivateStateThread();
4038 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004039 m_stdio_communication.StopReadThread();
4040 m_stdio_communication.Disconnect();
Vince Harrondf3f00f2015-02-10 21:09:04 +00004041 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00004042
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004043 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00004044 {
4045 m_process_input_reader->SetIsDone(true);
4046 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004047 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00004048 }
4049
Greg Clayton85fb1b92012-09-11 02:33:37 +00004050 // If we exited when we were waiting for a process to stop, then
4051 // forward the event here so we don't lose the event
4052 if (exit_event_sp)
4053 {
4054 // Directly broadcast our exited event because we shut down our
4055 // private state thread above
4056 BroadcastEvent(exit_event_sp);
4057 }
4058
Jim Inghamb1e2e842012-04-12 18:49:31 +00004059 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4060 // the last events through the event system, in which case we might strand the write lock. Unlock
4061 // 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 +00004062 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004063 }
Jim Ingham09437922013-03-01 20:04:25 +00004064
4065 m_destroy_in_process = false;
4066
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004067 return error;
4068}
4069
4070Error
4071Process::Signal (int signal)
4072{
4073 Error error (WillSignal());
4074 if (error.Success())
4075 {
4076 error = DoSignal(signal);
4077 if (error.Success())
4078 DidSignal();
4079 }
4080 return error;
4081}
4082
Zachary Turner93749ab2015-03-03 21:51:25 +00004083void
4084Process::SetUnixSignals (const UnixSignalsSP &signals_sp)
4085{
4086 assert (signals_sp && "null signals_sp");
4087 m_unix_signals_sp = signals_sp;
4088}
4089
4090UnixSignals &
4091Process::GetUnixSignals ()
4092{
4093 assert (m_unix_signals_sp && "null m_unix_signals_sp");
4094 return *m_unix_signals_sp;
4095}
4096
Greg Clayton514487e2011-02-15 21:59:32 +00004097lldb::ByteOrder
4098Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004099{
Greg Clayton514487e2011-02-15 21:59:32 +00004100 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004101}
4102
4103uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00004104Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004105{
Greg Clayton514487e2011-02-15 21:59:32 +00004106 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004107}
4108
Greg Clayton514487e2011-02-15 21:59:32 +00004109
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004110bool
4111Process::ShouldBroadcastEvent (Event *event_ptr)
4112{
4113 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4114 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00004115 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00004116
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117 switch (state)
4118 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004119 case eStateDetached:
4120 case eStateExited:
4121 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00004122 m_stdio_communication.SynchronizeWithReadThread();
4123 // fall-through
4124 case eStateConnected:
4125 case eStateAttaching:
4126 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004127 // These events indicate changes in the state of the debugging session, always report them.
4128 return_value = true;
4129 break;
4130 case eStateInvalid:
4131 // We stopped for no apparent reason, don't report it.
4132 return_value = false;
4133 break;
4134 case eStateRunning:
4135 case eStateStepping:
4136 // If we've started the target running, we handle the cases where we
4137 // are already running and where there is a transition from stopped to
4138 // running differently.
4139 // running -> running: Automatically suppress extra running events
4140 // stopped -> running: Report except when there is one or more no votes
4141 // and no yes votes.
4142 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004143 if (m_force_next_event_delivery)
4144 return_value = true;
4145 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004146 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004147 switch (m_last_broadcast_state)
4148 {
4149 case eStateRunning:
4150 case eStateStepping:
4151 // We always suppress multiple runnings with no PUBLIC stop in between.
4152 return_value = false;
4153 break;
4154 default:
4155 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004156 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004157 // events. If I run the lldb/test/thread/a.out file and
4158 // break at main.cpp:58, run and hit the breakpoints on
4159 // multiple threads, then somehow during the stepping over
4160 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004161
Jim Ingham1460e4b2014-01-10 23:46:59 +00004162 // This is a transition from stop to run.
4163 switch (m_thread_list.ShouldReportRun (event_ptr))
4164 {
4165 case eVoteYes:
4166 case eVoteNoOpinion:
4167 return_value = true;
4168 break;
4169 case eVoteNo:
4170 return_value = false;
4171 break;
4172 }
4173 break;
4174 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004175 }
4176 break;
4177 case eStateStopped:
4178 case eStateCrashed:
4179 case eStateSuspended:
4180 {
4181 // We've stopped. First see if we're going to restart the target.
4182 // If we are going to stop, then we always broadcast the event.
4183 // 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 +00004184 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004185
Pavel Labath3f5df532015-03-12 10:12:41 +00004186 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00004187 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004188 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004189 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004190 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004191 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004192 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004193 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004194 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4195 // so they can properly set their state.
4196 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004197 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004198 }
4199 else
4200 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004201 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4202 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004203
Jim Ingham0161b492013-02-09 01:29:05 +00004204 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4205 // Asking the thread list is also not likely to go well, since we are running again.
4206 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004207
Jim Ingham0161b492013-02-09 01:29:05 +00004208 if (!was_restarted)
4209 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004210
Jim Ingham221d51c2013-05-08 00:35:16 +00004211 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004212 {
Jim Ingham0161b492013-02-09 01:29:05 +00004213 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4214 if (log)
4215 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004216 should_resume, StateAsCString(state),
4217 was_restarted, stop_vote);
4218
Jim Ingham0161b492013-02-09 01:29:05 +00004219 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004220 {
4221 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004222 return_value = true;
4223 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004224 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225 case eVoteNo:
4226 return_value = false;
4227 break;
4228 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004229
Jim Inghamcb95f342012-09-05 21:13:56 +00004230 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004231 {
4232 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004233 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4234 static_cast<void*>(event_ptr),
4235 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004236 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004237 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004238 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004239
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004240 }
4241 else
4242 {
4243 return_value = true;
4244 SynchronouslyNotifyStateChanged (state);
4245 }
4246 }
4247 }
Jim Ingham0161b492013-02-09 01:29:05 +00004248 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004249 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004250
Jim Ingham1460e4b2014-01-10 23:46:59 +00004251 // Forcing the next event delivery is a one shot deal. So reset it here.
4252 m_force_next_event_delivery = false;
4253
Jim Ingham0161b492013-02-09 01:29:05 +00004254 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4255 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4256 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4257 // because the PublicState reflects the last event pulled off the queue, and there may be several
4258 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4259 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004260
Jim Ingham0161b492013-02-09 01:29:05 +00004261 if (return_value)
4262 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004263
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004264 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004265 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004266 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004267 StateAsCString(m_last_broadcast_state),
4268 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004269 return return_value;
4270}
4271
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004272
4273bool
Jim Ingham372787f2012-04-07 00:00:41 +00004274Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004275{
Greg Clayton5160ce52013-03-27 23:08:40 +00004276 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004277
Greg Clayton8b82f082011-04-12 05:54:46 +00004278 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004279 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004280 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4281
Jim Ingham372787f2012-04-07 00:00:41 +00004282 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004283 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004284
4285 // Create a thread that watches our internal state and controls which
4286 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004287 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004288
Zachary Turner39de3112014-09-09 20:54:56 +00004289 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004290 {
Zachary Turner39de3112014-09-09 20:54:56 +00004291 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4292 if (already_running)
4293 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4294 else
4295 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004296 }
Jim Ingham372787f2012-04-07 00:00:41 +00004297 else
Todd Fiala17096d72014-07-16 19:03:16 +00004298 {
4299 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004300 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004301 else
Zachary Turner39de3112014-09-09 20:54:56 +00004302 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004303 }
4304
Jim Ingham076b3042012-04-10 01:21:57 +00004305 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00004306 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004307 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004308 {
4309 ResumePrivateStateThread();
4310 return true;
4311 }
4312 else
4313 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004314}
4315
4316void
4317Process::PausePrivateStateThread ()
4318{
4319 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4320}
4321
4322void
4323Process::ResumePrivateStateThread ()
4324{
4325 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4326}
4327
4328void
4329Process::StopPrivateStateThread ()
4330{
Greg Clayton8b82f082011-04-12 05:54:46 +00004331 if (PrivateStateThreadIsValid ())
4332 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004333 else
4334 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004335 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004336 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004337 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004338 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004339}
4340
4341void
4342Process::ControlPrivateStateThread (uint32_t signal)
4343{
Greg Clayton5160ce52013-03-27 23:08:40 +00004344 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004345
4346 assert (signal == eBroadcastInternalStateControlStop ||
4347 signal == eBroadcastInternalStateControlPause ||
4348 signal == eBroadcastInternalStateControlResume);
4349
4350 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004351 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004352
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004353 // Signal the private state thread. First we should copy this is case the
4354 // thread starts exiting since the private state thread will NULL this out
4355 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004356 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004357 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004358 {
4359 TimeValue timeout_time;
4360 bool timed_out;
4361
4362 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4363
4364 timeout_time = TimeValue::Now();
4365 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004366 if (log)
4367 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004368 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4369 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4370
4371 if (signal == eBroadcastInternalStateControlStop)
4372 {
4373 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004374 {
Zachary Turner39de3112014-09-09 20:54:56 +00004375 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004376 if (log)
4377 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4378 }
4379 else
4380 {
4381 if (log)
4382 log->Printf ("The control event killed the private state thread without having to cancel.");
4383 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004384
4385 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004386 private_state_thread.Join(&result);
4387 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004388 }
4389 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004390 else
4391 {
4392 if (log)
4393 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4394 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004395}
4396
4397void
Jim Inghamcfc09352012-07-27 23:57:19 +00004398Process::SendAsyncInterrupt ()
4399{
4400 if (PrivateStateThreadIsValid())
4401 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4402 else
4403 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4404}
4405
4406void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004407Process::HandlePrivateEvent (EventSP &event_sp)
4408{
Greg Clayton5160ce52013-03-27 23:08:40 +00004409 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004410 m_resume_requested = false;
4411
Jim Inghamaacc3182012-06-06 00:29:30 +00004412 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004413
Greg Clayton414f5d32011-01-25 02:58:48 +00004414 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004415
4416 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004417 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004418 {
Jim Ingham754ab982011-01-29 04:05:41 +00004419 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004420 if (log)
4421 log->Printf ("Ran next event action, result was %d.", action_result);
4422
Jim Inghambb3a2832011-01-29 01:49:25 +00004423 switch (action_result)
4424 {
4425 case NextEventAction::eEventActionSuccess:
4426 SetNextEventAction(NULL);
4427 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004428
Jim Inghambb3a2832011-01-29 01:49:25 +00004429 case NextEventAction::eEventActionRetry:
4430 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004431
Jim Inghambb3a2832011-01-29 01:49:25 +00004432 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004433 // Handle Exiting Here. If we already got an exited event,
4434 // we should just propagate it. Otherwise, swallow this event,
4435 // and set our state to exit so the next event will kill us.
4436 if (new_state != eStateExited)
4437 {
4438 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004439 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004440 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004441 SetNextEventAction(NULL);
4442 return;
4443 }
4444 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004445 break;
4446 }
4447 }
4448
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004449 // See if we should broadcast this state to external clients?
4450 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004451
4452 if (should_broadcast)
4453 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004454 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004455 if (log)
4456 {
Daniel Malead01b2952012-11-29 21:49:15 +00004457 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004458 __FUNCTION__,
4459 GetID(),
4460 StateAsCString(new_state),
4461 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004462 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004463 }
Jim Ingham9575d842011-03-11 03:53:59 +00004464 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004465 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004466 {
4467 // Only push the input handler if we aren't fowarding events,
4468 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004469 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004470 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4471 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004472 {
Greg Clayton44d93782014-01-27 23:43:24 +00004473 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004474 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4475 if (log)
4476 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4477 }
Greg Clayton44d93782014-01-27 23:43:24 +00004478 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004479 else if (StateIsStoppedState(new_state, false))
4480 {
4481 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4482 {
4483 // If the lldb_private::Debugger is handling the events, we don't
4484 // want to pop the process IOHandler here, we want to do it when
4485 // we receive the stopped event so we can carefully control when
4486 // the process IOHandler is popped because when we stop we want to
4487 // display some text stating how and why we stopped, then maybe some
4488 // process/thread/frame info, and then we want the "(lldb) " prompt
4489 // to show up. If we pop the process IOHandler here, then we will
4490 // cause the command interpreter to become the top IOHandler after
4491 // the process pops off and it will update its prompt right away...
4492 // See the Debugger.cpp file where it calls the function as
4493 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4494 // Otherwise we end up getting overlapping "(lldb) " prompts and
4495 // garbled output.
4496 //
4497 // If we aren't handling the events in the debugger (which is indicated
4498 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4499 // are hijacked, then we always pop the process IO handler manually.
4500 // Hijacking happens when the internal process state thread is running
4501 // thread plans, or when commands want to run in synchronous mode
4502 // and they call "process->WaitForProcessToStop()". An example of something
4503 // that will hijack the events is a simple expression:
4504 //
4505 // (lldb) expr (int)puts("hello")
4506 //
4507 // This will cause the internal process state thread to resume and halt
4508 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4509 // events) and we do need the IO handler to be pushed and popped
4510 // correctly.
4511
4512 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4513 PopProcessIOHandler ();
4514 }
4515 }
Jim Ingham9575d842011-03-11 03:53:59 +00004516
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004517 BroadcastEvent (event_sp);
4518 }
4519 else
4520 {
4521 if (log)
4522 {
Daniel Malead01b2952012-11-29 21:49:15 +00004523 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004524 __FUNCTION__,
4525 GetID(),
4526 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004527 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004528 }
4529 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004530 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004531}
4532
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004533thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004534Process::PrivateStateThread (void *arg)
4535{
4536 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004537 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004538 return result;
4539}
4540
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004541thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004542Process::RunPrivateStateThread ()
4543{
Jim Ingham076b3042012-04-10 01:21:57 +00004544 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004545 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004546
Greg Clayton5160ce52013-03-27 23:08:40 +00004547 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004548 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004549 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4550 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004551
4552 bool exit_now = false;
4553 while (!exit_now)
4554 {
4555 EventSP event_sp;
4556 WaitForEventsPrivate (NULL, event_sp, control_only);
4557 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4558 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004559 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004560 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4561 __FUNCTION__, static_cast<void*>(this), GetID(),
4562 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004563
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004564 switch (event_sp->GetType())
4565 {
4566 case eBroadcastInternalStateControlStop:
4567 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004568 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004569
4570 case eBroadcastInternalStateControlPause:
4571 control_only = true;
4572 break;
4573
4574 case eBroadcastInternalStateControlResume:
4575 control_only = false;
4576 break;
4577 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004578
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004579 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004580 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004581 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004582 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4583 {
4584 if (m_public_state.GetValue() == eStateAttaching)
4585 {
4586 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004587 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4588 __FUNCTION__, static_cast<void*>(this),
4589 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004590 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4591 }
4592 else
4593 {
4594 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004595 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4596 __FUNCTION__, static_cast<void*>(this),
4597 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004598 Halt();
4599 }
4600 continue;
4601 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004602
4603 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4604
4605 if (internal_state != eStateInvalid)
4606 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004607 if (m_clear_thread_plans_on_stop &&
4608 StateIsStoppedState(internal_state, true))
4609 {
4610 m_clear_thread_plans_on_stop = false;
4611 m_thread_list.DiscardThreadPlans();
4612 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004613 HandlePrivateEvent (event_sp);
4614 }
4615
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004616 if (internal_state == eStateInvalid ||
4617 internal_state == eStateExited ||
4618 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004619 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004620 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004621 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4622 __FUNCTION__, static_cast<void*>(this), GetID(),
4623 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004624
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004625 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004626 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004627 }
4628
Caroline Tice20ad3c42010-10-29 21:48:37 +00004629 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004630 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004631 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4632 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004633
Ed Maste64fad602013-07-29 20:58:06 +00004634 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004635 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004636 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004637 return NULL;
4638}
4639
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004640//------------------------------------------------------------------
4641// Process Event Data
4642//------------------------------------------------------------------
4643
4644Process::ProcessEventData::ProcessEventData () :
4645 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004646 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004647 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004648 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004649 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004650 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004651{
4652}
4653
4654Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4655 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004656 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004657 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004658 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004659 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004660 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004661{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004662 if (process_sp)
4663 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004664}
4665
4666Process::ProcessEventData::~ProcessEventData()
4667{
4668}
4669
4670const ConstString &
4671Process::ProcessEventData::GetFlavorString ()
4672{
4673 static ConstString g_flavor ("Process::ProcessEventData");
4674 return g_flavor;
4675}
4676
4677const ConstString &
4678Process::ProcessEventData::GetFlavor () const
4679{
4680 return ProcessEventData::GetFlavorString ();
4681}
4682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004683void
4684Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4685{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004686 ProcessSP process_sp(m_process_wp.lock());
4687
4688 if (!process_sp)
4689 return;
4690
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004691 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004692 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4693 // the public event queue, then other times when we're pretending that this is where we stopped at the
4694 // end of expression evaluation. m_update_state is used to distinguish these
4695 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004696 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004697 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004698 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004699
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004700 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004701
4702 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4703 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4704 // end up restarting the process.
4705 if (m_interrupted)
4706 return;
4707
4708 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004709 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004710 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004711 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004712 uint32_t num_threads = curr_thread_list.GetSize();
4713 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004714
Jim Ingham4b536182011-08-09 02:12:22 +00004715 // The actions might change one of the thread's stop_info's opinions about whether we should
4716 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004717
4718 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4719 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4720 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4721 // 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
4722 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004723 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004724 for (idx = 0; idx < num_threads; ++idx)
4725 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4726
Jim Inghamc7078c22012-12-13 22:24:15 +00004727 // Use this to track whether we should continue from here. We will only continue the target running if
4728 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4729 // then it doesn't matter what the other threads say...
4730
4731 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004732
Jim Ingham0ad7e052013-04-25 02:04:59 +00004733 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4734 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4735 // thing to do is, and it's better to let the user decide than continue behind their backs.
4736
4737 bool does_anybody_have_an_opinion = false;
4738
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004739 for (idx = 0; idx < num_threads; ++idx)
4740 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004741 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004742 if (curr_thread_list.GetSize() != num_threads)
4743 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004744 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004745 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004746 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 +00004747 break;
4748 }
4749
4750 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4751
4752 if (thread_sp->GetIndexID() != thread_index_array[idx])
4753 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004754 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004755 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004756 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004757 idx,
4758 thread_index_array[idx],
4759 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004760 break;
4761 }
4762
Jim Inghamb15bfc72010-10-20 00:39:53 +00004763 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004764 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004765 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004766 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004767 bool this_thread_wants_to_stop;
4768 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004769 {
Jim Ingham0161b492013-02-09 01:29:05 +00004770 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4771 }
4772 else
4773 {
4774 stop_info_sp->PerformAction(event_ptr);
4775 // The stop action might restart the target. If it does, then we want to mark that in the
4776 // event so that whoever is receiving it will know to wait for the running event and reflect
4777 // that state appropriately.
4778 // We also need to stop processing actions, since they aren't expecting the target to be running.
4779
4780 // FIXME: we might have run.
4781 if (stop_info_sp->HasTargetRunSinceMe())
4782 {
4783 SetRestarted (true);
4784 break;
4785 }
4786
4787 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004788 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004789
Jim Inghamc7078c22012-12-13 22:24:15 +00004790 if (still_should_stop == false)
4791 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004792 }
4793 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004794
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004795
Jim Inghama8ca6e22013-05-03 23:04:37 +00004796 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004797 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004798 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004799 {
4800 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004801 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004802 // Use the public resume method here, since this is just
4803 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004804 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004805 }
4806 else
4807 {
4808 // If we didn't restart, run the Stop Hooks here:
4809 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004810 process_sp->GetTarget().RunStopHooks();
4811 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004812 SetRestarted(true);
4813 }
Jim Ingham9575d842011-03-11 03:53:59 +00004814 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004815 }
4816}
4817
4818void
4819Process::ProcessEventData::Dump (Stream *s) const
4820{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004821 ProcessSP process_sp(m_process_wp.lock());
4822
4823 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004824 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004825 static_cast<void*>(process_sp.get()), process_sp->GetID());
4826 else
4827 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004828
Greg Clayton8b82f082011-04-12 05:54:46 +00004829 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004830}
4831
4832const Process::ProcessEventData *
4833Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4834{
4835 if (event_ptr)
4836 {
4837 const EventData *event_data = event_ptr->GetData();
4838 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4839 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4840 }
4841 return NULL;
4842}
4843
4844ProcessSP
4845Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4846{
4847 ProcessSP process_sp;
4848 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4849 if (data)
4850 process_sp = data->GetProcessSP();
4851 return process_sp;
4852}
4853
4854StateType
4855Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4856{
4857 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4858 if (data == NULL)
4859 return eStateInvalid;
4860 else
4861 return data->GetState();
4862}
4863
4864bool
4865Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4866{
4867 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4868 if (data == NULL)
4869 return false;
4870 else
4871 return data->GetRestarted();
4872}
4873
4874void
4875Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4876{
4877 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4878 if (data != NULL)
4879 data->SetRestarted(new_value);
4880}
4881
Jim Ingham0161b492013-02-09 01:29:05 +00004882size_t
4883Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4884{
4885 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4886 if (data != NULL)
4887 return data->GetNumRestartedReasons();
4888 else
4889 return 0;
4890}
4891
4892const char *
4893Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4894{
4895 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4896 if (data != NULL)
4897 return data->GetRestartedReasonAtIndex(idx);
4898 else
4899 return NULL;
4900}
4901
4902void
4903Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4904{
4905 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4906 if (data != NULL)
4907 data->AddRestartedReason(reason);
4908}
4909
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004910bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004911Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4912{
4913 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4914 if (data == NULL)
4915 return false;
4916 else
4917 return data->GetInterrupted ();
4918}
4919
4920void
4921Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4922{
4923 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4924 if (data != NULL)
4925 data->SetInterrupted(new_value);
4926}
4927
4928bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004929Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4930{
4931 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4932 if (data)
4933 {
4934 data->SetUpdateStateOnRemoval();
4935 return true;
4936 }
4937 return false;
4938}
4939
Greg Claytond9e416c2012-02-18 05:35:26 +00004940lldb::TargetSP
4941Process::CalculateTarget ()
4942{
4943 return m_target.shared_from_this();
4944}
4945
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004946void
Greg Clayton0603aa92010-10-04 01:05:56 +00004947Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004948{
Greg Claytonc14ee322011-09-22 04:58:26 +00004949 exe_ctx.SetTargetPtr (&m_target);
4950 exe_ctx.SetProcessPtr (this);
4951 exe_ctx.SetThreadPtr(NULL);
4952 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004953}
4954
Greg Claytone996fd32011-03-08 22:40:15 +00004955//uint32_t
4956//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4957//{
4958// return 0;
4959//}
4960//
4961//ArchSpec
4962//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4963//{
4964// return Host::GetArchSpecForExistingProcess (pid);
4965//}
4966//
4967//ArchSpec
4968//Process::GetArchSpecForExistingProcess (const char *process_name)
4969//{
4970// return Host::GetArchSpecForExistingProcess (process_name);
4971//}
4972//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004973void
4974Process::AppendSTDOUT (const char * s, size_t len)
4975{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004976 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004977 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004978 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004979}
4980
4981void
Greg Clayton93e86192011-11-13 04:45:22 +00004982Process::AppendSTDERR (const char * s, size_t len)
4983{
4984 Mutex::Locker locker (m_stdio_communication_mutex);
4985 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004986 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004987}
4988
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004989void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004990Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004991{
4992 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004993 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004994 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4995}
4996
4997size_t
4998Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4999{
5000 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005001 if (m_profile_data.empty())
5002 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005003
5004 std::string &one_profile_data = m_profile_data.front();
5005 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005006 if (bytes_available > 0)
5007 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005008 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005009 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005010 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5011 static_cast<void*>(buf),
5012 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005013 if (bytes_available > buf_size)
5014 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005015 memcpy(buf, one_profile_data.c_str(), buf_size);
5016 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005017 bytes_available = buf_size;
5018 }
5019 else
5020 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005021 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005022 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005023 }
5024 }
5025 return bytes_available;
5026}
5027
5028
Greg Clayton93e86192011-11-13 04:45:22 +00005029//------------------------------------------------------------------
5030// Process STDIO
5031//------------------------------------------------------------------
5032
5033size_t
5034Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5035{
5036 Mutex::Locker locker(m_stdio_communication_mutex);
5037 size_t bytes_available = m_stdout_data.size();
5038 if (bytes_available > 0)
5039 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005040 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005041 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005042 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5043 static_cast<void*>(buf),
5044 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005045 if (bytes_available > buf_size)
5046 {
5047 memcpy(buf, m_stdout_data.c_str(), buf_size);
5048 m_stdout_data.erase(0, buf_size);
5049 bytes_available = buf_size;
5050 }
5051 else
5052 {
5053 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5054 m_stdout_data.clear();
5055 }
5056 }
5057 return bytes_available;
5058}
5059
5060
5061size_t
5062Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5063{
5064 Mutex::Locker locker(m_stdio_communication_mutex);
5065 size_t bytes_available = m_stderr_data.size();
5066 if (bytes_available > 0)
5067 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005068 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005069 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005070 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5071 static_cast<void*>(buf),
5072 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005073 if (bytes_available > buf_size)
5074 {
5075 memcpy(buf, m_stderr_data.c_str(), buf_size);
5076 m_stderr_data.erase(0, buf_size);
5077 bytes_available = buf_size;
5078 }
5079 else
5080 {
5081 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5082 m_stderr_data.clear();
5083 }
5084 }
5085 return bytes_available;
5086}
5087
5088void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005089Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5090{
5091 Process *process = (Process *) baton;
5092 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5093}
5094
Greg Clayton44d93782014-01-27 23:43:24 +00005095class IOHandlerProcessSTDIO :
5096 public IOHandler
5097{
5098public:
5099 IOHandlerProcessSTDIO (Process *process,
5100 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005101 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005102 m_process (process),
5103 m_read_file (),
5104 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005105 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005106 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005107 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00005108 m_read_file.SetDescriptor(GetInputFD(), false);
5109 }
5110
5111 virtual
5112 ~IOHandlerProcessSTDIO ()
5113 {
5114
5115 }
5116
Greg Clayton44d93782014-01-27 23:43:24 +00005117 // Each IOHandler gets to run until it is done. It should read data
5118 // from the "in" and place output into "out" and "err and return
5119 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00005120 void
5121 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00005122 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005123 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005124 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005125 SetIsDone(true);
5126 return;
5127 }
5128
5129 SetIsDone(false);
5130 const int read_fd = m_read_file.GetDescriptor();
5131 TerminalState terminal_state;
5132 terminal_state.Save (read_fd, false);
5133 Terminal terminal(read_fd);
5134 terminal.SetCanonical(false);
5135 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005136// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005137#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005138 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5139 while (!GetIsDone())
5140 {
5141 fd_set read_fdset;
5142 FD_ZERO (&read_fdset);
5143 FD_SET (read_fd, &read_fdset);
5144 FD_SET (pipe_read_fd, &read_fdset);
5145 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5146 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5147 if (num_set_fds < 0)
5148 {
5149 const int select_errno = errno;
5150
5151 if (select_errno != EINTR)
5152 SetIsDone(true);
5153 }
5154 else if (num_set_fds > 0)
5155 {
5156 char ch = 0;
5157 size_t n;
5158 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00005159 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005160 n = 1;
5161 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005162 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005163 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005164 SetIsDone(true);
5165 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005166 else
5167 SetIsDone(true);
5168 }
5169 if (FD_ISSET (pipe_read_fd, &read_fdset))
5170 {
5171 size_t bytes_read;
5172 // Consume the interrupt byte
5173 Error error = m_pipe.Read(&ch, 1, bytes_read);
5174 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00005175 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005176 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00005177 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005178 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00005179 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005180 break;
5181 case 'i':
5182 if (StateIsRunningState(m_process->GetState()))
5183 m_process->Halt();
5184 break;
Greg Clayton44d93782014-01-27 23:43:24 +00005185 }
5186 }
5187 }
Greg Clayton44d93782014-01-27 23:43:24 +00005188 }
Greg Clayton44d93782014-01-27 23:43:24 +00005189 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005190#endif
5191 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005192 }
5193
Pavel Labath44464872015-05-27 12:40:32 +00005194 void
5195 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005196 {
Greg Clayton19e11352014-02-26 22:47:33 +00005197 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005198 size_t bytes_written = 0;
5199 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005200 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005201
Pavel Labath44464872015-05-27 12:40:32 +00005202 bool
5203 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005204 {
Greg Clayton19e11352014-02-26 22:47:33 +00005205 // Do only things that are safe to do in an interrupt context (like in
5206 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5207 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5208 // that was written to the pipe and then call m_process->Halt() from a
5209 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005210 if (m_active)
5211 {
5212 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005213 size_t bytes_written = 0;
5214 Error result = m_pipe.Write(&ch, 1, bytes_written);
5215 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005216 }
5217 else
5218 {
5219 // This IOHandler might be pushed on the stack, but not being run currently
5220 // so do the right thing if we aren't actively watching for STDIN by sending
5221 // the interrupt to the process. Otherwise the write to the pipe above would
5222 // do nothing. This can happen when the command interpreter is running and
5223 // gets a "expression ...". It will be on the IOHandler thread and sending
5224 // the input is complete to the delegate which will cause the expression to
5225 // run, which will push the process IO handler, but not run it.
5226
5227 if (StateIsRunningState(m_process->GetState()))
5228 {
5229 m_process->SendAsyncInterrupt();
5230 return true;
5231 }
5232 }
5233 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005234 }
Greg Clayton44d93782014-01-27 23:43:24 +00005235
Pavel Labath44464872015-05-27 12:40:32 +00005236 void
5237 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005238 {
5239
5240 }
5241
5242protected:
5243 Process *m_process;
5244 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5245 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005246 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005247};
5248
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005249void
Greg Clayton44d93782014-01-27 23:43:24 +00005250Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005251{
5252 // First set up the Read Thread for reading/handling process I/O
5253
Greg Clayton44d93782014-01-27 23:43:24 +00005254 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005255
5256 if (conn_ap.get())
5257 {
5258 m_stdio_communication.SetConnection (conn_ap.release());
5259 if (m_stdio_communication.IsConnected())
5260 {
5261 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5262 m_stdio_communication.StartReadThread();
5263
5264 // Now read thread is set up, set up input reader.
5265
5266 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005267 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005268 }
5269 }
5270}
5271
Greg Claytonb4874f12014-02-28 18:22:24 +00005272bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005273Process::ProcessIOHandlerIsActive ()
5274{
5275 IOHandlerSP io_handler_sp (m_process_input_reader);
5276 if (io_handler_sp)
5277 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5278 return false;
5279}
5280bool
Greg Clayton44d93782014-01-27 23:43:24 +00005281Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005282{
Greg Clayton44d93782014-01-27 23:43:24 +00005283 IOHandlerSP io_handler_sp (m_process_input_reader);
5284 if (io_handler_sp)
5285 {
Pavel Labath44464872015-05-27 12:40:32 +00005286 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5287 if (log)
5288 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5289
Greg Clayton44d93782014-01-27 23:43:24 +00005290 io_handler_sp->SetIsDone(false);
5291 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005292 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005293 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005294 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005295}
5296
Greg Claytonb4874f12014-02-28 18:22:24 +00005297bool
Greg Clayton44d93782014-01-27 23:43:24 +00005298Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005299{
Greg Clayton44d93782014-01-27 23:43:24 +00005300 IOHandlerSP io_handler_sp (m_process_input_reader);
5301 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005302 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5303 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005304}
5305
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005306// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005307void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005308Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005309{
Greg Clayton6920b522012-08-22 18:39:03 +00005310 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005311}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005312
Greg Clayton99d0faf2010-11-18 23:32:35 +00005313void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005314Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005315{
Greg Clayton6920b522012-08-22 18:39:03 +00005316 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005317}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005318
Jim Ingham1624a2d2014-05-05 02:26:40 +00005319ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005320Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005321 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005322 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005323 Stream &errors)
5324{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005325 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005326
Jim Ingham77787032011-01-20 02:03:18 +00005327 if (thread_plan_sp.get() == NULL)
5328 {
5329 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005330 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005331 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005332
Jim Ingham7d7931d2013-03-28 00:05:34 +00005333 if (!thread_plan_sp->ValidatePlan(NULL))
5334 {
5335 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005336 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005337 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005338
Greg Claytonc14ee322011-09-22 04:58:26 +00005339 if (exe_ctx.GetProcessPtr() != this)
5340 {
5341 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005342 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005343 }
5344
5345 Thread *thread = exe_ctx.GetThreadPtr();
5346 if (thread == NULL)
5347 {
5348 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005349 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005350 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005351
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005352 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5353 // For that to be true the plan can't be private - since private plans suppress themselves in the
5354 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005355
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005356 bool orig_plan_private = thread_plan_sp->GetPrivate();
5357 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005358
Jim Ingham444586b2011-01-24 06:34:17 +00005359 if (m_private_state.GetValue() != eStateStopped)
5360 {
5361 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005362 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005363 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005364
Jim Ingham66243842011-08-13 00:56:10 +00005365 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005366 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005367 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005368 if (!selected_frame_sp)
5369 {
5370 thread->SetSelectedFrame(0);
5371 selected_frame_sp = thread->GetSelectedFrame();
5372 if (!selected_frame_sp)
5373 {
5374 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005375 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005376 }
5377 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005378
Jim Ingham11b0e052013-02-19 23:22:45 +00005379 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005380
5381 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5382 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005383
Greg Claytonc14ee322011-09-22 04:58:26 +00005384 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005385
Jim Ingham66243842011-08-13 00:56:10 +00005386 uint32_t selected_tid;
5387 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005388 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005389 {
5390 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005391 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005392 }
5393 else
5394 {
5395 selected_tid = LLDB_INVALID_THREAD_ID;
5396 }
5397
Zachary Turner39de3112014-09-09 20:54:56 +00005398 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005399 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005400 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005401
Greg Clayton5160ce52013-03-27 23:08:40 +00005402 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005403 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005404 {
Jim Ingham076b3042012-04-10 01:21:57 +00005405 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5406 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005407 // 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 +00005408 // we are fielding public events here.
5409 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005410 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 +00005411
Jim Ingham372787f2012-04-07 00:00:41 +00005412 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005413
5414 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5415 // returning control here.
5416 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5417 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5418 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5419 // do just what we want.
5420 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5421 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5422 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5423 old_state = m_public_state.GetValue();
5424 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005425
Jim Ingham076b3042012-04-10 01:21:57 +00005426 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005427 StartPrivateStateThread(true);
5428 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005429
Jim Ingham372787f2012-04-07 00:00:41 +00005430 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005431
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005432 if (options.GetDebug())
5433 {
5434 // In this case, we aren't actually going to run, we just want to stop right away.
5435 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5436 // FIXME: To make this prettier we should invent some stop reason for this, but that
5437 // is only cosmetic, and this functionality is only of use to lldb developers who can
5438 // live with not pretty...
5439 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005440 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005441 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005442
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005443 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005444
Sean Callanana46ec452012-07-11 21:31:24 +00005445 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005446
Jim Ingham77787032011-01-20 02:03:18 +00005447 {
Sean Callanana46ec452012-07-11 21:31:24 +00005448 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5449 // restored on exit to the function.
5450 //
5451 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5452 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005453
Sean Callanana46ec452012-07-11 21:31:24 +00005454 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005455
Jim Inghamf48169b2010-11-30 02:22:11 +00005456 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005457 {
5458 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005459 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005460 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005461 thread->GetIndexID(),
5462 thread->GetID(),
5463 s.GetData());
5464 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005465
Sean Callanana46ec452012-07-11 21:31:24 +00005466 bool got_event;
5467 lldb::EventSP event_sp;
5468 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005469
Sean Callanana46ec452012-07-11 21:31:24 +00005470 TimeValue* timeout_ptr = NULL;
5471 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005472
Jim Ingham0161b492013-02-09 01:29:05 +00005473 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 +00005474 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005475 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005476 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005477
Jim Ingham0161b492013-02-09 01:29:05 +00005478 // This is just for accounting:
5479 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005480
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005481 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005482 uint32_t one_thread_timeout_usec;
5483 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005484
5485 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5486 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5487 // first timeout already.
5488
5489 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005490 {
5491 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005492 one_thread_timeout_usec = 0;
5493 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005494 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005495 else
Jim Ingham0161b492013-02-09 01:29:05 +00005496 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005497 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005498
Jim Ingham914f4e72014-03-28 21:58:28 +00005499 // If the overall wait is forever, then we only need to set the one thread timeout:
5500 if (timeout_usec == 0)
5501 {
Ed Maste801335c2014-03-31 19:28:14 +00005502 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005503 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005504 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005505 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005506 }
Jim Ingham0161b492013-02-09 01:29:05 +00005507 else
5508 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005509 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5510 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5511 uint64_t computed_one_thread_timeout;
5512 if (option_one_thread_timeout != 0)
5513 {
5514 if (timeout_usec < option_one_thread_timeout)
5515 {
5516 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005517 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005518 }
5519 computed_one_thread_timeout = option_one_thread_timeout;
5520 }
5521 else
5522 {
5523 computed_one_thread_timeout = timeout_usec / 2;
5524 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5525 computed_one_thread_timeout = default_one_thread_timeout_usec;
5526 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005527 one_thread_timeout_usec = computed_one_thread_timeout;
5528 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5529
Jim Ingham0161b492013-02-09 01:29:05 +00005530 }
Jim Ingham0161b492013-02-09 01:29:05 +00005531 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005532
5533 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005534 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 +00005535 options.GetStopOthers(),
5536 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005537 before_first_timeout,
5538 one_thread_timeout_usec,
5539 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005540
Jim Ingham1460e4b2014-01-10 23:46:59 +00005541 // This isn't going to work if there are unfetched events on the queue.
5542 // Are there cases where we might want to run the remaining events here, and then try to
5543 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005544
Jim Ingham1460e4b2014-01-10 23:46:59 +00005545 Event *other_events = listener.PeekAtNextEvent();
5546 if (other_events != NULL)
5547 {
5548 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005549 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005550 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005551
Jim Ingham1460e4b2014-01-10 23:46:59 +00005552 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5553 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5554 // event coalescing to cause us to lose OUR running event...
5555 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005556
Jim Ingham8559a352012-11-26 23:52:18 +00005557 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5558 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005559
5560#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5561 // It's pretty much impossible to write test cases for things like:
5562 // One thread timeout expires, I go to halt, but the process already stopped
5563 // on the function call stop breakpoint. Turning on this define will make us not
5564 // fetch the first event till after the halt. So if you run a quick function, it will have
5565 // completed, and the completion event will be waiting, when you interrupt for halt.
5566 // The expression evaluation should still succeed.
5567 bool miss_first_event = true;
5568#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005569 TimeValue one_thread_timeout;
5570 TimeValue final_timeout;
5571
Jim Ingham35878c42014-04-08 21:33:21 +00005572
Sean Callanana46ec452012-07-11 21:31:24 +00005573 while (1)
5574 {
5575 // We usually want to resume the process if we get to the top of the loop.
5576 // The only exception is if we get two running events with no intervening
5577 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005578 if (log)
5579 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5580 do_resume,
5581 handle_running_event,
5582 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005583
Jim Ingham184e9812013-01-15 02:47:48 +00005584 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005585 {
5586 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005587
Jim Ingham184e9812013-01-15 02:47:48 +00005588 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005589 {
Jim Ingham0161b492013-02-09 01:29:05 +00005590 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005591 Error resume_error = PrivateResume ();
5592 if (!resume_error.Success())
5593 {
Jim Ingham0161b492013-02-09 01:29:05 +00005594 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5595 num_resumes,
5596 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005597 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005598 break;
5599 }
Sean Callanana46ec452012-07-11 21:31:24 +00005600 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005601
Jim Ingham0161b492013-02-09 01:29:05 +00005602 TimeValue resume_timeout = TimeValue::Now();
5603 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005604
Jim Ingham0161b492013-02-09 01:29:05 +00005605 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005606 if (!got_event)
5607 {
5608 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005609 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5610 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005611
Jim Ingham0161b492013-02-09 01:29:05 +00005612 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005613 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005614 break;
5615 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005616
Sean Callanana46ec452012-07-11 21:31:24 +00005617 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005618
Sean Callanana46ec452012-07-11 21:31:24 +00005619 if (stop_state != eStateRunning)
5620 {
Jim Ingham0161b492013-02-09 01:29:05 +00005621 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005622
Jim Ingham0161b492013-02-09 01:29:05 +00005623 if (stop_state == eStateStopped)
5624 {
5625 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5626 if (log)
5627 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5628 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5629 num_resumes,
5630 StateAsCString(stop_state),
5631 restarted,
5632 do_resume,
5633 handle_running_event);
5634 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005635
Jim Ingham0161b492013-02-09 01:29:05 +00005636 if (restarted)
5637 {
5638 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5639 // event here. But if I do, the best thing is to Halt and then get out of here.
5640 Halt();
5641 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005642
Jim Ingham35e1bda2012-10-16 21:41:58 +00005643 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5644 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005645 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005646 break;
5647 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005648
Sean Callanana46ec452012-07-11 21:31:24 +00005649 if (log)
5650 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5651 // We need to call the function synchronously, so spin waiting for it to return.
5652 // If we get interrupted while executing, we're going to lose our context, and
5653 // won't be able to gather the result at this point.
5654 // We set the timeout AFTER the resume, since the resume takes some time and we
5655 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005656 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005657 else
5658 {
Sean Callanana46ec452012-07-11 21:31:24 +00005659 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005660 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005661 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005662
Jim Ingham0161b492013-02-09 01:29:05 +00005663 if (before_first_timeout)
5664 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005665 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005666 {
5667 one_thread_timeout = TimeValue::Now();
5668 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005669 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005670 }
Jim Ingham0161b492013-02-09 01:29:05 +00005671 else
5672 {
5673 if (timeout_usec == 0)
5674 timeout_ptr = NULL;
5675 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005676 {
5677 final_timeout = TimeValue::Now();
5678 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005679 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005680 }
Jim Ingham0161b492013-02-09 01:29:05 +00005681 }
5682 }
5683 else
5684 {
5685 if (timeout_usec == 0)
5686 timeout_ptr = NULL;
5687 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005688 {
5689 final_timeout = TimeValue::Now();
5690 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005691 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005692 }
Jim Ingham0161b492013-02-09 01:29:05 +00005693 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005694
Jim Ingham0161b492013-02-09 01:29:05 +00005695 do_resume = true;
5696 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005697
Sean Callanana46ec452012-07-11 21:31:24 +00005698 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005699 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005700
Jim Ingham0f16e732011-02-08 05:20:59 +00005701 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005702 {
Sean Callanana46ec452012-07-11 21:31:24 +00005703 if (timeout_ptr)
5704 {
Matt Kopec676a4872013-02-21 23:55:31 +00005705 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005706 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5707 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005708 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005709 else
Sean Callanana46ec452012-07-11 21:31:24 +00005710 {
5711 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5712 }
5713 }
Jim Ingham35878c42014-04-08 21:33:21 +00005714
5715#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5716 // See comment above...
5717 if (miss_first_event)
5718 {
5719 usleep(1000);
5720 miss_first_event = false;
5721 got_event = false;
5722 }
5723 else
5724#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005725 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005726
Sean Callanana46ec452012-07-11 21:31:24 +00005727 if (got_event)
5728 {
5729 if (event_sp.get())
5730 {
5731 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005732 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005733 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005734 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005735 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005736 errors.Printf ("Execution halted by user interrupt.");
5737 if (log)
5738 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005739 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005740 }
5741 else
5742 {
5743 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5744 if (log)
5745 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005746
Jim Inghamcfc09352012-07-27 23:57:19 +00005747 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005748 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005749 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005750 {
Jim Ingham0161b492013-02-09 01:29:05 +00005751 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005752 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5753 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005754 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005755 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005756 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005757 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005758 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005759 }
5760 else
5761 {
Jim Ingham0161b492013-02-09 01:29:05 +00005762 // If we were restarted, we just need to go back up to fetch another event.
5763 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005764 {
5765 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005766 {
5767 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5768 }
5769 keep_going = true;
5770 do_resume = false;
5771 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005772
Jim Inghamcfc09352012-07-27 23:57:19 +00005773 }
5774 else
5775 {
Jim Ingham0161b492013-02-09 01:29:05 +00005776 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5777 StopReason stop_reason = eStopReasonInvalid;
5778 if (stop_info_sp)
5779 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005780
Jim Ingham0161b492013-02-09 01:29:05 +00005781 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5782 // it is OUR plan that is complete?
5783 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005784 {
5785 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005786 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5787 // Now mark this plan as private so it doesn't get reported as the stop reason
5788 // after this point.
5789 if (thread_plan_sp)
5790 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005791 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005792 }
5793 else
5794 {
Jim Ingham0161b492013-02-09 01:29:05 +00005795 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005796 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005797 {
5798 if (log)
5799 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005800 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005801 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005802 {
5803 event_to_broadcast_sp = event_sp;
5804 }
Jim Ingham0161b492013-02-09 01:29:05 +00005805 }
Jim Ingham184e9812013-01-15 02:47:48 +00005806 else
Jim Ingham0161b492013-02-09 01:29:05 +00005807 {
5808 if (log)
5809 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005810 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005811 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005812 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005813 }
Jim Ingham184e9812013-01-15 02:47:48 +00005814 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005815 }
Sean Callanana46ec452012-07-11 21:31:24 +00005816 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005817 }
5818 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005819
Jim Inghamcfc09352012-07-27 23:57:19 +00005820 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005821 // This shouldn't really happen, but sometimes we do get two running events without an
5822 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005823 do_resume = false;
5824 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005825 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005826 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005827
Jim Inghamcfc09352012-07-27 23:57:19 +00005828 default:
5829 if (log)
5830 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005831
Jim Inghamcfc09352012-07-27 23:57:19 +00005832 if (stop_state == eStateExited)
5833 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005834
Sean Callananbf154da2012-08-08 17:35:10 +00005835 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005836 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005837 break;
5838 }
Sean Callanana46ec452012-07-11 21:31:24 +00005839 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005840
Sean Callanana46ec452012-07-11 21:31:24 +00005841 if (keep_going)
5842 continue;
5843 else
5844 break;
5845 }
5846 else
5847 {
5848 if (log)
5849 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005850 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005851 break;
5852 }
5853 }
5854 else
5855 {
5856 // If we didn't get an event that means we've timed out...
5857 // We will interrupt the process here. Depending on what we were asked to do we will
5858 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005859
Sean Callanana46ec452012-07-11 21:31:24 +00005860 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005861 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005862 {
Jim Ingham0161b492013-02-09 01:29:05 +00005863 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005864 {
5865 if (timeout_usec != 0)
5866 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005867 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005868 "running for %" PRIu32 " usec with all threads enabled.",
5869 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005870 }
5871 else
5872 {
5873 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005874 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005875 }
5876 }
Sean Callanana46ec452012-07-11 21:31:24 +00005877 else
5878 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005879 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005880 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005881 }
5882 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005883 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005884 "abandoning execution.",
5885 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005886 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005887
Jim Ingham0161b492013-02-09 01:29:05 +00005888 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5889 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5890 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5891 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5892 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005893
Jim Ingham0161b492013-02-09 01:29:05 +00005894 bool back_to_top = true;
5895 uint32_t try_halt_again = 0;
5896 bool do_halt = true;
5897 const uint32_t num_retries = 5;
5898 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005899 {
Jim Ingham0161b492013-02-09 01:29:05 +00005900 Error halt_error;
5901 if (do_halt)
5902 {
5903 if (log)
5904 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5905 halt_error = Halt();
5906 }
5907 if (halt_error.Success())
5908 {
5909 if (log)
5910 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005911
Jim Ingham0161b492013-02-09 01:29:05 +00005912 real_timeout = TimeValue::Now();
5913 real_timeout.OffsetWithMicroSeconds(500000);
5914
5915 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005916
Jim Ingham0161b492013-02-09 01:29:05 +00005917 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005918 {
Jim Ingham0161b492013-02-09 01:29:05 +00005919 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5920 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005921 {
Jim Ingham0161b492013-02-09 01:29:05 +00005922 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5923 if (stop_state == lldb::eStateStopped
5924 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5925 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005926 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005927
Jim Ingham0161b492013-02-09 01:29:05 +00005928 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005929 {
Jim Ingham0161b492013-02-09 01:29:05 +00005930 // Between the time we initiated the Halt and the time we delivered it, the process could have
5931 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005932
Jim Ingham0161b492013-02-09 01:29:05 +00005933 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5934 {
5935 if (log)
5936 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5937 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005938 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005939 back_to_top = false;
5940 break;
5941 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005942
Jim Ingham0161b492013-02-09 01:29:05 +00005943 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5944 {
5945 if (log)
5946 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5947 "Exiting wait loop.");
5948 try_halt_again++;
5949 do_halt = false;
5950 continue;
5951 }
Sean Callanana46ec452012-07-11 21:31:24 +00005952
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005953 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005954 {
5955 if (log)
5956 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005957 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005958 back_to_top = false;
5959 break;
5960 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005961
Jim Ingham0161b492013-02-09 01:29:05 +00005962 if (before_first_timeout)
5963 {
5964 // Set all the other threads to run, and return to the top of the loop, which will continue;
5965 before_first_timeout = false;
5966 thread_plan_sp->SetStopOthers (false);
5967 if (log)
5968 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005969
Jim Ingham0161b492013-02-09 01:29:05 +00005970 back_to_top = true;
5971 break;
5972 }
5973 else
5974 {
5975 // Running all threads failed, so return Interrupted.
5976 if (log)
5977 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005978 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005979 back_to_top = false;
5980 break;
5981 }
Sean Callanana46ec452012-07-11 21:31:24 +00005982 }
5983 }
5984 else
Jim Ingham0161b492013-02-09 01:29:05 +00005985 { if (log)
5986 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5987 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005988 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005989 back_to_top = false;
5990 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005991 }
5992 }
Jim Ingham0161b492013-02-09 01:29:05 +00005993 else
5994 {
5995 try_halt_again++;
5996 continue;
5997 }
Sean Callanana46ec452012-07-11 21:31:24 +00005998 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005999
Jim Ingham0161b492013-02-09 01:29:05 +00006000 if (!back_to_top || try_halt_again > num_retries)
6001 break;
6002 else
6003 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006004 }
Sean Callanana46ec452012-07-11 21:31:24 +00006005 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006006
Sean Callanana46ec452012-07-11 21:31:24 +00006007 // 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 +00006008 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006009 {
6010 StopPrivateStateThread();
6011 Error error;
6012 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006013 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006014 {
6015 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6016 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006017 if (old_state != eStateInvalid)
6018 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006019 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006020
Jim Ingham184e9812013-01-15 02:47:48 +00006021 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6022 // could happen:
6023 // 1) The execution successfully completed
6024 // 2) We hit a breakpoint, and ignore_breakpoints was true
6025 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006026 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6027 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006028
Jim Ingham8646d3c2014-05-05 02:47:44 +00006029 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006030 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006031 {
6032 thread_plan_sp->RestoreThreadState();
6033 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006034
Sean Callanana46ec452012-07-11 21:31:24 +00006035 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006036 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006037 {
6038 if (log)
6039 {
6040 StreamString s;
6041 if (event_sp)
6042 event_sp->Dump (&s);
6043 else
6044 {
6045 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6046 }
6047
6048 StreamString ts;
6049
6050 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006051
Sean Callanana46ec452012-07-11 21:31:24 +00006052 do
6053 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006054 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006055 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006056 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006057 break;
6058 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006059 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006060 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006061 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006062 break;
6063 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006064 else
Sean Callanana46ec452012-07-11 21:31:24 +00006065 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006066 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6067
6068 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006069 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006070 event_explanation = "<no event data>";
6071 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006072 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006073
Jim Inghamcfc09352012-07-27 23:57:19 +00006074 Process *process = event_data->GetProcessSP().get();
6075
6076 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006077 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006078 event_explanation = "<no process>";
6079 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006080 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006081
Jim Inghamcfc09352012-07-27 23:57:19 +00006082 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006083
Jim Inghamcfc09352012-07-27 23:57:19 +00006084 uint32_t num_threads = thread_list.GetSize();
6085 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006086
Jim Inghamcfc09352012-07-27 23:57:19 +00006087 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006088
Jim Inghamcfc09352012-07-27 23:57:19 +00006089 for (thread_index = 0;
6090 thread_index < num_threads;
6091 ++thread_index)
6092 {
6093 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006094
Jim Inghamcfc09352012-07-27 23:57:19 +00006095 if (!thread)
6096 {
6097 ts.Printf("<?> ");
6098 continue;
6099 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006100
Daniel Malead01b2952012-11-29 21:49:15 +00006101 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006102 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006103
Jim Inghamcfc09352012-07-27 23:57:19 +00006104 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006105 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006106 else
6107 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006108
Jim Inghamcfc09352012-07-27 23:57:19 +00006109 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6110 if (stop_info_sp)
6111 {
6112 const char *stop_desc = stop_info_sp->GetDescription();
6113 if (stop_desc)
6114 ts.PutCString (stop_desc);
6115 }
6116 ts.Printf(">");
6117 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006118
Jim Inghamcfc09352012-07-27 23:57:19 +00006119 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006120 }
Sean Callanana46ec452012-07-11 21:31:24 +00006121 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006122
Jim Inghamcfc09352012-07-27 23:57:19 +00006123 if (event_explanation)
6124 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006125 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006126 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6127 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006128
Jim Inghame4483cf2013-09-27 01:13:01 +00006129 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006130 {
6131 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006132 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6133 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006134 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6135 thread_plan_sp->SetPrivate (orig_plan_private);
6136 }
6137 else
6138 {
6139 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006140 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6141 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006142 }
6143 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006144 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006145 {
6146 if (log)
6147 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006148
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006149 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006150 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006151 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006152 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006153 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006154 }
6155 else
6156 {
Sean Callanana46ec452012-07-11 21:31:24 +00006157 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006158 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006159 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006160 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006161 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006162 }
6163 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6164 {
6165 if (log)
6166 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006167 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006168 }
6169 else
6170 {
6171 if (log)
6172 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006173 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006174 {
6175 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006176 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006177 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6178 thread_plan_sp->SetPrivate (orig_plan_private);
6179 }
6180 }
6181 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006182
Sean Callanana46ec452012-07-11 21:31:24 +00006183 // Thread we ran the function in may have gone away because we ran the target
6184 // Check that it's still there, and if it is put it back in the context. Also restore the
6185 // frame in the context if it is still present.
6186 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6187 if (thread)
6188 {
6189 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6190 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006191
Sean Callanana46ec452012-07-11 21:31:24 +00006192 // Also restore the current process'es selected frame & thread, since this function calling may
6193 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006194
Sean Callanana46ec452012-07-11 21:31:24 +00006195 if (selected_tid != LLDB_INVALID_THREAD_ID)
6196 {
6197 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6198 {
6199 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006200 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006201 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006202 if (old_frame_sp)
6203 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006204 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006205 }
6206 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006207
Sean Callanana46ec452012-07-11 21:31:24 +00006208 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006209
Sean Callanana46ec452012-07-11 21:31:24 +00006210 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006211 {
Sean Callanana46ec452012-07-11 21:31:24 +00006212 if (log)
6213 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6214 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006215 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006216
Jim Inghamf48169b2010-11-30 02:22:11 +00006217 return return_value;
6218}
6219
6220const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006221Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006222{
6223 const char *result_name;
6224
6225 switch (result)
6226 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006227 case eExpressionCompleted:
6228 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006229 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006230 case eExpressionDiscarded:
6231 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006232 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006233 case eExpressionInterrupted:
6234 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006235 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006236 case eExpressionHitBreakpoint:
6237 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006238 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006239 case eExpressionSetupError:
6240 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006241 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006242 case eExpressionParseError:
6243 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006244 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006245 case eExpressionResultUnavailable:
6246 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006247 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006248 case eExpressionTimedOut:
6249 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006250 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006251 case eExpressionStoppedForDebug:
6252 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006253 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006254 }
6255 return result_name;
6256}
6257
Greg Clayton7260f622011-04-18 08:33:37 +00006258void
6259Process::GetStatus (Stream &strm)
6260{
6261 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006262 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006263 {
6264 if (state == eStateExited)
6265 {
6266 int exit_status = GetExitStatus();
6267 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006268 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006269 GetID(),
6270 exit_status,
6271 exit_status,
6272 exit_description ? exit_description : "");
6273 }
6274 else
6275 {
6276 if (state == eStateConnected)
6277 strm.Printf ("Connected to remote target.\n");
6278 else
Daniel Malead01b2952012-11-29 21:49:15 +00006279 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006280 }
6281 }
6282 else
6283 {
Daniel Malead01b2952012-11-29 21:49:15 +00006284 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006285 }
6286}
6287
6288size_t
6289Process::GetThreadStatus (Stream &strm,
6290 bool only_threads_with_stop_reason,
6291 uint32_t start_frame,
6292 uint32_t num_frames,
6293 uint32_t num_frames_with_source)
6294{
6295 size_t num_thread_infos_dumped = 0;
6296
Jim Ingham4a65fb12014-03-07 11:20:03 +00006297 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6298 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6299 // ID's, and look them up one by one:
6300
6301 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006302 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006303 //Scope for thread list locker;
6304 {
6305 Mutex::Locker locker (GetThreadList().GetMutex());
6306 ThreadList &curr_thread_list = GetThreadList();
6307 num_threads = curr_thread_list.GetSize();
6308 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006309 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006310 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006311 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006312 }
6313
Greg Clayton7260f622011-04-18 08:33:37 +00006314 for (uint32_t i = 0; i < num_threads; i++)
6315 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006316 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006317 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006318 {
6319 if (only_threads_with_stop_reason)
6320 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006321 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006322 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006323 continue;
6324 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006325 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006326 start_frame,
6327 num_frames,
6328 num_frames_with_source);
6329 ++num_thread_infos_dumped;
6330 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006331 else
6332 {
6333 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6334 if (log)
6335 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6336
6337 }
Greg Clayton7260f622011-04-18 08:33:37 +00006338 }
6339 return num_thread_infos_dumped;
6340}
6341
Greg Claytona9f40ad2012-02-22 04:37:26 +00006342void
6343Process::AddInvalidMemoryRegion (const LoadRange &region)
6344{
6345 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6346}
6347
6348bool
6349Process::RemoveInvalidMemoryRange (const LoadRange &region)
6350{
6351 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6352}
6353
Jim Ingham372787f2012-04-07 00:00:41 +00006354void
6355Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6356{
6357 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6358}
6359
6360bool
6361Process::RunPreResumeActions ()
6362{
6363 bool result = true;
6364 while (!m_pre_resume_actions.empty())
6365 {
6366 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6367 m_pre_resume_actions.pop_back();
6368 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006369 if (result == true)
6370 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006371 }
6372 return result;
6373}
6374
6375void
6376Process::ClearPreResumeActions ()
6377{
6378 m_pre_resume_actions.clear();
6379}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006380
Zachary Turner93749ab2015-03-03 21:51:25 +00006381ProcessRunLock &
6382Process::GetRunLock()
6383{
6384 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6385 return m_private_run_lock;
6386 else
6387 return m_public_run_lock;
6388}
6389
Greg Claytonfa559e52012-05-18 02:38:05 +00006390void
6391Process::Flush ()
6392{
6393 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006394 m_extended_thread_list.Flush();
6395 m_extended_thread_stop_id = 0;
6396 m_queue_list.Clear();
6397 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006398}
Greg Clayton90ba8112012-12-05 00:16:59 +00006399
6400void
6401Process::DidExec ()
6402{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006403 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6404 if (log)
6405 log->Printf ("Process::%s()", __FUNCTION__);
6406
Greg Clayton90ba8112012-12-05 00:16:59 +00006407 Target &target = GetTarget();
6408 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006409 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006410 m_dynamic_checkers_ap.reset();
6411 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006412 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006413 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006414 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006415 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006416 m_image_tokens.clear();
6417 m_allocated_memory_cache.Clear();
6418 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006419 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006420 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006421 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006422 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006423 DoDidExec();
6424 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006425 // Flush the process (threads and all stack frames) after running CompleteAttach()
6426 // in case the dynamic loader loaded things in new locations.
6427 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006428
6429 // After we figure out what was loaded/unloaded in CompleteAttach,
6430 // we need to let the target know so it can do any cleanup it needs to.
6431 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006432}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006433
Jim Ingham1460e4b2014-01-10 23:46:59 +00006434addr_t
6435Process::ResolveIndirectFunction(const Address *address, Error &error)
6436{
6437 if (address == nullptr)
6438 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006439 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006440 return LLDB_INVALID_ADDRESS;
6441 }
6442
6443 addr_t function_addr = LLDB_INVALID_ADDRESS;
6444
6445 addr_t addr = address->GetLoadAddress(&GetTarget());
6446 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6447 if (iter != m_resolved_indirect_addresses.end())
6448 {
6449 function_addr = (*iter).second;
6450 }
6451 else
6452 {
6453 if (!InferiorCall(this, address, function_addr))
6454 {
6455 Symbol *symbol = address->CalculateSymbolContextSymbol();
6456 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6457 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6458 function_addr = LLDB_INVALID_ADDRESS;
6459 }
6460 else
6461 {
6462 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6463 }
6464 }
6465 return function_addr;
6466}
6467
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006468void
6469Process::ModulesDidLoad (ModuleList &module_list)
6470{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006471 SystemRuntime *sys_runtime = GetSystemRuntime();
6472 if (sys_runtime)
6473 {
6474 sys_runtime->ModulesDidLoad (module_list);
6475 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006476
Kuba Breckaafdf8422014-10-10 23:43:03 +00006477 GetJITLoaders().ModulesDidLoad (module_list);
6478
6479 // Give runtimes a chance to be created.
6480 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6481
6482 // Tell runtimes about new modules.
6483 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6484 {
6485 InstrumentationRuntimeSP runtime = pos->second;
6486 runtime->ModulesDidLoad(module_list);
6487 }
6488
Greg Clayton35ca64b2015-04-16 17:13:34 +00006489 // Let any language runtimes we have already created know
6490 // about the modules that loaded.
6491
6492 // Iterate over a copy of this language runtime list in case
6493 // the language runtime ModulesDidLoad somehow causes the language
6494 // riuntime to be unloaded.
6495 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6496 for (const auto &pair: language_runtimes)
6497 {
6498 // We must check language_runtime_sp to make sure it is not
6499 // NULL as we might cache the fact that we didn't have a
6500 // language runtime for a language.
6501 LanguageRuntimeSP language_runtime_sp = pair.second;
6502 if (language_runtime_sp)
6503 language_runtime_sp->ModulesDidLoad(module_list);
6504 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006505}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006506
6507ThreadCollectionSP
6508Process::GetHistoryThreads(lldb::addr_t addr)
6509{
6510 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006511
Kuba Breckaa51ea382014-09-06 01:33:13 +00006512 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6513
6514 if (! memory_history.get()) {
6515 return threads;
6516 }
6517
6518 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6519
6520 return threads;
6521}
Kuba Brecka63927542014-10-11 01:59:32 +00006522
6523InstrumentationRuntimeSP
6524Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6525{
6526 InstrumentationRuntimeCollection::iterator pos;
6527 pos = m_instrumentation_runtimes.find (type);
6528 if (pos == m_instrumentation_runtimes.end())
6529 {
6530 return InstrumentationRuntimeSP();
6531 }
6532 else
6533 return (*pos).second;
6534}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006535
6536bool
6537Process::GetModuleSpec(const FileSpec& module_file_spec,
6538 const ArchSpec& arch,
6539 ModuleSpec& module_spec)
6540{
6541 module_spec.Clear();
6542 return false;
6543}