blob: 77e9b5dbc0ab22cb9c7e6fdcdb223b49a4a2ec35 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include "lldb/Breakpoint/StoppointCallbackContext.h"
12#include "lldb/Breakpoint/BreakpointLocation.h"
13#include "lldb/Core/Event.h"
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000016#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000017#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000020#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000021#include "lldb/Expression/ClangUserExpression.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000022#include "lldb/Expression/IRDynamicChecks.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000023#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000025#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000026#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000027#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000029#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000030#include "lldb/Interpreter/OptionValueProperties.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000031#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000033#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000034#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000035#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000036#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000037#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000039#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000040#include "lldb/Target/LanguageRuntime.h"
41#include "lldb/Target/CPPLanguageRuntime.h"
42#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000043#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000045#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000046#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Target/Target.h"
48#include "lldb/Target/TargetList.h"
49#include "lldb/Target/Thread.h"
50#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000051#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000052#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000053#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000054#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055
56using namespace lldb;
57using namespace lldb_private;
58
Greg Clayton67cc0632012-08-22 17:17:09 +000059
60// Comment out line below to disable memory caching, overriding the process setting
61// target.process.disable-memory-cache
62#define ENABLE_MEMORY_CACHING
63
64#ifdef ENABLE_MEMORY_CACHING
65#define DISABLE_MEM_CACHE_DEFAULT false
66#else
67#define DISABLE_MEM_CACHE_DEFAULT true
68#endif
69
70class ProcessOptionValueProperties : public OptionValueProperties
71{
72public:
73 ProcessOptionValueProperties (const ConstString &name) :
74 OptionValueProperties (name)
75 {
76 }
77
78 // This constructor is used when creating ProcessOptionValueProperties when it
79 // is part of a new lldb_private::Process instance. It will copy all current
80 // global property values as needed
81 ProcessOptionValueProperties (ProcessProperties *global_properties) :
82 OptionValueProperties(*global_properties->GetValueProperties())
83 {
84 }
85
86 virtual const Property *
87 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
88 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000089 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000090 // try and grab the setting from the current process if there is one. Else we just
91 // use the one from this instance.
92 if (exe_ctx)
93 {
94 Process *process = exe_ctx->GetProcessPtr();
95 if (process)
96 {
97 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
98 if (this != instance_properties)
99 return instance_properties->ProtectedGetPropertyAtIndex (idx);
100 }
101 }
102 return ProtectedGetPropertyAtIndex (idx);
103 }
104};
105
106static PropertyDefinition
107g_properties[] =
108{
109 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Ingham8c3f2762012-11-29 00:41:12 +0000110 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
111 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000112 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
113 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Claytone1e835c2012-11-29 18:48:47 +0000114 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham29950772013-01-26 02:19:28 +0000115 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Jim Inghamacff8952013-05-02 00:27:30 +0000116 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Jason Molendaf0340c92014-09-03 22:30:54 +0000117 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Greg Clayton67cc0632012-08-22 17:17:09 +0000118 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
119};
120
121enum {
122 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000123 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000124 ePropertyIgnoreBreakpointsInExpressions,
125 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000126 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000127 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000128 ePropertyDetachKeepsStopped,
129 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09 +0000130};
131
Greg Clayton332e8b12015-01-13 21:13:08 +0000132ProcessProperties::ProcessProperties (lldb_private::Process *process) :
133 Properties (),
134 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000135{
Greg Clayton332e8b12015-01-13 21:13:08 +0000136 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000137 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000138 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000139 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
140 m_collection_sp->Initialize(g_properties);
141 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000142 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000143 true,
144 Thread::GetGlobalProperties()->GetValueProperties());
145 }
146 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000147 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000148 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000149 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
150 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000151}
152
153ProcessProperties::~ProcessProperties()
154{
155}
156
Greg Clayton332e8b12015-01-13 21:13:08 +0000157void
158ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
159{
160 ProcessProperties *properties = (ProcessProperties *)baton;
161 if (properties->m_process)
162 properties->m_process->LoadOperatingSystemPlugin(true);
163}
164
Greg Clayton67cc0632012-08-22 17:17:09 +0000165bool
166ProcessProperties::GetDisableMemoryCache() const
167{
168 const uint32_t idx = ePropertyDisableMemCache;
169 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
170}
171
Jason Molendaf0340c92014-09-03 22:30:54 +0000172uint64_t
173ProcessProperties::GetMemoryCacheLineSize() const
174{
175 const uint32_t idx = ePropertyMemCacheLineSize;
176 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
177}
178
Greg Clayton67cc0632012-08-22 17:17:09 +0000179Args
180ProcessProperties::GetExtraStartupCommands () const
181{
182 Args args;
183 const uint32_t idx = ePropertyExtraStartCommand;
184 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
185 return args;
186}
187
188void
189ProcessProperties::SetExtraStartupCommands (const Args &args)
190{
191 const uint32_t idx = ePropertyExtraStartCommand;
192 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
193}
194
Greg Claytonc9d645d2012-10-18 22:40:37 +0000195FileSpec
196ProcessProperties::GetPythonOSPluginPath () const
197{
198 const uint32_t idx = ePropertyPythonOSPluginPath;
199 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
200}
201
202void
203ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
204{
205 const uint32_t idx = ePropertyPythonOSPluginPath;
206 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
207}
208
Jim Ingham184e9812013-01-15 02:47:48 +0000209
210bool
211ProcessProperties::GetIgnoreBreakpointsInExpressions () const
212{
213 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
214 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
215}
216
217void
218ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
219{
220 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
221 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
222}
223
224bool
225ProcessProperties::GetUnwindOnErrorInExpressions () const
226{
227 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
228 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
229}
230
231void
232ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
233{
234 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
235 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
236}
237
Jim Ingham29950772013-01-26 02:19:28 +0000238bool
239ProcessProperties::GetStopOnSharedLibraryEvents () const
240{
241 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
243}
244
245void
246ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
247{
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
249 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
250}
251
Jim Inghamacff8952013-05-02 00:27:30 +0000252bool
253ProcessProperties::GetDetachKeepsStopped () const
254{
255 const uint32_t idx = ePropertyDetachKeepsStopped;
256 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
257}
258
259void
260ProcessProperties::SetDetachKeepsStopped (bool stop)
261{
262 const uint32_t idx = ePropertyDetachKeepsStopped;
263 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
264}
265
Greg Clayton32e0a752011-03-30 18:16:51 +0000266void
Greg Clayton8b82f082011-04-12 05:54:46 +0000267ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000268{
269 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000270 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000271 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000272
273 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000274 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000275
276 if (m_executable)
277 {
278 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
279 s.PutCString (" file = ");
280 m_executable.Dump(&s);
281 s.EOL();
282 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000284 if (argc > 0)
285 {
286 for (uint32_t i=0; i<argc; i++)
287 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000289 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 }
294 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000295
296 const uint32_t envc = m_environment.GetArgumentCount();
297 if (envc > 0)
298 {
299 for (uint32_t i=0; i<envc; i++)
300 {
301 const char *env = m_environment.GetArgumentAtIndex(i);
302 if (i < 10)
303 s.Printf (" env[%u] = %s\n", i, env);
304 else
305 s.Printf ("env[%u] = %s\n", i, env);
306 }
307 }
308
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000309 if (m_arch.IsValid())
310 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
311
Greg Clayton8b82f082011-04-12 05:54:46 +0000312 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000313 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000314 cstr = platform->GetUserName (m_uid);
315 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000316 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000317 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000318 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000319 cstr = platform->GetGroupName (m_gid);
320 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000321 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000322 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000323 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000324 cstr = platform->GetUserName (m_euid);
325 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000326 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000327 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000328 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000329 cstr = platform->GetGroupName (m_egid);
330 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000331 }
332}
333
334void
Greg Clayton8b82f082011-04-12 05:54:46 +0000335ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000336{
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 const char *label;
338 if (show_args || verbose)
339 label = "ARGUMENTS";
340 else
341 label = "NAME";
342
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000343 if (verbose)
344 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000345 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000346 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
347 }
348 else
349 {
Jim Ingham368ac222014-08-15 17:05:27 +0000350 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
351 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000352 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000353}
354
355void
Greg Clayton8b82f082011-04-12 05:54:46 +0000356ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000357{
358 if (m_pid != LLDB_INVALID_PROCESS_ID)
359 {
360 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000361 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000362
Greg Clayton32e0a752011-03-30 18:16:51 +0000363
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000364 if (verbose)
365 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000366 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000367 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
368 s.Printf ("%-10s ", cstr);
369 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000371
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
374 s.Printf ("%-10s ", cstr);
375 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000376 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000377
Greg Clayton8b82f082011-04-12 05:54:46 +0000378 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000379 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
380 s.Printf ("%-10s ", cstr);
381 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000382 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383
Greg Clayton8b82f082011-04-12 05:54:46 +0000384 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000385 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
386 s.Printf ("%-10s ", cstr);
387 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000388 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000389 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
390 }
391 else
392 {
Jim Ingham368ac222014-08-15 17:05:27 +0000393 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000394 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000395 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000396 }
397
Greg Clayton8b82f082011-04-12 05:54:46 +0000398 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000399 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000400 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000401 if (argc > 0)
402 {
403 for (uint32_t i=0; i<argc; i++)
404 {
405 if (i > 0)
406 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000407 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000408 }
409 }
410 }
411 else
412 {
413 s.PutCString (GetName());
414 }
415
416 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000417 }
418}
419
Greg Clayton8b82f082011-04-12 05:54:46 +0000420Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000421ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000422{
423 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000424 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000425
426 switch (short_option)
427 {
428 case 's': // Stop at program entry point
429 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
430 break;
431
Greg Clayton8b82f082011-04-12 05:54:46 +0000432 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000433 {
434 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000435 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000436 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000437 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000438 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000439
440 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000441 {
442 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000443 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000444 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000445 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000446 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000447
448 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000449 {
450 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000451 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000452 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000453 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000454 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000455
Greg Clayton8b82f082011-04-12 05:54:46 +0000456 case 'p': // Process plug-in name
457 launch_info.SetProcessPluginName (option_arg);
458 break;
459
460 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000461 {
462 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000463 const FileSpec dev_null{"/dev/null", false};
464 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000465 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000466 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000467 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000468 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000469 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000470 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000471 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000472
473 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000474 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 break;
476
477 case 't': // Open process in new terminal window
478 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
479 break;
480
481 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000482 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
483 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000484 break;
485
Todd Fiala51637922014-08-19 17:40:43 +0000486 case 'A': // Disable ASLR.
487 {
488 bool success;
489 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
490 if (success)
491 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
492 else
493 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 break;
Todd Fiala51637922014-08-19 17:40:43 +0000495 }
496
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000497 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000498 {
499 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000500 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000501 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000502 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000503 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000504 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000505 break;
506 }
507
Todd Fiala51637922014-08-19 17:40:43 +0000508 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000509 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000510 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000511 else
Zachary Turner10687b02014-10-20 17:46:43 +0000512 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000513 break;
514
Greg Clayton8b82f082011-04-12 05:54:46 +0000515 case 'v':
516 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
517 break;
518
519 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000520 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000521 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000522 }
523 return error;
524}
525
526OptionDefinition
527ProcessLaunchCommandOptions::g_option_table[] =
528{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000529{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
Todd Fiala51637922014-08-19 17:40:43 +0000530{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000531{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
532{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
533{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
534{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Enrico Granatad7a83a92015-02-10 03:06:24 +0000535{ LLDB_OPT_SET_1|LLDB_OPT_SET_2|LLDB_OPT_SET_3, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000536
Zachary Turnerd37221d2014-07-09 16:31:49 +0000537{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
538{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
539{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000540
Zachary Turnerd37221d2014-07-09 16:31:49 +0000541{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000542
Zachary Turnerd37221d2014-07-09 16:31:49 +0000543{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000544{ LLDB_OPT_SET_4, false, "shell-expand-args", 'X', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to shell expand arguments to the process when launching."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000545{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000546};
547
548
549
550bool
551ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000552{
553 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
554 return true;
555 const char *match_name = m_match_info.GetName();
556 if (!match_name)
557 return true;
558
559 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
560}
561
562bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000563ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000564{
565 if (!NameMatches (proc_info.GetName()))
566 return false;
567
568 if (m_match_info.ProcessIDIsValid() &&
569 m_match_info.GetProcessID() != proc_info.GetProcessID())
570 return false;
571
572 if (m_match_info.ParentProcessIDIsValid() &&
573 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
574 return false;
575
Greg Clayton8b82f082011-04-12 05:54:46 +0000576 if (m_match_info.UserIDIsValid () &&
577 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000578 return false;
579
Greg Clayton8b82f082011-04-12 05:54:46 +0000580 if (m_match_info.GroupIDIsValid () &&
581 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000582 return false;
583
584 if (m_match_info.EffectiveUserIDIsValid () &&
585 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
586 return false;
587
588 if (m_match_info.EffectiveGroupIDIsValid () &&
589 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
590 return false;
591
592 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000593 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000594 return false;
595 return true;
596}
597
598bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000599ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000600{
601 if (m_name_match_type != eNameMatchIgnore)
602 return false;
603
604 if (m_match_info.ProcessIDIsValid())
605 return false;
606
607 if (m_match_info.ParentProcessIDIsValid())
608 return false;
609
Greg Clayton8b82f082011-04-12 05:54:46 +0000610 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000611 return false;
612
Greg Clayton8b82f082011-04-12 05:54:46 +0000613 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000614 return false;
615
616 if (m_match_info.EffectiveUserIDIsValid ())
617 return false;
618
619 if (m_match_info.EffectiveGroupIDIsValid ())
620 return false;
621
622 if (m_match_info.GetArchitecture().IsValid())
623 return false;
624
625 if (m_match_all_users)
626 return false;
627
628 return true;
629
630}
631
632void
Greg Clayton8b82f082011-04-12 05:54:46 +0000633ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000634{
635 m_match_info.Clear();
636 m_name_match_type = eNameMatchIgnore;
637 m_match_all_users = false;
638}
Greg Clayton58be07b2011-01-07 06:08:19 +0000639
Greg Claytonc3776bf2012-02-09 06:16:32 +0000640ProcessSP
641Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000642{
Greg Clayton949e8222013-01-16 17:29:04 +0000643 static uint32_t g_process_unique_id = 0;
644
Greg Claytonc3776bf2012-02-09 06:16:32 +0000645 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 ProcessCreateInstance create_callback = NULL;
647 if (plugin_name)
648 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000649 ConstString const_plugin_name(plugin_name);
650 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651 if (create_callback)
652 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000653 process_sp = create_callback(target, listener, crash_file_path);
654 if (process_sp)
655 {
Greg Clayton949e8222013-01-16 17:29:04 +0000656 if (process_sp->CanDebug(target, true))
657 {
658 process_sp->m_process_unique_id = ++g_process_unique_id;
659 }
660 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000661 process_sp.reset();
662 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 }
664 }
665 else
666 {
Greg Claytonc982c762010-07-09 20:39:50 +0000667 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000668 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000669 process_sp = create_callback(target, listener, crash_file_path);
670 if (process_sp)
671 {
Greg Clayton949e8222013-01-16 17:29:04 +0000672 if (process_sp->CanDebug(target, false))
673 {
674 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000675 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000676 }
677 else
678 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000679 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 }
681 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000682 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683}
684
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000685ConstString &
686Process::GetStaticBroadcasterClass ()
687{
688 static ConstString class_name ("lldb.process");
689 return class_name;
690}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691
692//----------------------------------------------------------------------
693// Process constructor
694//----------------------------------------------------------------------
695Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000696 Process(target, listener, Host::GetUnixSignals ())
697{
698 // This constructor just delegates to the full Process constructor,
699 // defaulting to using the Host's UnixSignals.
700}
701
702Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000703 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 UserID (LLDB_INVALID_PROCESS_ID),
Ilia K8a00a562015-03-17 16:54:52 +0000705 Broadcaster (&(target.GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000706 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000707 m_public_state (eStateUnloaded),
708 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000709 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
710 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000711 m_private_state_listener ("lldb.process.internal_state_listener"),
712 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000713 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000714 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000716 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717 m_exit_status (-1),
718 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000719 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000720 m_thread_mutex (Mutex::eMutexTypeRecursive),
721 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000722 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000723 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000724 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000725 m_queue_list (this),
726 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000728 m_image_tokens (),
729 m_listener (listener),
730 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000731 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000732 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000733 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000734 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000735 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000736 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000737 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000738 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000739 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000740 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
741 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32 +0000742 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42 +0000743 m_memory_cache (*this),
744 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000745 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000746 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000747 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000748 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000749 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000750 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58 +0000751 m_finalizing (false),
752 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000753 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000754 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000755 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000756 m_destroy_in_process (false),
757 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000759 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000760
Greg Clayton5160ce52013-03-27 23:08:40 +0000761 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000763 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764
Todd Fiala4ceced32014-08-29 17:35:57 +0000765 if (!m_unix_signals_sp)
766 m_unix_signals_sp.reset (new UnixSignals ());
767
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000768 SetEventName (eBroadcastBitStateChanged, "state-changed");
769 SetEventName (eBroadcastBitInterrupt, "interrupt");
770 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
771 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000772 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000773
Greg Clayton35a4cc52012-10-29 20:52:08 +0000774 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
775 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
776 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
777
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778 listener.StartListeningForEvents (this,
779 eBroadcastBitStateChanged |
780 eBroadcastBitInterrupt |
781 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000782 eBroadcastBitSTDERR |
783 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784
785 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000786 eBroadcastBitStateChanged |
787 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788
789 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
790 eBroadcastInternalStateControlStop |
791 eBroadcastInternalStateControlPause |
792 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000793 // We need something valid here, even if just the default UnixSignalsSP.
794 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795}
796
797//----------------------------------------------------------------------
798// Destructor
799//----------------------------------------------------------------------
800Process::~Process()
801{
Greg Clayton5160ce52013-03-27 23:08:40 +0000802 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000804 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000806
807 // ThreadList::Clear() will try to acquire this process's mutex, so
808 // explicitly clear the thread list here to ensure that the mutex
809 // is not destroyed before the thread list.
810 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000811}
812
Greg Clayton67cc0632012-08-22 17:17:09 +0000813const ProcessPropertiesSP &
814Process::GetGlobalProperties()
815{
816 static ProcessPropertiesSP g_settings_sp;
817 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000818 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000819 return g_settings_sp;
820}
821
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822void
823Process::Finalize()
824{
Greg Claytonc00ca312015-04-02 18:44:58 +0000825 m_finalizing = true;
826
Ilia Kc7efd562015-03-26 07:40:40 +0000827 // Destroy this process if needed
828 switch (GetPrivateState())
829 {
830 case eStateConnected:
831 case eStateAttaching:
832 case eStateLaunching:
833 case eStateStopped:
834 case eStateRunning:
835 case eStateStepping:
836 case eStateCrashed:
837 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000838 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000839 break;
840
841 case eStateInvalid:
842 case eStateUnloaded:
843 case eStateDetached:
844 case eStateExited:
845 break;
846 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000847
Greg Clayton1ed54f52011-10-01 00:45:15 +0000848 // Clear our broadcaster before we proceed with destroying
849 Broadcaster::Clear();
850
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851 // Do any cleanup needed prior to being destructed... Subclasses
852 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000853
854 // We need to destroy the loader before the derived Process class gets destroyed
855 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000856 m_dynamic_checkers_ap.reset();
857 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000858 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000859 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000860 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000861 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000862 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000863 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000864 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000865 m_queue_list.Clear();
866 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000867 std::vector<Notifications> empty_notifications;
868 m_notifications.swap(empty_notifications);
869 m_image_tokens.clear();
870 m_memory_cache.Clear();
871 m_allocated_memory_cache.Clear();
872 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000873 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000874 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000875 m_stop_info_override_callback = NULL;
Greg Clayton08765fa2015-05-28 03:24:30 +0000876 // Clear the last natural stop ID since it has a strong
877 // reference to this process
878 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000879//#ifdef LLDB_CONFIGURATION_DEBUG
880// StreamFile s(stdout, false);
881// EventSP event_sp;
882// while (m_private_state_listener.GetNextEvent(event_sp))
883// {
884// event_sp->Dump (&s);
885// s.EOL();
886// }
887//#endif
888 // We have to be very careful here as the m_private_state_listener might
889 // contain events that have ProcessSP values in them which can keep this
890 // process around forever. These events need to be cleared out.
891 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000892 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
893 m_public_run_lock.SetStopped();
894 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
895 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000896 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897}
898
899void
900Process::RegisterNotificationCallbacks (const Notifications& callbacks)
901{
902 m_notifications.push_back(callbacks);
903 if (callbacks.initialize != NULL)
904 callbacks.initialize (callbacks.baton, this);
905}
906
907bool
908Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
909{
910 std::vector<Notifications>::iterator pos, end = m_notifications.end();
911 for (pos = m_notifications.begin(); pos != end; ++pos)
912 {
913 if (pos->baton == callbacks.baton &&
914 pos->initialize == callbacks.initialize &&
915 pos->process_state_changed == callbacks.process_state_changed)
916 {
917 m_notifications.erase(pos);
918 return true;
919 }
920 }
921 return false;
922}
923
924void
925Process::SynchronouslyNotifyStateChanged (StateType state)
926{
927 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
928 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
929 {
930 if (notification_pos->process_state_changed)
931 notification_pos->process_state_changed (notification_pos->baton, this, state);
932 }
933}
934
935// FIXME: We need to do some work on events before the general Listener sees them.
936// For instance if we are continuing from a breakpoint, we need to ensure that we do
937// the little "insert real insn, step & stop" trick. But we can't do that when the
938// event is delivered by the broadcaster - since that is done on the thread that is
939// waiting for new events, so if we needed more than one event for our handling, we would
940// stall. So instead we do it when we fetch the event off of the queue.
941//
942
943StateType
944Process::GetNextEvent (EventSP &event_sp)
945{
946 StateType state = eStateInvalid;
947
948 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
949 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
950
951 return state;
952}
953
Pavel Labath44464872015-05-27 12:40:32 +0000954void
955Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000956{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000957 // don't sync (potentially context switch) in case where there is no process IO
Pavel Labath44464872015-05-27 12:40:32 +0000958 if (! m_process_input_reader)
959 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000960
Pavel Labath44464872015-05-27 12:40:32 +0000961 TimeValue timeout = TimeValue::Now();
962 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
963 uint32_t new_iohandler_id = 0;
964 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000965
Pavel Labath44464872015-05-27 12:40:32 +0000966 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
967 if (log)
968 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, new value is %u", __FUNCTION__, iohandler_id, new_iohandler_id);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000969}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970
971StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000972Process::WaitForProcessToStop (const TimeValue *timeout,
973 EventSP *event_sp_ptr,
974 bool wait_always,
975 Listener *hijack_listener,
976 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000977{
Jim Ingham4b536182011-08-09 02:12:22 +0000978 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
979 // We have to actually check each event, and in the case of a stopped event check the restarted flag
980 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000981 if (event_sp_ptr)
982 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000983 StateType state = GetState();
984 // If we are exited or detached, we won't ever get back to any
985 // other valid state...
986 if (state == eStateDetached || state == eStateExited)
987 return state;
988
Daniel Malea9e9919f2013-10-09 16:56:28 +0000989 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
990 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000991 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
992 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000993
994 if (!wait_always &&
995 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +0000996 StateIsStoppedState(GetPrivateState(), true))
997 {
Daniel Malea9e9919f2013-10-09 16:56:28 +0000998 if (log)
999 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1000 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001001 // We need to toggle the run lock as this won't get done in
1002 // SetPublicState() if the process is hijacked.
1003 if (hijack_listener)
1004 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001005 return state;
1006 }
1007
Jim Ingham4b536182011-08-09 02:12:22 +00001008 while (state != eStateInvalid)
1009 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001010 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001011 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001012 if (event_sp_ptr && event_sp)
1013 *event_sp_ptr = event_sp;
1014
Greg Claytondc6224e2014-10-21 01:00:42 +00001015 bool pop_process_io_handler = hijack_listener != NULL;
1016 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1017
Jim Ingham4b536182011-08-09 02:12:22 +00001018 switch (state)
1019 {
1020 case eStateCrashed:
1021 case eStateDetached:
1022 case eStateExited:
1023 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001024 // We need to toggle the run lock as this won't get done in
1025 // SetPublicState() if the process is hijacked.
1026 if (hijack_listener)
1027 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001028 return state;
1029 case eStateStopped:
1030 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1031 continue;
1032 else
Greg Clayton44d93782014-01-27 23:43:24 +00001033 {
1034 // We need to toggle the run lock as this won't get done in
1035 // SetPublicState() if the process is hijacked.
1036 if (hijack_listener)
1037 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001038 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001039 }
Jim Ingham4b536182011-08-09 02:12:22 +00001040 default:
1041 continue;
1042 }
1043 }
1044 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045}
1046
Greg Claytondc6224e2014-10-21 01:00:42 +00001047bool
1048Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1049 Stream *stream,
1050 bool &pop_process_io_handler)
1051{
1052 const bool handle_pop = pop_process_io_handler == true;
1053
1054 pop_process_io_handler = false;
1055 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1056
1057 if (!process_sp)
1058 return false;
1059
1060 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1061 if (event_state == eStateInvalid)
1062 return false;
1063
1064 switch (event_state)
1065 {
1066 case eStateInvalid:
1067 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001068 case eStateAttaching:
1069 case eStateLaunching:
1070 case eStateStepping:
1071 case eStateDetached:
1072 {
1073 if (stream)
1074 stream->Printf ("Process %" PRIu64 " %s\n",
1075 process_sp->GetID(),
1076 StateAsCString (event_state));
1077
1078 if (event_state == eStateDetached)
1079 pop_process_io_handler = true;
1080 }
1081 break;
1082
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001083 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001084 case eStateRunning:
1085 // Don't be chatty when we run...
1086 break;
1087
1088 case eStateExited:
1089 if (stream)
1090 process_sp->GetStatus(*stream);
1091 pop_process_io_handler = true;
1092 break;
1093
1094 case eStateStopped:
1095 case eStateCrashed:
1096 case eStateSuspended:
1097 // Make sure the program hasn't been auto-restarted:
1098 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1099 {
1100 if (stream)
1101 {
1102 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1103 if (num_reasons > 0)
1104 {
1105 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1106 if (num_reasons == 1)
1107 {
1108 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1109 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1110 process_sp->GetID(),
1111 reason ? reason : "<UNKNOWN REASON>");
1112 }
1113 else
1114 {
1115 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1116 process_sp->GetID());
1117
1118
1119 for (size_t i = 0; i < num_reasons; i++)
1120 {
1121 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1122 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1123 }
1124 }
1125 }
1126 }
1127 }
1128 else
1129 {
1130 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1131 {
1132 ThreadList &thread_list = process_sp->GetThreadList();
1133 Mutex::Locker locker (thread_list.GetMutex());
1134
1135 ThreadSP curr_thread (thread_list.GetSelectedThread());
1136 ThreadSP thread;
1137 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1138 if (curr_thread)
1139 curr_thread_stop_reason = curr_thread->GetStopReason();
1140 if (!curr_thread ||
1141 !curr_thread->IsValid() ||
1142 curr_thread_stop_reason == eStopReasonInvalid ||
1143 curr_thread_stop_reason == eStopReasonNone)
1144 {
1145 // Prefer a thread that has just completed its plan over another thread as current thread.
1146 ThreadSP plan_thread;
1147 ThreadSP other_thread;
1148 const size_t num_threads = thread_list.GetSize();
1149 size_t i;
1150 for (i = 0; i < num_threads; ++i)
1151 {
1152 thread = thread_list.GetThreadAtIndex(i);
1153 StopReason thread_stop_reason = thread->GetStopReason();
1154 switch (thread_stop_reason)
1155 {
1156 case eStopReasonInvalid:
1157 case eStopReasonNone:
1158 break;
1159
1160 case eStopReasonTrace:
1161 case eStopReasonBreakpoint:
1162 case eStopReasonWatchpoint:
1163 case eStopReasonSignal:
1164 case eStopReasonException:
1165 case eStopReasonExec:
1166 case eStopReasonThreadExiting:
1167 case eStopReasonInstrumentation:
1168 if (!other_thread)
1169 other_thread = thread;
1170 break;
1171 case eStopReasonPlanComplete:
1172 if (!plan_thread)
1173 plan_thread = thread;
1174 break;
1175 }
1176 }
1177 if (plan_thread)
1178 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1179 else if (other_thread)
1180 thread_list.SetSelectedThreadByID (other_thread->GetID());
1181 else
1182 {
1183 if (curr_thread && curr_thread->IsValid())
1184 thread = curr_thread;
1185 else
1186 thread = thread_list.GetThreadAtIndex(0);
1187
1188 if (thread)
1189 thread_list.SetSelectedThreadByID (thread->GetID());
1190 }
1191 }
1192 }
1193 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1194 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1195 // have a hard time restarting the process.
1196 if (stream)
1197 {
1198 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1199 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1200 {
1201 const bool only_threads_with_stop_reason = true;
1202 const uint32_t start_frame = 0;
1203 const uint32_t num_frames = 1;
1204 const uint32_t num_frames_with_source = 1;
1205 process_sp->GetStatus(*stream);
1206 process_sp->GetThreadStatus (*stream,
1207 only_threads_with_stop_reason,
1208 start_frame,
1209 num_frames,
1210 num_frames_with_source);
1211 }
1212 else
1213 {
1214 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1215 if (target_idx != UINT32_MAX)
1216 stream->Printf ("Target %d: (", target_idx);
1217 else
1218 stream->Printf ("Target <unknown index>: (");
1219 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1220 stream->Printf (") stopped.\n");
1221 }
1222 }
1223
1224 // Pop the process IO handler
1225 pop_process_io_handler = true;
1226 }
1227 break;
1228 }
1229
1230 if (handle_pop && pop_process_io_handler)
1231 process_sp->PopProcessIOHandler();
1232
1233 return true;
1234}
1235
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001236
1237StateType
1238Process::WaitForState
1239(
1240 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001241 const StateType *match_states,
1242 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001243)
1244{
1245 EventSP event_sp;
1246 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001247 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248 while (state != eStateInvalid)
1249 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001250 // If we are exited or detached, we won't ever get back to any
1251 // other valid state...
1252 if (state == eStateDetached || state == eStateExited)
1253 return state;
1254
Greg Clayton44d93782014-01-27 23:43:24 +00001255 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256
1257 for (i=0; i<num_match_states; ++i)
1258 {
1259 if (match_states[i] == state)
1260 return state;
1261 }
1262 }
1263 return state;
1264}
1265
Jim Ingham30f9b212010-10-11 23:53:14 +00001266bool
1267Process::HijackProcessEvents (Listener *listener)
1268{
1269 if (listener != NULL)
1270 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001271 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001272 }
1273 else
1274 return false;
1275}
1276
1277void
1278Process::RestoreProcessEvents ()
1279{
1280 RestoreBroadcaster();
1281}
1282
Jim Ingham0f16e732011-02-08 05:20:59 +00001283bool
1284Process::HijackPrivateProcessEvents (Listener *listener)
1285{
1286 if (listener != NULL)
1287 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001288 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001289 }
1290 else
1291 return false;
1292}
1293
1294void
1295Process::RestorePrivateProcessEvents ()
1296{
1297 m_private_state_broadcaster.RestoreBroadcaster();
1298}
1299
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001301Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302{
Greg Clayton5160ce52013-03-27 23:08:40 +00001303 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304
1305 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001306 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1307 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308
Greg Clayton44d93782014-01-27 23:43:24 +00001309 Listener *listener = hijack_listener;
1310 if (listener == NULL)
1311 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001314 if (listener->WaitForEventForBroadcasterWithType (timeout,
1315 this,
1316 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1317 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001318 {
1319 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1320 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1321 else if (log)
1322 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1323 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324
1325 if (log)
1326 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001327 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 StateAsCString(state));
1329 return state;
1330}
1331
1332Event *
1333Process::PeekAtStateChangedEvents ()
1334{
Greg Clayton5160ce52013-03-27 23:08:40 +00001335 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336
1337 if (log)
1338 log->Printf ("Process::%s...", __FUNCTION__);
1339
1340 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001341 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1342 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 if (log)
1344 {
1345 if (event_ptr)
1346 {
1347 log->Printf ("Process::%s (event_ptr) => %s",
1348 __FUNCTION__,
1349 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1350 }
1351 else
1352 {
1353 log->Printf ("Process::%s no events found",
1354 __FUNCTION__);
1355 }
1356 }
1357 return event_ptr;
1358}
1359
1360StateType
1361Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1362{
Greg Clayton5160ce52013-03-27 23:08:40 +00001363 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364
1365 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001366 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1367 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368
1369 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001370 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1371 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001372 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001373 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001374 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1375 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376
1377 // This is a bit of a hack, but when we wait here we could very well return
1378 // to the command-line, and that could disable the log, which would render the
1379 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001381 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1382 __FUNCTION__, static_cast<const void *>(timeout),
1383 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 return state;
1385}
1386
1387bool
1388Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1389{
Greg Clayton5160ce52013-03-27 23:08:40 +00001390 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391
1392 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001393 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1394 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395
1396 if (control_only)
1397 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1398 else
1399 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1400}
1401
1402bool
1403Process::IsRunning () const
1404{
1405 return StateIsRunningState (m_public_state.GetValue());
1406}
1407
1408int
1409Process::GetExitStatus ()
1410{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001411 Mutex::Locker locker (m_exit_status_mutex);
1412
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413 if (m_public_state.GetValue() == eStateExited)
1414 return m_exit_status;
1415 return -1;
1416}
1417
Greg Clayton85851dd2010-12-04 00:10:17 +00001418
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419const char *
1420Process::GetExitDescription ()
1421{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001422 Mutex::Locker locker (m_exit_status_mutex);
1423
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001424 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1425 return m_exit_string.c_str();
1426 return NULL;
1427}
1428
Greg Clayton6779606a2011-01-22 23:43:18 +00001429bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001430Process::SetExitStatus (int status, const char *cstr)
1431{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001432 // Use a mutex to protect setting the exit status.
1433 Mutex::Locker locker (m_exit_status_mutex);
1434
Greg Clayton5160ce52013-03-27 23:08:40 +00001435 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001436 if (log)
1437 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1438 status, status,
1439 cstr ? "\"" : "",
1440 cstr ? cstr : "NULL",
1441 cstr ? "\"" : "");
1442
Greg Clayton6779606a2011-01-22 23:43:18 +00001443 // We were already in the exited state
1444 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001445 {
Greg Clayton385d6032011-01-26 23:47:29 +00001446 if (log)
1447 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001448 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001449 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001450
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001451 m_exit_status = status;
1452 if (cstr)
1453 m_exit_string = cstr;
1454 else
1455 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001456
Greg Clayton5df78fa2015-05-23 03:54:53 +00001457 // When we exit, we no longer need to the communication channel
Greg Clayton5df78fa2015-05-23 03:54:53 +00001458 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00001459 m_stdio_communication.StopReadThread();
Greg Clayton5df78fa2015-05-23 03:54:53 +00001460 m_stdin_forward = false;
1461
1462 // And we don't need the input reader anymore as well
1463 if (m_process_input_reader)
1464 {
1465 m_process_input_reader->SetIsDone(true);
1466 m_process_input_reader->Cancel();
1467 m_process_input_reader.reset();
1468 }
Greg Clayton10177aa2010-12-08 05:08:21 +00001469
Greg Clayton08765fa2015-05-28 03:24:30 +00001470 // Clear the last natural stop ID since it has a strong
1471 // reference to this process
1472 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1473
Greg Clayton6779606a2011-01-22 23:43:18 +00001474 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001475
1476 // Allow subclasses to do some cleanup
1477 DidExit ();
1478
Greg Clayton6779606a2011-01-22 23:43:18 +00001479 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480}
1481
1482// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001483// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484// found in the global target list (we want to be completely sure that the
1485// lldb_private::Process doesn't go away before we can deliver the signal.
1486bool
Greg Claytone4e45922011-11-16 05:37:56 +00001487Process::SetProcessExitStatus (void *callback_baton,
1488 lldb::pid_t pid,
1489 bool exited,
1490 int signo, // Zero for no signal
1491 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001492)
1493{
Greg Clayton5160ce52013-03-27 23:08:40 +00001494 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001495 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001496 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001497 callback_baton,
1498 pid,
1499 exited,
1500 signo,
1501 exit_status);
1502
1503 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 {
Greg Clayton66111032010-06-23 01:19:29 +00001505 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001506 if (target_sp)
1507 {
1508 ProcessSP process_sp (target_sp->GetProcessSP());
1509 if (process_sp)
1510 {
1511 const char *signal_cstr = NULL;
1512 if (signo)
1513 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1514
1515 process_sp->SetExitStatus (exit_status, signal_cstr);
1516 }
1517 }
1518 return true;
1519 }
1520 return false;
1521}
1522
1523
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001524void
1525Process::UpdateThreadListIfNeeded ()
1526{
1527 const uint32_t stop_id = GetStopID();
1528 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1529 {
Greg Clayton2637f822011-11-17 01:23:07 +00001530 const StateType state = GetPrivateState();
1531 if (StateIsStoppedState (state, true))
1532 {
1533 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001534 // m_thread_list does have its own mutex, but we need to
1535 // hold onto the mutex between the call to UpdateThreadList(...)
1536 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001537 ThreadList &old_thread_list = m_thread_list;
1538 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001539 ThreadList new_thread_list(this);
1540 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001541 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001542 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001543 {
Jim Ingham09437922013-03-01 20:04:25 +00001544 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1545 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1546 // shutting us down, causing a deadlock.
1547 if (!m_destroy_in_process)
1548 {
1549 OperatingSystem *os = GetOperatingSystem ();
1550 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001551 {
1552 // Clear any old backing threads where memory threads might have been
1553 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001554 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001555 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001556 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001557
Greg Clayton15484402015-05-15 18:40:24 +00001558 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1559 // can run an expression to determine if a SBValue is a dynamic type or not
1560 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1561 // that require running code...
1562
1563 Target &target = GetTarget();
1564 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1565 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1566 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1567
Greg Claytonb3ae8762013-04-12 20:07:46 +00001568 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001569
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001570 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1571 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1572 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Clayton15484402015-05-15 18:40:24 +00001573
1574 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1575 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001576 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001577 else
1578 {
1579 // No OS plug-in, the new thread list is the same as the real thread list
1580 new_thread_list = real_thread_list;
1581 }
Jim Ingham09437922013-03-01 20:04:25 +00001582 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001583
1584 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001585 m_thread_list.Update (new_thread_list);
1586 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001587
Jason Molenda4ff13262013-11-20 00:31:38 +00001588 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1589 {
1590 // Clear any extended threads that we may have accumulated previously
1591 m_extended_thread_list.Clear();
1592 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001593
1594 m_queue_list.Clear();
1595 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001596 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001597 }
Greg Clayton2637f822011-11-17 01:23:07 +00001598 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001599 }
1600}
1601
Jason Molenda5e8dce42013-12-13 00:29:16 +00001602void
1603Process::UpdateQueueListIfNeeded ()
1604{
1605 if (m_system_runtime_ap.get())
1606 {
1607 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1608 {
1609 const StateType state = GetPrivateState();
1610 if (StateIsStoppedState (state, true))
1611 {
1612 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1613 m_queue_list_stop_id = GetLastNaturalStopID();
1614 }
1615 }
1616 }
1617}
1618
Greg Claytona4d87472013-01-18 23:41:08 +00001619ThreadSP
1620Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1621{
1622 OperatingSystem *os = GetOperatingSystem ();
1623 if (os)
1624 return os->CreateThread(tid, context);
1625 return ThreadSP();
1626}
1627
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001628uint32_t
1629Process::GetNextThreadIndexID (uint64_t thread_id)
1630{
1631 return AssignIndexIDToThread(thread_id);
1632}
1633
1634bool
1635Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1636{
1637 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1638 if (iterator == m_thread_id_to_index_id_map.end())
1639 {
1640 return false;
1641 }
1642 else
1643 {
1644 return true;
1645 }
1646}
1647
1648uint32_t
1649Process::AssignIndexIDToThread(uint64_t thread_id)
1650{
1651 uint32_t result = 0;
1652 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1653 if (iterator == m_thread_id_to_index_id_map.end())
1654 {
1655 result = ++m_thread_index_id;
1656 m_thread_id_to_index_id_map[thread_id] = result;
1657 }
1658 else
1659 {
1660 result = iterator->second;
1661 }
1662
1663 return result;
1664}
1665
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666StateType
1667Process::GetState()
1668{
1669 // If any other threads access this we will need a mutex for it
1670 return m_public_state.GetValue ();
1671}
1672
Greg Claytondc6224e2014-10-21 01:00:42 +00001673bool
1674Process::StateChangedIsExternallyHijacked()
1675{
1676 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1677 {
1678 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1679 return true;
1680 }
1681 return false;
1682}
1683
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684void
Jim Ingham221d51c2013-05-08 00:35:16 +00001685Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686{
Greg Clayton5160ce52013-03-27 23:08:40 +00001687 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001689 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001690 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001691 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001692
1693 // On the transition from Run to Stopped, we unlock the writer end of the
1694 // run lock. The lock gets locked in Resume, which is the public API
1695 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001696 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001697 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001698 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001699 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001700 if (log)
1701 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001702 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001703 }
1704 else
1705 {
1706 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1707 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001708 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001709 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001710 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001711 {
1712 if (log)
1713 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001714 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001715 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001716 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001717 }
1718 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001719}
1720
Jim Ingham3b8285d2012-04-19 01:40:33 +00001721Error
1722Process::Resume ()
1723{
Greg Clayton5160ce52013-03-27 23:08:40 +00001724 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001725 if (log)
1726 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001727 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001728 {
1729 Error error("Resume request failed - process still running.");
1730 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001731 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001732 return error;
1733 }
1734 return PrivateResume();
1735}
1736
Greg Claytondc6224e2014-10-21 01:00:42 +00001737Error
1738Process::ResumeSynchronous (Stream *stream)
1739{
1740 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1741 if (log)
1742 log->Printf("Process::ResumeSynchronous -- locking run lock");
1743 if (!m_public_run_lock.TrySetRunning())
1744 {
1745 Error error("Resume request failed - process still running.");
1746 if (log)
1747 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1748 return error;
1749 }
1750
1751 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1752 HijackProcessEvents(listener_sp.get());
1753
1754 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001755 if (error.Success())
1756 {
1757 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1758 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1759 if (!StateIsStoppedState(state, must_be_alive))
1760 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1761 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001762
1763 // Undo the hijacking of process events...
1764 RestoreProcessEvents();
1765
Greg Claytondc6224e2014-10-21 01:00:42 +00001766 return error;
1767}
1768
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001769StateType
1770Process::GetPrivateState ()
1771{
1772 return m_private_state.GetValue();
1773}
1774
1775void
1776Process::SetPrivateState (StateType new_state)
1777{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001778 if (m_finalize_called)
1779 return;
1780
Greg Clayton5160ce52013-03-27 23:08:40 +00001781 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001782 bool state_changed = false;
1783
1784 if (log)
1785 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1786
Andrew Kaylor29d65742013-05-10 17:19:04 +00001787 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001788 Mutex::Locker locker(m_private_state.GetMutex());
1789
1790 const StateType old_state = m_private_state.GetValueNoLock ();
1791 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001792
Greg Claytonaa49c832013-05-03 22:25:56 +00001793 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1794 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1795 if (old_state_is_stopped != new_state_is_stopped)
1796 {
1797 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001798 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001799 else
Ed Maste64fad602013-07-29 20:58:06 +00001800 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001801 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001802
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 if (state_changed)
1804 {
1805 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001806 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001807 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001809 // Note, this currently assumes that all threads in the list
1810 // stop when the process stops. In the future we will want to
1811 // support a debugging model where some threads continue to run
1812 // while others are stopped. When that happens we will either need
1813 // a way for the thread list to identify which threads are stopping
1814 // or create a special thread list containing only threads which
1815 // actually stopped.
1816 //
1817 // The process plugin is responsible for managing the actual
1818 // behavior of the threads and should have stopped any threads
1819 // that are going to stop before we get here.
1820 m_thread_list.DidStop();
1821
Jim Ingham4b536182011-08-09 02:12:22 +00001822 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001823 if (!m_mod_id.IsLastResumeForUserExpression())
1824 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001825 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001827 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 }
Ilia K38810f42015-05-20 10:15:47 +00001829
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001830 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001831 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:47 +00001832 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001833 else
Ilia K38810f42015-05-20 10:15:47 +00001834 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835 }
1836 else
1837 {
1838 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001839 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001840 }
1841}
1842
Jim Ingham0faa43f2011-11-08 03:00:11 +00001843void
1844Process::SetRunningUserExpression (bool on)
1845{
1846 m_mod_id.SetRunningUserExpression (on);
1847}
1848
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849addr_t
1850Process::GetImageInfoAddress()
1851{
1852 return LLDB_INVALID_ADDRESS;
1853}
1854
Greg Clayton8f343b02010-11-04 01:54:29 +00001855//----------------------------------------------------------------------
1856// LoadImage
1857//
1858// This function provides a default implementation that works for most
1859// unix variants. Any Process subclasses that need to do shared library
1860// loading differently should override LoadImage and UnloadImage and
1861// do what is needed.
1862//----------------------------------------------------------------------
1863uint32_t
1864Process::LoadImage (const FileSpec &image_spec, Error &error)
1865{
Greg Claytonc00ca312015-04-02 18:44:58 +00001866 if (m_finalizing)
1867 {
1868 error.SetErrorString("process is tearing itself down");
1869 return LLDB_INVALID_IMAGE_TOKEN;
1870 }
1871
Greg Claytonac7a3db2012-04-18 00:05:19 +00001872 char path[PATH_MAX];
1873 image_spec.GetPath(path, sizeof(path));
1874
Greg Clayton8f343b02010-11-04 01:54:29 +00001875 DynamicLoader *loader = GetDynamicLoader();
1876 if (loader)
1877 {
1878 error = loader->CanLoadImage();
1879 if (error.Fail())
1880 return LLDB_INVALID_IMAGE_TOKEN;
1881 }
1882
1883 if (error.Success())
1884 {
1885 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001886
1887 if (thread_sp)
1888 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001889 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001890
1891 if (frame_sp)
1892 {
1893 ExecutionContext exe_ctx;
1894 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001895 EvaluateExpressionOptions expr_options;
1896 expr_options.SetUnwindOnError(true);
1897 expr_options.SetIgnoreBreakpoints(true);
1898 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001899 expr_options.SetResultIsInternal(true);
1900
Greg Clayton8f343b02010-11-04 01:54:29 +00001901 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001902 expr.Printf(R"(
1903 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1904 the_result.image_ptr = dlopen ("%s", 2);
1905 if (the_result.image_ptr == (void *) 0x0)
1906 {
1907 the_result.error_str = dlerror();
1908 }
1909 else
1910 {
1911 the_result.error_str = (const char *) 0x0;
1912 }
1913 the_result;
1914 )",
1915 path);
1916 const char *prefix = R"(
1917 extern "C" void* dlopen (const char *path, int mode);
1918 extern "C" const char *dlerror (void);
1919 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001920 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001921 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001922 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001923 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001924 expr.GetData(),
1925 prefix,
1926 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001927 expr_error);
1928 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001929 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001930 error = result_valobj_sp->GetError();
1931 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001932 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001933 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001934 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1935 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001936 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001937 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1938 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1939 {
1940 uint32_t image_token = m_image_tokens.size();
1941 m_image_tokens.push_back (image_ptr);
1942 return image_token;
1943 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001944 else if (image_ptr == 0)
1945 {
Jim Ingham6971b862014-07-19 00:37:06 +00001946 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1947 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001948 {
Jim Ingham6971b862014-07-19 00:37:06 +00001949 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001950 {
Enrico Granata2206b482014-10-30 18:27:31 +00001951 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1952 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001953 if (error.Success() && num_chars > 0)
1954 {
1955 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001956 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1957 }
1958 else
1959 {
1960 error.Clear();
1961 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001962 }
1963 }
1964 }
1965 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001966 }
1967 }
1968 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001969 else
1970 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001971 }
1972 }
1973 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001974 if (!error.AsCString())
1975 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001976 return LLDB_INVALID_IMAGE_TOKEN;
1977}
1978
1979//----------------------------------------------------------------------
1980// UnloadImage
1981//
1982// This function provides a default implementation that works for most
1983// unix variants. Any Process subclasses that need to do shared library
1984// loading differently should override LoadImage and UnloadImage and
1985// do what is needed.
1986//----------------------------------------------------------------------
1987Error
1988Process::UnloadImage (uint32_t image_token)
1989{
1990 Error error;
Greg Claytonc00ca312015-04-02 18:44:58 +00001991
1992 if (m_finalizing)
1993 {
1994 error.SetErrorString("process is tearing itself down");
1995 return error;
1996 }
1997
Greg Clayton8f343b02010-11-04 01:54:29 +00001998 if (image_token < m_image_tokens.size())
1999 {
2000 const addr_t image_addr = m_image_tokens[image_token];
2001 if (image_addr == LLDB_INVALID_ADDRESS)
2002 {
2003 error.SetErrorString("image already unloaded");
2004 }
2005 else
2006 {
2007 DynamicLoader *loader = GetDynamicLoader();
2008 if (loader)
2009 error = loader->CanLoadImage();
2010
2011 if (error.Success())
2012 {
2013 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00002014
2015 if (thread_sp)
2016 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002017 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00002018
2019 if (frame_sp)
2020 {
2021 ExecutionContext exe_ctx;
2022 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00002023 EvaluateExpressionOptions expr_options;
2024 expr_options.SetUnwindOnError(true);
2025 expr_options.SetIgnoreBreakpoints(true);
2026 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00002027 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00002028 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00002029 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00002030 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00002031 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00002032 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002033 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00002034 expr.GetData(),
2035 prefix,
2036 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00002037 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002038 if (result_valobj_sp->GetError().Success())
2039 {
2040 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002041 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002042 {
2043 if (scalar.UInt(1))
2044 {
2045 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2046 }
2047 else
2048 {
2049 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2050 }
2051 }
2052 }
2053 else
2054 {
2055 error = result_valobj_sp->GetError();
2056 }
2057 }
2058 }
2059 }
2060 }
2061 }
2062 else
2063 {
2064 error.SetErrorString("invalid image token");
2065 }
2066 return error;
2067}
2068
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002069const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002070Process::GetABI()
2071{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002072 if (!m_abi_sp)
2073 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2074 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075}
2076
Jim Ingham22777012010-09-23 02:01:19 +00002077LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002078Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002079{
Greg Claytonc00ca312015-04-02 18:44:58 +00002080 if (m_finalizing)
2081 return nullptr;
2082
Jim Ingham22777012010-09-23 02:01:19 +00002083 LanguageRuntimeCollection::iterator pos;
2084 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002085 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002086 {
Jim Inghamab175242012-03-10 00:22:19 +00002087 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002088
Jim Inghamab175242012-03-10 00:22:19 +00002089 m_language_runtimes[language] = runtime_sp;
2090 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002091 }
2092 else
2093 return (*pos).second.get();
2094}
2095
2096CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002097Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002098{
Jim Inghamab175242012-03-10 00:22:19 +00002099 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002100 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2101 return static_cast<CPPLanguageRuntime *> (runtime);
2102 return NULL;
2103}
2104
2105ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002106Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002107{
Jim Inghamab175242012-03-10 00:22:19 +00002108 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002109 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2110 return static_cast<ObjCLanguageRuntime *> (runtime);
2111 return NULL;
2112}
2113
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002114bool
2115Process::IsPossibleDynamicValue (ValueObject& in_value)
2116{
Greg Claytonc00ca312015-04-02 18:44:58 +00002117 if (m_finalizing)
2118 return false;
2119
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002120 if (in_value.IsDynamic())
2121 return false;
2122 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2123
2124 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2125 {
2126 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2127 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2128 }
2129
2130 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2131 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2132 return true;
2133
2134 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2135 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2136}
2137
Zachary Turner93749ab2015-03-03 21:51:25 +00002138void
2139Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2140{
2141 m_dynamic_checkers_ap.reset(dynamic_checkers);
2142}
2143
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144BreakpointSiteList &
2145Process::GetBreakpointSiteList()
2146{
2147 return m_breakpoint_site_list;
2148}
2149
2150const BreakpointSiteList &
2151Process::GetBreakpointSiteList() const
2152{
2153 return m_breakpoint_site_list;
2154}
2155
2156
2157void
2158Process::DisableAllBreakpointSites ()
2159{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002160 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2161// bp_site->SetEnabled(true);
2162 DisableBreakpointSite(bp_site);
2163 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164}
2165
2166Error
2167Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2168{
2169 Error error (DisableBreakpointSiteByID (break_id));
2170
2171 if (error.Success())
2172 m_breakpoint_site_list.Remove(break_id);
2173
2174 return error;
2175}
2176
2177Error
2178Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2179{
2180 Error error;
2181 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2182 if (bp_site_sp)
2183 {
2184 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002185 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002186 }
2187 else
2188 {
Daniel Malead01b2952012-11-29 21:49:15 +00002189 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190 }
2191
2192 return error;
2193}
2194
2195Error
2196Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2197{
2198 Error error;
2199 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2200 if (bp_site_sp)
2201 {
2202 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002203 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204 }
2205 else
2206 {
Daniel Malead01b2952012-11-29 21:49:15 +00002207 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002208 }
2209 return error;
2210}
2211
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002212lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002213Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002215 addr_t load_addr = LLDB_INVALID_ADDRESS;
2216
2217 bool show_error = true;
2218 switch (GetState())
2219 {
2220 case eStateInvalid:
2221 case eStateUnloaded:
2222 case eStateConnected:
2223 case eStateAttaching:
2224 case eStateLaunching:
2225 case eStateDetached:
2226 case eStateExited:
2227 show_error = false;
2228 break;
2229
2230 case eStateStopped:
2231 case eStateRunning:
2232 case eStateStepping:
2233 case eStateCrashed:
2234 case eStateSuspended:
2235 show_error = IsAlive();
2236 break;
2237 }
2238
2239 // Reset the IsIndirect flag here, in case the location changes from
2240 // pointing to a indirect symbol to a regular symbol.
2241 owner->SetIsIndirect (false);
2242
2243 if (owner->ShouldResolveIndirectFunctions())
2244 {
2245 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2246 if (symbol && symbol->IsIndirect())
2247 {
2248 Error error;
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;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002475 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 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.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00004040 m_stdio_communication.StopReadThread();
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 Ingham60c915e2015-06-23 21:02:45 +00004274Process::StartPrivateStateThread (bool is_secondary_thread)
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 Ingham60c915e2015-06-23 21:02:45 +00004282 if (!is_secondary_thread && 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.
Jim Ingham60c915e2015-06-23 21:02:45 +00004306 PrivateStateThreadArgs args = {this, is_secondary_thread};
4307 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) &args, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004308 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004309 {
4310 ResumePrivateStateThread();
4311 return true;
4312 }
4313 else
4314 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004315}
4316
4317void
4318Process::PausePrivateStateThread ()
4319{
4320 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4321}
4322
4323void
4324Process::ResumePrivateStateThread ()
4325{
4326 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4327}
4328
4329void
4330Process::StopPrivateStateThread ()
4331{
Greg Clayton8b82f082011-04-12 05:54:46 +00004332 if (PrivateStateThreadIsValid ())
4333 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004334 else
4335 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004336 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004337 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004338 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004339 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004340}
4341
4342void
4343Process::ControlPrivateStateThread (uint32_t signal)
4344{
Greg Clayton5160ce52013-03-27 23:08:40 +00004345 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004346
4347 assert (signal == eBroadcastInternalStateControlStop ||
4348 signal == eBroadcastInternalStateControlPause ||
4349 signal == eBroadcastInternalStateControlResume);
4350
4351 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004352 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004354 // Signal the private state thread. First we should copy this is case the
4355 // thread starts exiting since the private state thread will NULL this out
4356 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004357 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004358 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004359 {
4360 TimeValue timeout_time;
4361 bool timed_out;
4362
4363 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4364
4365 timeout_time = TimeValue::Now();
4366 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004367 if (log)
4368 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004369 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4370 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4371
4372 if (signal == eBroadcastInternalStateControlStop)
4373 {
4374 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004375 {
Zachary Turner39de3112014-09-09 20:54:56 +00004376 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004377 if (log)
4378 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4379 }
4380 else
4381 {
4382 if (log)
4383 log->Printf ("The control event killed the private state thread without having to cancel.");
4384 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004385
4386 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004387 private_state_thread.Join(&result);
4388 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004389 }
4390 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004391 else
4392 {
4393 if (log)
4394 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4395 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004396}
4397
4398void
Jim Inghamcfc09352012-07-27 23:57:19 +00004399Process::SendAsyncInterrupt ()
4400{
4401 if (PrivateStateThreadIsValid())
4402 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4403 else
4404 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4405}
4406
4407void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004408Process::HandlePrivateEvent (EventSP &event_sp)
4409{
Greg Clayton5160ce52013-03-27 23:08:40 +00004410 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004411 m_resume_requested = false;
4412
Jim Inghamaacc3182012-06-06 00:29:30 +00004413 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004414
Greg Clayton414f5d32011-01-25 02:58:48 +00004415 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004416
4417 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004418 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004419 {
Jim Ingham754ab982011-01-29 04:05:41 +00004420 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004421 if (log)
4422 log->Printf ("Ran next event action, result was %d.", action_result);
4423
Jim Inghambb3a2832011-01-29 01:49:25 +00004424 switch (action_result)
4425 {
4426 case NextEventAction::eEventActionSuccess:
4427 SetNextEventAction(NULL);
4428 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004429
Jim Inghambb3a2832011-01-29 01:49:25 +00004430 case NextEventAction::eEventActionRetry:
4431 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004432
Jim Inghambb3a2832011-01-29 01:49:25 +00004433 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004434 // Handle Exiting Here. If we already got an exited event,
4435 // we should just propagate it. Otherwise, swallow this event,
4436 // and set our state to exit so the next event will kill us.
4437 if (new_state != eStateExited)
4438 {
4439 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004440 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004441 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004442 SetNextEventAction(NULL);
4443 return;
4444 }
4445 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004446 break;
4447 }
4448 }
4449
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004450 // See if we should broadcast this state to external clients?
4451 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004452
4453 if (should_broadcast)
4454 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004455 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004456 if (log)
4457 {
Daniel Malead01b2952012-11-29 21:49:15 +00004458 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004459 __FUNCTION__,
4460 GetID(),
4461 StateAsCString(new_state),
4462 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004463 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004464 }
Jim Ingham9575d842011-03-11 03:53:59 +00004465 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004466 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004467 {
4468 // Only push the input handler if we aren't fowarding events,
4469 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004470 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004471 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4472 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004473 {
Greg Clayton44d93782014-01-27 23:43:24 +00004474 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004475 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4476 if (log)
4477 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4478 }
Greg Clayton44d93782014-01-27 23:43:24 +00004479 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004480 else if (StateIsStoppedState(new_state, false))
4481 {
4482 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4483 {
4484 // If the lldb_private::Debugger is handling the events, we don't
4485 // want to pop the process IOHandler here, we want to do it when
4486 // we receive the stopped event so we can carefully control when
4487 // the process IOHandler is popped because when we stop we want to
4488 // display some text stating how and why we stopped, then maybe some
4489 // process/thread/frame info, and then we want the "(lldb) " prompt
4490 // to show up. If we pop the process IOHandler here, then we will
4491 // cause the command interpreter to become the top IOHandler after
4492 // the process pops off and it will update its prompt right away...
4493 // See the Debugger.cpp file where it calls the function as
4494 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4495 // Otherwise we end up getting overlapping "(lldb) " prompts and
4496 // garbled output.
4497 //
4498 // If we aren't handling the events in the debugger (which is indicated
4499 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4500 // are hijacked, then we always pop the process IO handler manually.
4501 // Hijacking happens when the internal process state thread is running
4502 // thread plans, or when commands want to run in synchronous mode
4503 // and they call "process->WaitForProcessToStop()". An example of something
4504 // that will hijack the events is a simple expression:
4505 //
4506 // (lldb) expr (int)puts("hello")
4507 //
4508 // This will cause the internal process state thread to resume and halt
4509 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4510 // events) and we do need the IO handler to be pushed and popped
4511 // correctly.
4512
4513 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4514 PopProcessIOHandler ();
4515 }
4516 }
Jim Ingham9575d842011-03-11 03:53:59 +00004517
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004518 BroadcastEvent (event_sp);
4519 }
4520 else
4521 {
4522 if (log)
4523 {
Daniel Malead01b2952012-11-29 21:49:15 +00004524 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004525 __FUNCTION__,
4526 GetID(),
4527 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004528 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004529 }
4530 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004531 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004532}
4533
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004534thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004535Process::PrivateStateThread (void *arg)
4536{
Jim Ingham60c915e2015-06-23 21:02:45 +00004537 PrivateStateThreadArgs *real_args = static_cast<PrivateStateThreadArgs *> (arg);
4538 thread_result_t result = real_args->process->RunPrivateStateThread(real_args->is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004539 return result;
4540}
4541
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004542thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004543Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004544{
Jim Ingham076b3042012-04-10 01:21:57 +00004545 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004546 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004547
Greg Clayton5160ce52013-03-27 23:08:40 +00004548 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004549 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004550 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4551 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004552
4553 bool exit_now = false;
4554 while (!exit_now)
4555 {
4556 EventSP event_sp;
4557 WaitForEventsPrivate (NULL, event_sp, control_only);
4558 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4559 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004560 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004561 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4562 __FUNCTION__, static_cast<void*>(this), GetID(),
4563 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004564
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004565 switch (event_sp->GetType())
4566 {
4567 case eBroadcastInternalStateControlStop:
4568 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004569 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004570
4571 case eBroadcastInternalStateControlPause:
4572 control_only = true;
4573 break;
4574
4575 case eBroadcastInternalStateControlResume:
4576 control_only = false;
4577 break;
4578 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004579
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004580 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004581 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004582 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004583 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4584 {
4585 if (m_public_state.GetValue() == eStateAttaching)
4586 {
4587 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004588 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4589 __FUNCTION__, static_cast<void*>(this),
4590 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004591 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4592 }
4593 else
4594 {
4595 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004596 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4597 __FUNCTION__, static_cast<void*>(this),
4598 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004599 Halt();
4600 }
4601 continue;
4602 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004603
4604 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4605
4606 if (internal_state != eStateInvalid)
4607 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004608 if (m_clear_thread_plans_on_stop &&
4609 StateIsStoppedState(internal_state, true))
4610 {
4611 m_clear_thread_plans_on_stop = false;
4612 m_thread_list.DiscardThreadPlans();
4613 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004614 HandlePrivateEvent (event_sp);
4615 }
4616
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004617 if (internal_state == eStateInvalid ||
4618 internal_state == eStateExited ||
4619 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004620 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004621 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004622 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4623 __FUNCTION__, static_cast<void*>(this), GetID(),
4624 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004626 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004627 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004628 }
4629
Caroline Tice20ad3c42010-10-29 21:48:37 +00004630 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004631 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004632 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4633 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004634
Jim Ingham60c915e2015-06-23 21:02:45 +00004635 // If we are a secondary thread, then the primary thread we are working for will have already
4636 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4637 // try to change it on the way out.
4638 if (!is_secondary_thread)
4639 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004640 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004641 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004642 return NULL;
4643}
4644
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004645//------------------------------------------------------------------
4646// Process Event Data
4647//------------------------------------------------------------------
4648
4649Process::ProcessEventData::ProcessEventData () :
4650 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004651 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004652 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004653 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004654 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004655 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004656{
4657}
4658
4659Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4660 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004661 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004662 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004663 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004664 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004665 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004666{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004667 if (process_sp)
4668 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004669}
4670
4671Process::ProcessEventData::~ProcessEventData()
4672{
4673}
4674
4675const ConstString &
4676Process::ProcessEventData::GetFlavorString ()
4677{
4678 static ConstString g_flavor ("Process::ProcessEventData");
4679 return g_flavor;
4680}
4681
4682const ConstString &
4683Process::ProcessEventData::GetFlavor () const
4684{
4685 return ProcessEventData::GetFlavorString ();
4686}
4687
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004688void
4689Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4690{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004691 ProcessSP process_sp(m_process_wp.lock());
4692
4693 if (!process_sp)
4694 return;
4695
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004696 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004697 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4698 // the public event queue, then other times when we're pretending that this is where we stopped at the
4699 // end of expression evaluation. m_update_state is used to distinguish these
4700 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004701 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004702 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004703 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004704
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004705 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004706
4707 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4708 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4709 // end up restarting the process.
4710 if (m_interrupted)
4711 return;
4712
4713 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004714 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004715 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004716 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004717 uint32_t num_threads = curr_thread_list.GetSize();
4718 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004719
Jim Ingham4b536182011-08-09 02:12:22 +00004720 // The actions might change one of the thread's stop_info's opinions about whether we should
4721 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004722
4723 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4724 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4725 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4726 // 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
4727 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004728 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004729 for (idx = 0; idx < num_threads; ++idx)
4730 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4731
Jim Inghamc7078c22012-12-13 22:24:15 +00004732 // Use this to track whether we should continue from here. We will only continue the target running if
4733 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4734 // then it doesn't matter what the other threads say...
4735
4736 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004737
Jim Ingham0ad7e052013-04-25 02:04:59 +00004738 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4739 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4740 // thing to do is, and it's better to let the user decide than continue behind their backs.
4741
4742 bool does_anybody_have_an_opinion = false;
4743
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004744 for (idx = 0; idx < num_threads; ++idx)
4745 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004746 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004747 if (curr_thread_list.GetSize() != num_threads)
4748 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004749 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004750 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004751 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 +00004752 break;
4753 }
4754
4755 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4756
4757 if (thread_sp->GetIndexID() != thread_index_array[idx])
4758 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004759 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004760 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004761 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004762 idx,
4763 thread_index_array[idx],
4764 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004765 break;
4766 }
4767
Jim Inghamb15bfc72010-10-20 00:39:53 +00004768 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004769 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004770 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004771 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004772 bool this_thread_wants_to_stop;
4773 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004774 {
Jim Ingham0161b492013-02-09 01:29:05 +00004775 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4776 }
4777 else
4778 {
4779 stop_info_sp->PerformAction(event_ptr);
4780 // The stop action might restart the target. If it does, then we want to mark that in the
4781 // event so that whoever is receiving it will know to wait for the running event and reflect
4782 // that state appropriately.
4783 // We also need to stop processing actions, since they aren't expecting the target to be running.
4784
4785 // FIXME: we might have run.
4786 if (stop_info_sp->HasTargetRunSinceMe())
4787 {
4788 SetRestarted (true);
4789 break;
4790 }
4791
4792 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004793 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004794
Jim Inghamc7078c22012-12-13 22:24:15 +00004795 if (still_should_stop == false)
4796 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004797 }
4798 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004799
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004800
Jim Inghama8ca6e22013-05-03 23:04:37 +00004801 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004802 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004803 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004804 {
4805 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004806 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004807 // Use the public resume method here, since this is just
4808 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004809 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004810 }
4811 else
4812 {
4813 // If we didn't restart, run the Stop Hooks here:
4814 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004815 process_sp->GetTarget().RunStopHooks();
4816 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004817 SetRestarted(true);
4818 }
Jim Ingham9575d842011-03-11 03:53:59 +00004819 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004820 }
4821}
4822
4823void
4824Process::ProcessEventData::Dump (Stream *s) const
4825{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004826 ProcessSP process_sp(m_process_wp.lock());
4827
4828 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004829 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004830 static_cast<void*>(process_sp.get()), process_sp->GetID());
4831 else
4832 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004833
Greg Clayton8b82f082011-04-12 05:54:46 +00004834 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004835}
4836
4837const Process::ProcessEventData *
4838Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4839{
4840 if (event_ptr)
4841 {
4842 const EventData *event_data = event_ptr->GetData();
4843 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4844 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4845 }
4846 return NULL;
4847}
4848
4849ProcessSP
4850Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4851{
4852 ProcessSP process_sp;
4853 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4854 if (data)
4855 process_sp = data->GetProcessSP();
4856 return process_sp;
4857}
4858
4859StateType
4860Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4861{
4862 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4863 if (data == NULL)
4864 return eStateInvalid;
4865 else
4866 return data->GetState();
4867}
4868
4869bool
4870Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4871{
4872 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4873 if (data == NULL)
4874 return false;
4875 else
4876 return data->GetRestarted();
4877}
4878
4879void
4880Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4881{
4882 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4883 if (data != NULL)
4884 data->SetRestarted(new_value);
4885}
4886
Jim Ingham0161b492013-02-09 01:29:05 +00004887size_t
4888Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4889{
4890 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4891 if (data != NULL)
4892 return data->GetNumRestartedReasons();
4893 else
4894 return 0;
4895}
4896
4897const char *
4898Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4899{
4900 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4901 if (data != NULL)
4902 return data->GetRestartedReasonAtIndex(idx);
4903 else
4904 return NULL;
4905}
4906
4907void
4908Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4909{
4910 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4911 if (data != NULL)
4912 data->AddRestartedReason(reason);
4913}
4914
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004915bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004916Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4917{
4918 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4919 if (data == NULL)
4920 return false;
4921 else
4922 return data->GetInterrupted ();
4923}
4924
4925void
4926Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4927{
4928 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4929 if (data != NULL)
4930 data->SetInterrupted(new_value);
4931}
4932
4933bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004934Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4935{
4936 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4937 if (data)
4938 {
4939 data->SetUpdateStateOnRemoval();
4940 return true;
4941 }
4942 return false;
4943}
4944
Greg Claytond9e416c2012-02-18 05:35:26 +00004945lldb::TargetSP
4946Process::CalculateTarget ()
4947{
4948 return m_target.shared_from_this();
4949}
4950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004951void
Greg Clayton0603aa92010-10-04 01:05:56 +00004952Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004953{
Greg Claytonc14ee322011-09-22 04:58:26 +00004954 exe_ctx.SetTargetPtr (&m_target);
4955 exe_ctx.SetProcessPtr (this);
4956 exe_ctx.SetThreadPtr(NULL);
4957 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004958}
4959
Greg Claytone996fd32011-03-08 22:40:15 +00004960//uint32_t
4961//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4962//{
4963// return 0;
4964//}
4965//
4966//ArchSpec
4967//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4968//{
4969// return Host::GetArchSpecForExistingProcess (pid);
4970//}
4971//
4972//ArchSpec
4973//Process::GetArchSpecForExistingProcess (const char *process_name)
4974//{
4975// return Host::GetArchSpecForExistingProcess (process_name);
4976//}
4977//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004978void
4979Process::AppendSTDOUT (const char * s, size_t len)
4980{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004981 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004982 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004983 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004984}
4985
4986void
Greg Clayton93e86192011-11-13 04:45:22 +00004987Process::AppendSTDERR (const char * s, size_t len)
4988{
4989 Mutex::Locker locker (m_stdio_communication_mutex);
4990 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004991 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004992}
4993
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004994void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004995Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004996{
4997 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004998 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004999 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
5000}
5001
5002size_t
5003Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
5004{
5005 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005006 if (m_profile_data.empty())
5007 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005008
5009 std::string &one_profile_data = m_profile_data.front();
5010 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005011 if (bytes_available > 0)
5012 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005013 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005014 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005015 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5016 static_cast<void*>(buf),
5017 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005018 if (bytes_available > buf_size)
5019 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005020 memcpy(buf, one_profile_data.c_str(), buf_size);
5021 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005022 bytes_available = buf_size;
5023 }
5024 else
5025 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005026 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005027 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005028 }
5029 }
5030 return bytes_available;
5031}
5032
5033
Greg Clayton93e86192011-11-13 04:45:22 +00005034//------------------------------------------------------------------
5035// Process STDIO
5036//------------------------------------------------------------------
5037
5038size_t
5039Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5040{
5041 Mutex::Locker locker(m_stdio_communication_mutex);
5042 size_t bytes_available = m_stdout_data.size();
5043 if (bytes_available > 0)
5044 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005045 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005046 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005047 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5048 static_cast<void*>(buf),
5049 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005050 if (bytes_available > buf_size)
5051 {
5052 memcpy(buf, m_stdout_data.c_str(), buf_size);
5053 m_stdout_data.erase(0, buf_size);
5054 bytes_available = buf_size;
5055 }
5056 else
5057 {
5058 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5059 m_stdout_data.clear();
5060 }
5061 }
5062 return bytes_available;
5063}
5064
5065
5066size_t
5067Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5068{
5069 Mutex::Locker locker(m_stdio_communication_mutex);
5070 size_t bytes_available = m_stderr_data.size();
5071 if (bytes_available > 0)
5072 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005073 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005074 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005075 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5076 static_cast<void*>(buf),
5077 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005078 if (bytes_available > buf_size)
5079 {
5080 memcpy(buf, m_stderr_data.c_str(), buf_size);
5081 m_stderr_data.erase(0, buf_size);
5082 bytes_available = buf_size;
5083 }
5084 else
5085 {
5086 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5087 m_stderr_data.clear();
5088 }
5089 }
5090 return bytes_available;
5091}
5092
5093void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005094Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5095{
5096 Process *process = (Process *) baton;
5097 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5098}
5099
Greg Clayton44d93782014-01-27 23:43:24 +00005100class IOHandlerProcessSTDIO :
5101 public IOHandler
5102{
5103public:
5104 IOHandlerProcessSTDIO (Process *process,
5105 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005106 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005107 m_process (process),
5108 m_read_file (),
5109 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005110 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005111 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005112 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00005113 m_read_file.SetDescriptor(GetInputFD(), false);
5114 }
5115
5116 virtual
5117 ~IOHandlerProcessSTDIO ()
5118 {
5119
5120 }
5121
Greg Clayton44d93782014-01-27 23:43:24 +00005122 // Each IOHandler gets to run until it is done. It should read data
5123 // from the "in" and place output into "out" and "err and return
5124 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00005125 void
5126 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00005127 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005128 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005129 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005130 SetIsDone(true);
5131 return;
5132 }
5133
5134 SetIsDone(false);
5135 const int read_fd = m_read_file.GetDescriptor();
5136 TerminalState terminal_state;
5137 terminal_state.Save (read_fd, false);
5138 Terminal terminal(read_fd);
5139 terminal.SetCanonical(false);
5140 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005141// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005142#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005143 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5144 while (!GetIsDone())
5145 {
5146 fd_set read_fdset;
5147 FD_ZERO (&read_fdset);
5148 FD_SET (read_fd, &read_fdset);
5149 FD_SET (pipe_read_fd, &read_fdset);
5150 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5151 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5152 if (num_set_fds < 0)
5153 {
5154 const int select_errno = errno;
5155
5156 if (select_errno != EINTR)
5157 SetIsDone(true);
5158 }
5159 else if (num_set_fds > 0)
5160 {
5161 char ch = 0;
5162 size_t n;
5163 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00005164 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005165 n = 1;
5166 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005167 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005168 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005169 SetIsDone(true);
5170 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005171 else
5172 SetIsDone(true);
5173 }
5174 if (FD_ISSET (pipe_read_fd, &read_fdset))
5175 {
5176 size_t bytes_read;
5177 // Consume the interrupt byte
5178 Error error = m_pipe.Read(&ch, 1, bytes_read);
5179 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00005180 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005181 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00005182 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005183 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00005184 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005185 break;
5186 case 'i':
5187 if (StateIsRunningState(m_process->GetState()))
5188 m_process->Halt();
5189 break;
Greg Clayton44d93782014-01-27 23:43:24 +00005190 }
5191 }
5192 }
Greg Clayton44d93782014-01-27 23:43:24 +00005193 }
Greg Clayton44d93782014-01-27 23:43:24 +00005194 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005195#endif
5196 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005197 }
5198
Pavel Labath44464872015-05-27 12:40:32 +00005199 void
5200 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005201 {
Greg Clayton19e11352014-02-26 22:47:33 +00005202 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005203 size_t bytes_written = 0;
5204 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005205 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005206
Pavel Labath44464872015-05-27 12:40:32 +00005207 bool
5208 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005209 {
Greg Clayton19e11352014-02-26 22:47:33 +00005210 // Do only things that are safe to do in an interrupt context (like in
5211 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5212 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5213 // that was written to the pipe and then call m_process->Halt() from a
5214 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005215 if (m_active)
5216 {
5217 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005218 size_t bytes_written = 0;
5219 Error result = m_pipe.Write(&ch, 1, bytes_written);
5220 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005221 }
5222 else
5223 {
5224 // This IOHandler might be pushed on the stack, but not being run currently
5225 // so do the right thing if we aren't actively watching for STDIN by sending
5226 // the interrupt to the process. Otherwise the write to the pipe above would
5227 // do nothing. This can happen when the command interpreter is running and
5228 // gets a "expression ...". It will be on the IOHandler thread and sending
5229 // the input is complete to the delegate which will cause the expression to
5230 // run, which will push the process IO handler, but not run it.
5231
5232 if (StateIsRunningState(m_process->GetState()))
5233 {
5234 m_process->SendAsyncInterrupt();
5235 return true;
5236 }
5237 }
5238 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005239 }
Greg Clayton44d93782014-01-27 23:43:24 +00005240
Pavel Labath44464872015-05-27 12:40:32 +00005241 void
5242 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005243 {
5244
5245 }
5246
5247protected:
5248 Process *m_process;
5249 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5250 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005251 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005252};
5253
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005254void
Greg Clayton44d93782014-01-27 23:43:24 +00005255Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005256{
5257 // First set up the Read Thread for reading/handling process I/O
5258
Greg Clayton44d93782014-01-27 23:43:24 +00005259 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005260
5261 if (conn_ap.get())
5262 {
5263 m_stdio_communication.SetConnection (conn_ap.release());
5264 if (m_stdio_communication.IsConnected())
5265 {
5266 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5267 m_stdio_communication.StartReadThread();
5268
5269 // Now read thread is set up, set up input reader.
5270
5271 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005272 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005273 }
5274 }
5275}
5276
Greg Claytonb4874f12014-02-28 18:22:24 +00005277bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005278Process::ProcessIOHandlerIsActive ()
5279{
5280 IOHandlerSP io_handler_sp (m_process_input_reader);
5281 if (io_handler_sp)
5282 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5283 return false;
5284}
5285bool
Greg Clayton44d93782014-01-27 23:43:24 +00005286Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005287{
Greg Clayton44d93782014-01-27 23:43:24 +00005288 IOHandlerSP io_handler_sp (m_process_input_reader);
5289 if (io_handler_sp)
5290 {
Pavel Labath44464872015-05-27 12:40:32 +00005291 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5292 if (log)
5293 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5294
Greg Clayton44d93782014-01-27 23:43:24 +00005295 io_handler_sp->SetIsDone(false);
5296 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005297 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005298 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005299 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005300}
5301
Greg Claytonb4874f12014-02-28 18:22:24 +00005302bool
Greg Clayton44d93782014-01-27 23:43:24 +00005303Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005304{
Greg Clayton44d93782014-01-27 23:43:24 +00005305 IOHandlerSP io_handler_sp (m_process_input_reader);
5306 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005307 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5308 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005309}
5310
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005311// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005312void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005313Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005314{
Greg Clayton6920b522012-08-22 18:39:03 +00005315 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005316}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005317
Greg Clayton99d0faf2010-11-18 23:32:35 +00005318void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005319Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005320{
Greg Clayton6920b522012-08-22 18:39:03 +00005321 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005322}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005323
Jim Ingham1624a2d2014-05-05 02:26:40 +00005324ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005325Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005326 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005327 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005328 Stream &errors)
5329{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005330 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005331
Jim Ingham77787032011-01-20 02:03:18 +00005332 if (thread_plan_sp.get() == NULL)
5333 {
5334 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005335 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005336 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005337
Jim Ingham7d7931d2013-03-28 00:05:34 +00005338 if (!thread_plan_sp->ValidatePlan(NULL))
5339 {
5340 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005341 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005342 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005343
Greg Claytonc14ee322011-09-22 04:58:26 +00005344 if (exe_ctx.GetProcessPtr() != this)
5345 {
5346 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005347 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005348 }
5349
5350 Thread *thread = exe_ctx.GetThreadPtr();
5351 if (thread == NULL)
5352 {
5353 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005354 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005355 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005356
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005357 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5358 // For that to be true the plan can't be private - since private plans suppress themselves in the
5359 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005360
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005361 bool orig_plan_private = thread_plan_sp->GetPrivate();
5362 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005363
Jim Ingham444586b2011-01-24 06:34:17 +00005364 if (m_private_state.GetValue() != eStateStopped)
5365 {
5366 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005367 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005368 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005369
Jim Ingham66243842011-08-13 00:56:10 +00005370 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005371 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005372 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005373 if (!selected_frame_sp)
5374 {
5375 thread->SetSelectedFrame(0);
5376 selected_frame_sp = thread->GetSelectedFrame();
5377 if (!selected_frame_sp)
5378 {
5379 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005380 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005381 }
5382 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005383
Jim Ingham11b0e052013-02-19 23:22:45 +00005384 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005385
5386 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5387 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005388
Greg Claytonc14ee322011-09-22 04:58:26 +00005389 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005390
Jim Ingham66243842011-08-13 00:56:10 +00005391 uint32_t selected_tid;
5392 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005393 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005394 {
5395 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005396 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005397 }
5398 else
5399 {
5400 selected_tid = LLDB_INVALID_THREAD_ID;
5401 }
5402
Zachary Turner39de3112014-09-09 20:54:56 +00005403 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005404 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005405 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005406
Greg Clayton5160ce52013-03-27 23:08:40 +00005407 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005408 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005409 {
Jim Ingham076b3042012-04-10 01:21:57 +00005410 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5411 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005412 // 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 +00005413 // we are fielding public events here.
5414 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005415 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 +00005416
Jim Ingham372787f2012-04-07 00:00:41 +00005417 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005418
5419 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5420 // returning control here.
5421 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5422 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5423 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5424 // do just what we want.
5425 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5426 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5427 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5428 old_state = m_public_state.GetValue();
5429 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005430
Jim Ingham076b3042012-04-10 01:21:57 +00005431 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005432 StartPrivateStateThread(true);
5433 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005434
Jim Ingham372787f2012-04-07 00:00:41 +00005435 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005436
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005437 if (options.GetDebug())
5438 {
5439 // In this case, we aren't actually going to run, we just want to stop right away.
5440 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5441 // FIXME: To make this prettier we should invent some stop reason for this, but that
5442 // is only cosmetic, and this functionality is only of use to lldb developers who can
5443 // live with not pretty...
5444 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005445 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005446 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005447
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005448 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005449
Sean Callanana46ec452012-07-11 21:31:24 +00005450 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005451
Jim Ingham77787032011-01-20 02:03:18 +00005452 {
Sean Callanana46ec452012-07-11 21:31:24 +00005453 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5454 // restored on exit to the function.
5455 //
5456 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5457 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005458
Sean Callanana46ec452012-07-11 21:31:24 +00005459 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005460
Jim Inghamf48169b2010-11-30 02:22:11 +00005461 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005462 {
5463 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005464 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005465 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005466 thread->GetIndexID(),
5467 thread->GetID(),
5468 s.GetData());
5469 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005470
Sean Callanana46ec452012-07-11 21:31:24 +00005471 bool got_event;
5472 lldb::EventSP event_sp;
5473 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005474
Sean Callanana46ec452012-07-11 21:31:24 +00005475 TimeValue* timeout_ptr = NULL;
5476 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005477
Jim Ingham0161b492013-02-09 01:29:05 +00005478 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 +00005479 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005480 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005481 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005482
Jim Ingham0161b492013-02-09 01:29:05 +00005483 // This is just for accounting:
5484 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005485
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005486 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005487 uint32_t one_thread_timeout_usec;
5488 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005489
5490 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5491 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5492 // first timeout already.
5493
5494 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005495 {
5496 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005497 one_thread_timeout_usec = 0;
5498 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005499 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005500 else
Jim Ingham0161b492013-02-09 01:29:05 +00005501 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005502 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005503
Jim Ingham914f4e72014-03-28 21:58:28 +00005504 // If the overall wait is forever, then we only need to set the one thread timeout:
5505 if (timeout_usec == 0)
5506 {
Ed Maste801335c2014-03-31 19:28:14 +00005507 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005508 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005509 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005510 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005511 }
Jim Ingham0161b492013-02-09 01:29:05 +00005512 else
5513 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005514 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5515 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5516 uint64_t computed_one_thread_timeout;
5517 if (option_one_thread_timeout != 0)
5518 {
5519 if (timeout_usec < option_one_thread_timeout)
5520 {
5521 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005522 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005523 }
5524 computed_one_thread_timeout = option_one_thread_timeout;
5525 }
5526 else
5527 {
5528 computed_one_thread_timeout = timeout_usec / 2;
5529 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5530 computed_one_thread_timeout = default_one_thread_timeout_usec;
5531 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005532 one_thread_timeout_usec = computed_one_thread_timeout;
5533 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5534
Jim Ingham0161b492013-02-09 01:29:05 +00005535 }
Jim Ingham0161b492013-02-09 01:29:05 +00005536 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005537
5538 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005539 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 +00005540 options.GetStopOthers(),
5541 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005542 before_first_timeout,
5543 one_thread_timeout_usec,
5544 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005545
Jim Ingham1460e4b2014-01-10 23:46:59 +00005546 // This isn't going to work if there are unfetched events on the queue.
5547 // Are there cases where we might want to run the remaining events here, and then try to
5548 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005549
Jim Ingham1460e4b2014-01-10 23:46:59 +00005550 Event *other_events = listener.PeekAtNextEvent();
5551 if (other_events != NULL)
5552 {
5553 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005554 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005555 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005556
Jim Ingham1460e4b2014-01-10 23:46:59 +00005557 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5558 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5559 // event coalescing to cause us to lose OUR running event...
5560 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005561
Jim Ingham8559a352012-11-26 23:52:18 +00005562 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5563 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005564
5565#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5566 // It's pretty much impossible to write test cases for things like:
5567 // One thread timeout expires, I go to halt, but the process already stopped
5568 // on the function call stop breakpoint. Turning on this define will make us not
5569 // fetch the first event till after the halt. So if you run a quick function, it will have
5570 // completed, and the completion event will be waiting, when you interrupt for halt.
5571 // The expression evaluation should still succeed.
5572 bool miss_first_event = true;
5573#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005574 TimeValue one_thread_timeout;
5575 TimeValue final_timeout;
5576
Jim Ingham35878c42014-04-08 21:33:21 +00005577
Sean Callanana46ec452012-07-11 21:31:24 +00005578 while (1)
5579 {
5580 // We usually want to resume the process if we get to the top of the loop.
5581 // The only exception is if we get two running events with no intervening
5582 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005583 if (log)
5584 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5585 do_resume,
5586 handle_running_event,
5587 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005588
Jim Ingham184e9812013-01-15 02:47:48 +00005589 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005590 {
5591 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005592
Jim Ingham184e9812013-01-15 02:47:48 +00005593 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005594 {
Jim Ingham0161b492013-02-09 01:29:05 +00005595 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005596 Error resume_error = PrivateResume ();
5597 if (!resume_error.Success())
5598 {
Jim Ingham0161b492013-02-09 01:29:05 +00005599 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5600 num_resumes,
5601 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005602 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005603 break;
5604 }
Sean Callanana46ec452012-07-11 21:31:24 +00005605 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005606
Jim Ingham0161b492013-02-09 01:29:05 +00005607 TimeValue resume_timeout = TimeValue::Now();
5608 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005609
Jim Ingham0161b492013-02-09 01:29:05 +00005610 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005611 if (!got_event)
5612 {
5613 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005614 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5615 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005616
Jim Ingham0161b492013-02-09 01:29:05 +00005617 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005618 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005619 break;
5620 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005621
Sean Callanana46ec452012-07-11 21:31:24 +00005622 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005623
Sean Callanana46ec452012-07-11 21:31:24 +00005624 if (stop_state != eStateRunning)
5625 {
Jim Ingham0161b492013-02-09 01:29:05 +00005626 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005627
Jim Ingham0161b492013-02-09 01:29:05 +00005628 if (stop_state == eStateStopped)
5629 {
5630 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5631 if (log)
5632 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5633 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5634 num_resumes,
5635 StateAsCString(stop_state),
5636 restarted,
5637 do_resume,
5638 handle_running_event);
5639 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005640
Jim Ingham0161b492013-02-09 01:29:05 +00005641 if (restarted)
5642 {
5643 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5644 // event here. But if I do, the best thing is to Halt and then get out of here.
5645 Halt();
5646 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005647
Jim Ingham35e1bda2012-10-16 21:41:58 +00005648 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5649 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005650 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005651 break;
5652 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005653
Sean Callanana46ec452012-07-11 21:31:24 +00005654 if (log)
5655 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5656 // We need to call the function synchronously, so spin waiting for it to return.
5657 // If we get interrupted while executing, we're going to lose our context, and
5658 // won't be able to gather the result at this point.
5659 // We set the timeout AFTER the resume, since the resume takes some time and we
5660 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005661 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005662 else
5663 {
Sean Callanana46ec452012-07-11 21:31:24 +00005664 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005665 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005666 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005667
Jim Ingham0161b492013-02-09 01:29:05 +00005668 if (before_first_timeout)
5669 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005670 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005671 {
5672 one_thread_timeout = TimeValue::Now();
5673 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005674 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005675 }
Jim Ingham0161b492013-02-09 01:29:05 +00005676 else
5677 {
5678 if (timeout_usec == 0)
5679 timeout_ptr = NULL;
5680 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005681 {
5682 final_timeout = TimeValue::Now();
5683 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005684 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005685 }
Jim Ingham0161b492013-02-09 01:29:05 +00005686 }
5687 }
5688 else
5689 {
5690 if (timeout_usec == 0)
5691 timeout_ptr = NULL;
5692 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005693 {
5694 final_timeout = TimeValue::Now();
5695 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005696 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005697 }
Jim Ingham0161b492013-02-09 01:29:05 +00005698 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005699
Jim Ingham0161b492013-02-09 01:29:05 +00005700 do_resume = true;
5701 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005702
Sean Callanana46ec452012-07-11 21:31:24 +00005703 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005704 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005705
Jim Ingham0f16e732011-02-08 05:20:59 +00005706 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005707 {
Sean Callanana46ec452012-07-11 21:31:24 +00005708 if (timeout_ptr)
5709 {
Matt Kopec676a4872013-02-21 23:55:31 +00005710 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005711 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5712 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005713 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005714 else
Sean Callanana46ec452012-07-11 21:31:24 +00005715 {
5716 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5717 }
5718 }
Jim Ingham35878c42014-04-08 21:33:21 +00005719
5720#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5721 // See comment above...
5722 if (miss_first_event)
5723 {
5724 usleep(1000);
5725 miss_first_event = false;
5726 got_event = false;
5727 }
5728 else
5729#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005730 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005731
Sean Callanana46ec452012-07-11 21:31:24 +00005732 if (got_event)
5733 {
5734 if (event_sp.get())
5735 {
5736 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005737 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005738 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005739 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005740 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005741 errors.Printf ("Execution halted by user interrupt.");
5742 if (log)
5743 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005744 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005745 }
5746 else
5747 {
5748 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5749 if (log)
5750 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005751
Jim Inghamcfc09352012-07-27 23:57:19 +00005752 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005753 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005754 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005755 {
Jim Ingham0161b492013-02-09 01:29:05 +00005756 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005757 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5758 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005759 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005760 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005761 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005762 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005763 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005764 }
5765 else
5766 {
Jim Ingham0161b492013-02-09 01:29:05 +00005767 // If we were restarted, we just need to go back up to fetch another event.
5768 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005769 {
5770 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005771 {
5772 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5773 }
5774 keep_going = true;
5775 do_resume = false;
5776 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005777
Jim Inghamcfc09352012-07-27 23:57:19 +00005778 }
5779 else
5780 {
Jim Ingham0161b492013-02-09 01:29:05 +00005781 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5782 StopReason stop_reason = eStopReasonInvalid;
5783 if (stop_info_sp)
5784 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005785
Jim Ingham0161b492013-02-09 01:29:05 +00005786 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5787 // it is OUR plan that is complete?
5788 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005789 {
5790 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005791 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5792 // Now mark this plan as private so it doesn't get reported as the stop reason
5793 // after this point.
5794 if (thread_plan_sp)
5795 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005796 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005797 }
5798 else
5799 {
Jim Ingham0161b492013-02-09 01:29:05 +00005800 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005801 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005802 {
5803 if (log)
5804 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005805 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005806 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005807 {
5808 event_to_broadcast_sp = event_sp;
5809 }
Jim Ingham0161b492013-02-09 01:29:05 +00005810 }
Jim Ingham184e9812013-01-15 02:47:48 +00005811 else
Jim Ingham0161b492013-02-09 01:29:05 +00005812 {
5813 if (log)
5814 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005815 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005816 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005817 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005818 }
Jim Ingham184e9812013-01-15 02:47:48 +00005819 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005820 }
Sean Callanana46ec452012-07-11 21:31:24 +00005821 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005822 }
5823 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005824
Jim Inghamcfc09352012-07-27 23:57:19 +00005825 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005826 // This shouldn't really happen, but sometimes we do get two running events without an
5827 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005828 do_resume = false;
5829 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005830 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005831 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005832
Jim Inghamcfc09352012-07-27 23:57:19 +00005833 default:
5834 if (log)
5835 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005836
Jim Inghamcfc09352012-07-27 23:57:19 +00005837 if (stop_state == eStateExited)
5838 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005839
Sean Callananbf154da2012-08-08 17:35:10 +00005840 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005841 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005842 break;
5843 }
Sean Callanana46ec452012-07-11 21:31:24 +00005844 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005845
Sean Callanana46ec452012-07-11 21:31:24 +00005846 if (keep_going)
5847 continue;
5848 else
5849 break;
5850 }
5851 else
5852 {
5853 if (log)
5854 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005855 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005856 break;
5857 }
5858 }
5859 else
5860 {
5861 // If we didn't get an event that means we've timed out...
5862 // We will interrupt the process here. Depending on what we were asked to do we will
5863 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005864
Sean Callanana46ec452012-07-11 21:31:24 +00005865 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005866 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005867 {
Jim Ingham0161b492013-02-09 01:29:05 +00005868 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005869 {
5870 if (timeout_usec != 0)
5871 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005872 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005873 "running for %" PRIu32 " usec with all threads enabled.",
5874 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005875 }
5876 else
5877 {
5878 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005879 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005880 }
5881 }
Sean Callanana46ec452012-07-11 21:31:24 +00005882 else
5883 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005884 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005885 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005886 }
5887 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005888 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005889 "abandoning execution.",
5890 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005891 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005892
Jim Ingham0161b492013-02-09 01:29:05 +00005893 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5894 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5895 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5896 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5897 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005898
Jim Ingham0161b492013-02-09 01:29:05 +00005899 bool back_to_top = true;
5900 uint32_t try_halt_again = 0;
5901 bool do_halt = true;
5902 const uint32_t num_retries = 5;
5903 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005904 {
Jim Ingham0161b492013-02-09 01:29:05 +00005905 Error halt_error;
5906 if (do_halt)
5907 {
5908 if (log)
5909 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5910 halt_error = Halt();
5911 }
5912 if (halt_error.Success())
5913 {
5914 if (log)
5915 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005916
Jim Ingham0161b492013-02-09 01:29:05 +00005917 real_timeout = TimeValue::Now();
5918 real_timeout.OffsetWithMicroSeconds(500000);
5919
5920 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005921
Jim Ingham0161b492013-02-09 01:29:05 +00005922 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005923 {
Jim Ingham0161b492013-02-09 01:29:05 +00005924 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5925 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005926 {
Jim Ingham0161b492013-02-09 01:29:05 +00005927 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5928 if (stop_state == lldb::eStateStopped
5929 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5930 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005931 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005932
Jim Ingham0161b492013-02-09 01:29:05 +00005933 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005934 {
Jim Ingham0161b492013-02-09 01:29:05 +00005935 // Between the time we initiated the Halt and the time we delivered it, the process could have
5936 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005937
Jim Ingham0161b492013-02-09 01:29:05 +00005938 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5939 {
5940 if (log)
5941 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5942 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005943 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005944 back_to_top = false;
5945 break;
5946 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005947
Jim Ingham0161b492013-02-09 01:29:05 +00005948 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5949 {
5950 if (log)
5951 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5952 "Exiting wait loop.");
5953 try_halt_again++;
5954 do_halt = false;
5955 continue;
5956 }
Sean Callanana46ec452012-07-11 21:31:24 +00005957
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005958 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005959 {
5960 if (log)
5961 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005962 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005963 back_to_top = false;
5964 break;
5965 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005966
Jim Ingham0161b492013-02-09 01:29:05 +00005967 if (before_first_timeout)
5968 {
5969 // Set all the other threads to run, and return to the top of the loop, which will continue;
5970 before_first_timeout = false;
5971 thread_plan_sp->SetStopOthers (false);
5972 if (log)
5973 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005974
Jim Ingham0161b492013-02-09 01:29:05 +00005975 back_to_top = true;
5976 break;
5977 }
5978 else
5979 {
5980 // Running all threads failed, so return Interrupted.
5981 if (log)
5982 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005983 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005984 back_to_top = false;
5985 break;
5986 }
Sean Callanana46ec452012-07-11 21:31:24 +00005987 }
5988 }
5989 else
Jim Ingham0161b492013-02-09 01:29:05 +00005990 { if (log)
5991 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5992 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005993 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005994 back_to_top = false;
5995 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005996 }
5997 }
Jim Ingham0161b492013-02-09 01:29:05 +00005998 else
5999 {
6000 try_halt_again++;
6001 continue;
6002 }
Sean Callanana46ec452012-07-11 21:31:24 +00006003 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006004
Jim Ingham0161b492013-02-09 01:29:05 +00006005 if (!back_to_top || try_halt_again > num_retries)
6006 break;
6007 else
6008 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006009 }
Sean Callanana46ec452012-07-11 21:31:24 +00006010 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006011
Sean Callanana46ec452012-07-11 21:31:24 +00006012 // 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 +00006013 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006014 {
6015 StopPrivateStateThread();
6016 Error error;
6017 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006018 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006019 {
6020 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6021 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006022 if (old_state != eStateInvalid)
6023 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006024 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006025
Jim Ingham184e9812013-01-15 02:47:48 +00006026 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6027 // could happen:
6028 // 1) The execution successfully completed
6029 // 2) We hit a breakpoint, and ignore_breakpoints was true
6030 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006031 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6032 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006033
Jim Ingham8646d3c2014-05-05 02:47:44 +00006034 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006035 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006036 {
6037 thread_plan_sp->RestoreThreadState();
6038 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006039
Sean Callanana46ec452012-07-11 21:31:24 +00006040 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006041 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006042 {
6043 if (log)
6044 {
6045 StreamString s;
6046 if (event_sp)
6047 event_sp->Dump (&s);
6048 else
6049 {
6050 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6051 }
6052
6053 StreamString ts;
6054
6055 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006056
Sean Callanana46ec452012-07-11 21:31:24 +00006057 do
6058 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006059 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006060 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006061 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006062 break;
6063 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006064 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006065 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006066 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006067 break;
6068 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006069 else
Sean Callanana46ec452012-07-11 21:31:24 +00006070 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006071 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6072
6073 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006074 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006075 event_explanation = "<no event data>";
6076 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006077 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006078
Jim Inghamcfc09352012-07-27 23:57:19 +00006079 Process *process = event_data->GetProcessSP().get();
6080
6081 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006082 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006083 event_explanation = "<no process>";
6084 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006085 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006086
Jim Inghamcfc09352012-07-27 23:57:19 +00006087 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006088
Jim Inghamcfc09352012-07-27 23:57:19 +00006089 uint32_t num_threads = thread_list.GetSize();
6090 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006091
Jim Inghamcfc09352012-07-27 23:57:19 +00006092 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006093
Jim Inghamcfc09352012-07-27 23:57:19 +00006094 for (thread_index = 0;
6095 thread_index < num_threads;
6096 ++thread_index)
6097 {
6098 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006099
Jim Inghamcfc09352012-07-27 23:57:19 +00006100 if (!thread)
6101 {
6102 ts.Printf("<?> ");
6103 continue;
6104 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006105
Daniel Malead01b2952012-11-29 21:49:15 +00006106 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006107 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006108
Jim Inghamcfc09352012-07-27 23:57:19 +00006109 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006110 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006111 else
6112 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006113
Jim Inghamcfc09352012-07-27 23:57:19 +00006114 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
6115 if (stop_info_sp)
6116 {
6117 const char *stop_desc = stop_info_sp->GetDescription();
6118 if (stop_desc)
6119 ts.PutCString (stop_desc);
6120 }
6121 ts.Printf(">");
6122 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006123
Jim Inghamcfc09352012-07-27 23:57:19 +00006124 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006125 }
Sean Callanana46ec452012-07-11 21:31:24 +00006126 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006127
Jim Inghamcfc09352012-07-27 23:57:19 +00006128 if (event_explanation)
6129 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006130 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006131 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6132 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006133
Jim Inghame4483cf2013-09-27 01:13:01 +00006134 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006135 {
6136 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006137 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6138 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006139 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6140 thread_plan_sp->SetPrivate (orig_plan_private);
6141 }
6142 else
6143 {
6144 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006145 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6146 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006147 }
6148 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006149 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006150 {
6151 if (log)
6152 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006153
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006154 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006155 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006156 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006157 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006158 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006159 }
6160 else
6161 {
Sean Callanana46ec452012-07-11 21:31:24 +00006162 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006163 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006164 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006165 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006166 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006167 }
6168 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6169 {
6170 if (log)
6171 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006172 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006173 }
6174 else
6175 {
6176 if (log)
6177 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006178 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006179 {
6180 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006181 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006182 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6183 thread_plan_sp->SetPrivate (orig_plan_private);
6184 }
6185 }
6186 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006187
Sean Callanana46ec452012-07-11 21:31:24 +00006188 // Thread we ran the function in may have gone away because we ran the target
6189 // Check that it's still there, and if it is put it back in the context. Also restore the
6190 // frame in the context if it is still present.
6191 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6192 if (thread)
6193 {
6194 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6195 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006196
Sean Callanana46ec452012-07-11 21:31:24 +00006197 // Also restore the current process'es selected frame & thread, since this function calling may
6198 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006199
Sean Callanana46ec452012-07-11 21:31:24 +00006200 if (selected_tid != LLDB_INVALID_THREAD_ID)
6201 {
6202 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6203 {
6204 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006205 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006206 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006207 if (old_frame_sp)
6208 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006209 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006210 }
6211 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006212
Sean Callanana46ec452012-07-11 21:31:24 +00006213 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006214
Sean Callanana46ec452012-07-11 21:31:24 +00006215 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006216 {
Sean Callanana46ec452012-07-11 21:31:24 +00006217 if (log)
6218 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6219 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006220 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006221
Jim Inghamf48169b2010-11-30 02:22:11 +00006222 return return_value;
6223}
6224
6225const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006226Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006227{
6228 const char *result_name;
6229
6230 switch (result)
6231 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006232 case eExpressionCompleted:
6233 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006234 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006235 case eExpressionDiscarded:
6236 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006237 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006238 case eExpressionInterrupted:
6239 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006240 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006241 case eExpressionHitBreakpoint:
6242 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006243 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006244 case eExpressionSetupError:
6245 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006246 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006247 case eExpressionParseError:
6248 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006249 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006250 case eExpressionResultUnavailable:
6251 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006252 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006253 case eExpressionTimedOut:
6254 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006255 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006256 case eExpressionStoppedForDebug:
6257 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006258 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006259 }
6260 return result_name;
6261}
6262
Greg Clayton7260f622011-04-18 08:33:37 +00006263void
6264Process::GetStatus (Stream &strm)
6265{
6266 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006267 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006268 {
6269 if (state == eStateExited)
6270 {
6271 int exit_status = GetExitStatus();
6272 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006273 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006274 GetID(),
6275 exit_status,
6276 exit_status,
6277 exit_description ? exit_description : "");
6278 }
6279 else
6280 {
6281 if (state == eStateConnected)
6282 strm.Printf ("Connected to remote target.\n");
6283 else
Daniel Malead01b2952012-11-29 21:49:15 +00006284 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006285 }
6286 }
6287 else
6288 {
Daniel Malead01b2952012-11-29 21:49:15 +00006289 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006290 }
6291}
6292
6293size_t
6294Process::GetThreadStatus (Stream &strm,
6295 bool only_threads_with_stop_reason,
6296 uint32_t start_frame,
6297 uint32_t num_frames,
6298 uint32_t num_frames_with_source)
6299{
6300 size_t num_thread_infos_dumped = 0;
6301
Jim Ingham4a65fb12014-03-07 11:20:03 +00006302 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6303 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6304 // ID's, and look them up one by one:
6305
6306 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006307 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006308 //Scope for thread list locker;
6309 {
6310 Mutex::Locker locker (GetThreadList().GetMutex());
6311 ThreadList &curr_thread_list = GetThreadList();
6312 num_threads = curr_thread_list.GetSize();
6313 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006314 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006315 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006316 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006317 }
6318
Greg Clayton7260f622011-04-18 08:33:37 +00006319 for (uint32_t i = 0; i < num_threads; i++)
6320 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006321 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006322 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006323 {
6324 if (only_threads_with_stop_reason)
6325 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006326 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006327 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006328 continue;
6329 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006330 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006331 start_frame,
6332 num_frames,
6333 num_frames_with_source);
6334 ++num_thread_infos_dumped;
6335 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006336 else
6337 {
6338 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6339 if (log)
6340 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6341
6342 }
Greg Clayton7260f622011-04-18 08:33:37 +00006343 }
6344 return num_thread_infos_dumped;
6345}
6346
Greg Claytona9f40ad2012-02-22 04:37:26 +00006347void
6348Process::AddInvalidMemoryRegion (const LoadRange &region)
6349{
6350 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6351}
6352
6353bool
6354Process::RemoveInvalidMemoryRange (const LoadRange &region)
6355{
6356 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6357}
6358
Jim Ingham372787f2012-04-07 00:00:41 +00006359void
6360Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6361{
6362 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6363}
6364
6365bool
6366Process::RunPreResumeActions ()
6367{
6368 bool result = true;
6369 while (!m_pre_resume_actions.empty())
6370 {
6371 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6372 m_pre_resume_actions.pop_back();
6373 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006374 if (result == true)
6375 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006376 }
6377 return result;
6378}
6379
6380void
6381Process::ClearPreResumeActions ()
6382{
6383 m_pre_resume_actions.clear();
6384}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006385
Zachary Turner93749ab2015-03-03 21:51:25 +00006386ProcessRunLock &
6387Process::GetRunLock()
6388{
6389 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6390 return m_private_run_lock;
6391 else
6392 return m_public_run_lock;
6393}
6394
Greg Claytonfa559e52012-05-18 02:38:05 +00006395void
6396Process::Flush ()
6397{
6398 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006399 m_extended_thread_list.Flush();
6400 m_extended_thread_stop_id = 0;
6401 m_queue_list.Clear();
6402 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006403}
Greg Clayton90ba8112012-12-05 00:16:59 +00006404
6405void
6406Process::DidExec ()
6407{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006408 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6409 if (log)
6410 log->Printf ("Process::%s()", __FUNCTION__);
6411
Greg Clayton90ba8112012-12-05 00:16:59 +00006412 Target &target = GetTarget();
6413 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006414 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006415 m_dynamic_checkers_ap.reset();
6416 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006417 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006418 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006419 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006420 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006421 m_image_tokens.clear();
6422 m_allocated_memory_cache.Clear();
6423 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006424 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006425 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006426 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006427 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006428 DoDidExec();
6429 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006430 // Flush the process (threads and all stack frames) after running CompleteAttach()
6431 // in case the dynamic loader loaded things in new locations.
6432 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006433
6434 // After we figure out what was loaded/unloaded in CompleteAttach,
6435 // we need to let the target know so it can do any cleanup it needs to.
6436 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006437}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006438
Jim Ingham1460e4b2014-01-10 23:46:59 +00006439addr_t
6440Process::ResolveIndirectFunction(const Address *address, Error &error)
6441{
6442 if (address == nullptr)
6443 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006444 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006445 return LLDB_INVALID_ADDRESS;
6446 }
6447
6448 addr_t function_addr = LLDB_INVALID_ADDRESS;
6449
6450 addr_t addr = address->GetLoadAddress(&GetTarget());
6451 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6452 if (iter != m_resolved_indirect_addresses.end())
6453 {
6454 function_addr = (*iter).second;
6455 }
6456 else
6457 {
6458 if (!InferiorCall(this, address, function_addr))
6459 {
6460 Symbol *symbol = address->CalculateSymbolContextSymbol();
6461 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6462 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6463 function_addr = LLDB_INVALID_ADDRESS;
6464 }
6465 else
6466 {
6467 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6468 }
6469 }
6470 return function_addr;
6471}
6472
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006473void
6474Process::ModulesDidLoad (ModuleList &module_list)
6475{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006476 SystemRuntime *sys_runtime = GetSystemRuntime();
6477 if (sys_runtime)
6478 {
6479 sys_runtime->ModulesDidLoad (module_list);
6480 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006481
Kuba Breckaafdf8422014-10-10 23:43:03 +00006482 GetJITLoaders().ModulesDidLoad (module_list);
6483
6484 // Give runtimes a chance to be created.
6485 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6486
6487 // Tell runtimes about new modules.
6488 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6489 {
6490 InstrumentationRuntimeSP runtime = pos->second;
6491 runtime->ModulesDidLoad(module_list);
6492 }
6493
Greg Clayton35ca64b2015-04-16 17:13:34 +00006494 // Let any language runtimes we have already created know
6495 // about the modules that loaded.
6496
6497 // Iterate over a copy of this language runtime list in case
6498 // the language runtime ModulesDidLoad somehow causes the language
6499 // riuntime to be unloaded.
6500 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6501 for (const auto &pair: language_runtimes)
6502 {
6503 // We must check language_runtime_sp to make sure it is not
6504 // NULL as we might cache the fact that we didn't have a
6505 // language runtime for a language.
6506 LanguageRuntimeSP language_runtime_sp = pair.second;
6507 if (language_runtime_sp)
6508 language_runtime_sp->ModulesDidLoad(module_list);
6509 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006510}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006511
6512ThreadCollectionSP
6513Process::GetHistoryThreads(lldb::addr_t addr)
6514{
6515 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006516
Kuba Breckaa51ea382014-09-06 01:33:13 +00006517 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6518
6519 if (! memory_history.get()) {
6520 return threads;
6521 }
6522
6523 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6524
6525 return threads;
6526}
Kuba Brecka63927542014-10-11 01:59:32 +00006527
6528InstrumentationRuntimeSP
6529Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6530{
6531 InstrumentationRuntimeCollection::iterator pos;
6532 pos = m_instrumentation_runtimes.find (type);
6533 if (pos == m_instrumentation_runtimes.end())
6534 {
6535 return InstrumentationRuntimeSP();
6536 }
6537 else
6538 return (*pos).second;
6539}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006540
6541bool
6542Process::GetModuleSpec(const FileSpec& module_file_spec,
6543 const ArchSpec& arch,
6544 ModuleSpec& module_spec)
6545{
6546 module_spec.Clear();
6547 return false;
6548}