blob: e634c1d53184b39735ac7607ca4e0e380d5014b6 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include "lldb/Breakpoint/StoppointCallbackContext.h"
12#include "lldb/Breakpoint/BreakpointLocation.h"
13#include "lldb/Core/Event.h"
14#include "lldb/Core/Debugger.h"
15#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000016#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000017#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000020#include "lldb/Core/StreamFile.h"
Jim Ingham151c0322015-09-15 21:13:50 +000021#include "lldb/Expression/UserExpression.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000022#include "lldb/Expression/IRDynamicChecks.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000023#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000024#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000026#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000027#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000028#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000029#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000031#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000032#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000033#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000035#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000036#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000037#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000038#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000039#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000040#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000041#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000042#include "lldb/Target/LanguageRuntime.h"
43#include "lldb/Target/CPPLanguageRuntime.h"
44#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000045#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000047#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000048#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Target/Target.h"
50#include "lldb/Target/TargetList.h"
51#include "lldb/Target/Thread.h"
52#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000053#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000054#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000055#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000056#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057
58using namespace lldb;
59using namespace lldb_private;
60
Greg Clayton67cc0632012-08-22 17:17:09 +000061
62// Comment out line below to disable memory caching, overriding the process setting
63// target.process.disable-memory-cache
64#define ENABLE_MEMORY_CACHING
65
66#ifdef ENABLE_MEMORY_CACHING
67#define DISABLE_MEM_CACHE_DEFAULT false
68#else
69#define DISABLE_MEM_CACHE_DEFAULT true
70#endif
71
72class ProcessOptionValueProperties : public OptionValueProperties
73{
74public:
75 ProcessOptionValueProperties (const ConstString &name) :
76 OptionValueProperties (name)
77 {
78 }
79
80 // This constructor is used when creating ProcessOptionValueProperties when it
81 // is part of a new lldb_private::Process instance. It will copy all current
82 // global property values as needed
83 ProcessOptionValueProperties (ProcessProperties *global_properties) :
84 OptionValueProperties(*global_properties->GetValueProperties())
85 {
86 }
87
88 virtual const Property *
89 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
90 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000091 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000092 // try and grab the setting from the current process if there is one. Else we just
93 // use the one from this instance.
94 if (exe_ctx)
95 {
96 Process *process = exe_ctx->GetProcessPtr();
97 if (process)
98 {
99 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
100 if (this != instance_properties)
101 return instance_properties->ProtectedGetPropertyAtIndex (idx);
102 }
103 }
104 return ProtectedGetPropertyAtIndex (idx);
105 }
106};
107
108static PropertyDefinition
109g_properties[] =
110{
111 { "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 +0000112 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
113 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000114 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
115 { "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 +0000116 { "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 +0000117 { "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 +0000118 { "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 +0000119 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Jason Molendaef7d6412015-08-06 03:27:10 +0000120 { "optimization-warnings" , OptionValue::eTypeBoolean, false, true, NULL, NULL, "If true, warn when stopped in code that is optimized where stepping and variable availability may not behave as expected." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000121 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
122};
123
124enum {
125 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000126 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000127 ePropertyIgnoreBreakpointsInExpressions,
128 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000129 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000130 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000131 ePropertyDetachKeepsStopped,
Jason Molendaef7d6412015-08-06 03:27:10 +0000132 ePropertyMemCacheLineSize,
133 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000134};
135
Greg Clayton332e8b12015-01-13 21:13:08 +0000136ProcessProperties::ProcessProperties (lldb_private::Process *process) :
137 Properties (),
138 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000139{
Greg Clayton332e8b12015-01-13 21:13:08 +0000140 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000141 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000142 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000143 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
144 m_collection_sp->Initialize(g_properties);
145 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000146 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000147 true,
148 Thread::GetGlobalProperties()->GetValueProperties());
149 }
150 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000151 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000152 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000153 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
154 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000155}
156
157ProcessProperties::~ProcessProperties()
158{
159}
160
Greg Clayton332e8b12015-01-13 21:13:08 +0000161void
162ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
163{
164 ProcessProperties *properties = (ProcessProperties *)baton;
165 if (properties->m_process)
166 properties->m_process->LoadOperatingSystemPlugin(true);
167}
168
Greg Clayton67cc0632012-08-22 17:17:09 +0000169bool
170ProcessProperties::GetDisableMemoryCache() const
171{
172 const uint32_t idx = ePropertyDisableMemCache;
173 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
174}
175
Jason Molendaf0340c92014-09-03 22:30:54 +0000176uint64_t
177ProcessProperties::GetMemoryCacheLineSize() const
178{
179 const uint32_t idx = ePropertyMemCacheLineSize;
180 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
181}
182
Greg Clayton67cc0632012-08-22 17:17:09 +0000183Args
184ProcessProperties::GetExtraStartupCommands () const
185{
186 Args args;
187 const uint32_t idx = ePropertyExtraStartCommand;
188 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
189 return args;
190}
191
192void
193ProcessProperties::SetExtraStartupCommands (const Args &args)
194{
195 const uint32_t idx = ePropertyExtraStartCommand;
196 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
197}
198
Greg Claytonc9d645d2012-10-18 22:40:37 +0000199FileSpec
200ProcessProperties::GetPythonOSPluginPath () const
201{
202 const uint32_t idx = ePropertyPythonOSPluginPath;
203 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
204}
205
206void
207ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
208{
209 const uint32_t idx = ePropertyPythonOSPluginPath;
210 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
211}
212
Jim Ingham184e9812013-01-15 02:47:48 +0000213
214bool
215ProcessProperties::GetIgnoreBreakpointsInExpressions () const
216{
217 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
218 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
219}
220
221void
222ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
223{
224 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
225 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
226}
227
228bool
229ProcessProperties::GetUnwindOnErrorInExpressions () const
230{
231 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
232 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
233}
234
235void
236ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
237{
238 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
239 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
240}
241
Jim Ingham29950772013-01-26 02:19:28 +0000242bool
243ProcessProperties::GetStopOnSharedLibraryEvents () const
244{
245 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
246 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
247}
248
249void
250ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
251{
252 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
253 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
254}
255
Jim Inghamacff8952013-05-02 00:27:30 +0000256bool
257ProcessProperties::GetDetachKeepsStopped () const
258{
259 const uint32_t idx = ePropertyDetachKeepsStopped;
260 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
261}
262
263void
264ProcessProperties::SetDetachKeepsStopped (bool stop)
265{
266 const uint32_t idx = ePropertyDetachKeepsStopped;
267 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
268}
269
Jason Molendaef7d6412015-08-06 03:27:10 +0000270bool
271ProcessProperties::GetWarningsOptimization () const
272{
273 const uint32_t idx = ePropertyWarningOptimization;
274 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
275}
276
Greg Clayton32e0a752011-03-30 18:16:51 +0000277void
Greg Clayton8b82f082011-04-12 05:54:46 +0000278ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000279{
280 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000281 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000282 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000283
284 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000285 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000286
287 if (m_executable)
288 {
289 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
290 s.PutCString (" file = ");
291 m_executable.Dump(&s);
292 s.EOL();
293 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000294 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000295 if (argc > 0)
296 {
297 for (uint32_t i=0; i<argc; i++)
298 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000300 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000301 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000302 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000303 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000304 }
305 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000306
307 const uint32_t envc = m_environment.GetArgumentCount();
308 if (envc > 0)
309 {
310 for (uint32_t i=0; i<envc; i++)
311 {
312 const char *env = m_environment.GetArgumentAtIndex(i);
313 if (i < 10)
314 s.Printf (" env[%u] = %s\n", i, env);
315 else
316 s.Printf ("env[%u] = %s\n", i, env);
317 }
318 }
319
Todd Fiala7df337f2015-10-13 23:41:19 +0000320 if (m_arch.IsValid())
321 {
322 s.Printf (" arch = ");
323 m_arch.DumpTriple(s);
324 s.EOL();
325 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000326
Greg Clayton8b82f082011-04-12 05:54:46 +0000327 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000328 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000329 cstr = platform->GetUserName (m_uid);
330 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000331 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000332 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000333 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000334 cstr = platform->GetGroupName (m_gid);
335 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000336 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000338 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000339 cstr = platform->GetUserName (m_euid);
340 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000341 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000343 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000344 cstr = platform->GetGroupName (m_egid);
345 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000346 }
347}
348
349void
Greg Clayton8b82f082011-04-12 05:54:46 +0000350ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000351{
Greg Clayton8b82f082011-04-12 05:54:46 +0000352 const char *label;
353 if (show_args || verbose)
354 label = "ARGUMENTS";
355 else
356 label = "NAME";
357
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000358 if (verbose)
359 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000360 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
362 }
363 else
364 {
Jim Ingham368ac222014-08-15 17:05:27 +0000365 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
366 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000367 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000368}
369
370void
Greg Clayton8b82f082011-04-12 05:54:46 +0000371ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000372{
373 if (m_pid != LLDB_INVALID_PROCESS_ID)
374 {
375 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000376 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000377
Todd Fiala7df337f2015-10-13 23:41:19 +0000378 StreamString arch_strm;
379 if (m_arch.IsValid())
380 m_arch.DumpTriple(arch_strm);
381
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000382 if (verbose)
383 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000384 cstr = platform->GetUserName (m_uid);
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_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000389
Greg Clayton8b82f082011-04-12 05:54:46 +0000390 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000391 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
392 s.Printf ("%-10s ", cstr);
393 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000394 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000395
Greg Clayton8b82f082011-04-12 05:54:46 +0000396 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000397 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
398 s.Printf ("%-10s ", cstr);
399 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000400 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000401
Greg Clayton8b82f082011-04-12 05:54:46 +0000402 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000403 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
404 s.Printf ("%-10s ", cstr);
405 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000406 s.Printf ("%-10u ", m_egid);
Todd Fiala7df337f2015-10-13 23:41:19 +0000407
408 s.Printf ("%-24s ", arch_strm.GetString().c_str());
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000409 }
410 else
411 {
Jim Ingham368ac222014-08-15 17:05:27 +0000412 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000413 platform->GetUserName (m_euid),
Todd Fiala7df337f2015-10-13 23:41:19 +0000414 arch_strm.GetString().c_str());
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000415 }
416
Greg Clayton8b82f082011-04-12 05:54:46 +0000417 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000418 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000419 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000420 if (argc > 0)
421 {
422 for (uint32_t i=0; i<argc; i++)
423 {
424 if (i > 0)
425 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000426 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000427 }
428 }
429 }
430 else
431 {
432 s.PutCString (GetName());
433 }
434
435 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000436 }
437}
438
Greg Clayton8b82f082011-04-12 05:54:46 +0000439Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000440ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000441{
442 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000443 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000444
445 switch (short_option)
446 {
447 case 's': // Stop at program entry point
448 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
449 break;
450
Greg Clayton8b82f082011-04-12 05:54:46 +0000451 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000452 {
453 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000454 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000455 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000456 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000457 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000458
459 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000460 {
461 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000462 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000463 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000464 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000465 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000466
467 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000468 {
469 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000470 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000471 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000472 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000473 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000474
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 case 'p': // Process plug-in name
476 launch_info.SetProcessPluginName (option_arg);
477 break;
478
479 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000480 {
481 FileAction action;
Zachary Turner4eff2d32015-10-14 21:37:36 +0000482 const FileSpec dev_null{FileSystem::DEV_NULL, false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000483 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000484 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000485 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000486 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000487 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000488 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000489 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000490 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000491
492 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000493 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 break;
495
496 case 't': // Open process in new terminal window
497 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
498 break;
499
500 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000501 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
502 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000503 break;
504
Todd Fiala51637922014-08-19 17:40:43 +0000505 case 'A': // Disable ASLR.
506 {
507 bool success;
508 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
509 if (success)
510 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
511 else
512 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000513 break;
Todd Fiala51637922014-08-19 17:40:43 +0000514 }
515
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000516 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000517 {
518 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000519 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000520 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000521 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000522 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000523 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000524 break;
525 }
526
Todd Fiala51637922014-08-19 17:40:43 +0000527 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000528 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000529 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000530 else
Zachary Turner10687b02014-10-20 17:46:43 +0000531 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000532 break;
533
Greg Clayton8b82f082011-04-12 05:54:46 +0000534 case 'v':
535 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
536 break;
537
538 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000539 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000540 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000541 }
542 return error;
543}
544
545OptionDefinition
546ProcessLaunchCommandOptions::g_option_table[] =
547{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000548{ 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 +0000549{ 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 +0000550{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
551{ 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."},
552{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
553{ 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 +0000554{ 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 +0000555
Zachary Turnerd37221d2014-07-09 16:31:49 +0000556{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
557{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
558{ 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 +0000559
Zachary Turnerd37221d2014-07-09 16:31:49 +0000560{ 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 +0000561
Zachary Turnerd37221d2014-07-09 16:31:49 +0000562{ 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 +0000563{ 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 +0000564{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000565};
566
567
568
569bool
570ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000571{
572 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
573 return true;
574 const char *match_name = m_match_info.GetName();
575 if (!match_name)
576 return true;
577
578 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
579}
580
581bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000582ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000583{
584 if (!NameMatches (proc_info.GetName()))
585 return false;
586
587 if (m_match_info.ProcessIDIsValid() &&
588 m_match_info.GetProcessID() != proc_info.GetProcessID())
589 return false;
590
591 if (m_match_info.ParentProcessIDIsValid() &&
592 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
593 return false;
594
Greg Clayton8b82f082011-04-12 05:54:46 +0000595 if (m_match_info.UserIDIsValid () &&
596 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000597 return false;
598
Greg Clayton8b82f082011-04-12 05:54:46 +0000599 if (m_match_info.GroupIDIsValid () &&
600 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000601 return false;
602
603 if (m_match_info.EffectiveUserIDIsValid () &&
604 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
605 return false;
606
607 if (m_match_info.EffectiveGroupIDIsValid () &&
608 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
609 return false;
610
611 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000612 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000613 return false;
614 return true;
615}
616
617bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000618ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000619{
620 if (m_name_match_type != eNameMatchIgnore)
621 return false;
622
623 if (m_match_info.ProcessIDIsValid())
624 return false;
625
626 if (m_match_info.ParentProcessIDIsValid())
627 return false;
628
Greg Clayton8b82f082011-04-12 05:54:46 +0000629 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000630 return false;
631
Greg Clayton8b82f082011-04-12 05:54:46 +0000632 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000633 return false;
634
635 if (m_match_info.EffectiveUserIDIsValid ())
636 return false;
637
638 if (m_match_info.EffectiveGroupIDIsValid ())
639 return false;
640
641 if (m_match_info.GetArchitecture().IsValid())
642 return false;
643
644 if (m_match_all_users)
645 return false;
646
647 return true;
648
649}
650
651void
Greg Clayton8b82f082011-04-12 05:54:46 +0000652ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000653{
654 m_match_info.Clear();
655 m_name_match_type = eNameMatchIgnore;
656 m_match_all_users = false;
657}
Greg Clayton58be07b2011-01-07 06:08:19 +0000658
Greg Claytonc3776bf2012-02-09 06:16:32 +0000659ProcessSP
Zachary Turner7529df92015-09-01 20:02:29 +0000660Process::FindPlugin (lldb::TargetSP target_sp, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661{
Greg Clayton949e8222013-01-16 17:29:04 +0000662 static uint32_t g_process_unique_id = 0;
663
Greg Claytonc3776bf2012-02-09 06:16:32 +0000664 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 ProcessCreateInstance create_callback = NULL;
666 if (plugin_name)
667 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000668 ConstString const_plugin_name(plugin_name);
669 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 if (create_callback)
671 {
Zachary Turner7529df92015-09-01 20:02:29 +0000672 process_sp = create_callback(target_sp, listener, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000673 if (process_sp)
674 {
Zachary Turner7529df92015-09-01 20:02:29 +0000675 if (process_sp->CanDebug(target_sp, true))
Greg Clayton949e8222013-01-16 17:29:04 +0000676 {
677 process_sp->m_process_unique_id = ++g_process_unique_id;
678 }
679 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000680 process_sp.reset();
681 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682 }
683 }
684 else
685 {
Greg Claytonc982c762010-07-09 20:39:50 +0000686 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 {
Zachary Turner7529df92015-09-01 20:02:29 +0000688 process_sp = create_callback(target_sp, listener, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000689 if (process_sp)
690 {
Zachary Turner7529df92015-09-01 20:02:29 +0000691 if (process_sp->CanDebug(target_sp, false))
Greg Clayton949e8222013-01-16 17:29:04 +0000692 {
693 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000694 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000695 }
696 else
697 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000698 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 }
700 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000701 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702}
703
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000704ConstString &
705Process::GetStaticBroadcasterClass ()
706{
707 static ConstString class_name ("lldb.process");
708 return class_name;
709}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710
711//----------------------------------------------------------------------
712// Process constructor
713//----------------------------------------------------------------------
Zachary Turner7529df92015-09-01 20:02:29 +0000714Process::Process(lldb::TargetSP target_sp, Listener &listener) :
715 Process(target_sp, listener, UnixSignals::Create(HostInfo::GetArchitecture()))
Todd Fiala4ceced32014-08-29 17:35:57 +0000716{
717 // This constructor just delegates to the full Process constructor,
718 // defaulting to using the Host's UnixSignals.
719}
720
Zachary Turner7529df92015-09-01 20:02:29 +0000721Process::Process(lldb::TargetSP target_sp, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000722 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 UserID (LLDB_INVALID_PROCESS_ID),
Zachary Turner7529df92015-09-01 20:02:29 +0000724 Broadcaster (&(target_sp->GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
725 m_target_sp (target_sp),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726 m_public_state (eStateUnloaded),
727 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000728 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
729 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 m_private_state_listener ("lldb.process.internal_state_listener"),
731 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000732 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000733 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000735 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736 m_exit_status (-1),
737 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000738 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000739 m_thread_mutex (Mutex::eMutexTypeRecursive),
740 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000742 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000743 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000744 m_queue_list (this),
745 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000747 m_image_tokens (),
748 m_listener (listener),
749 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000750 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000751 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000752 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000753 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000754 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000755 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000756 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000757 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000758 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000759 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
760 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32 +0000761 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42 +0000762 m_memory_cache (*this),
763 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000764 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000765 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000766 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000767 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000768 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000769 m_stop_info_override_callback (NULL),
Greg Claytonc00ca312015-04-02 18:44:58 +0000770 m_finalizing (false),
771 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000772 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000773 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000774 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000775 m_destroy_in_process (false),
Ewan Crawford90ff7912015-07-14 10:56:58 +0000776 m_can_interpret_function_calls(false),
Jason Molendaef7d6412015-08-06 03:27:10 +0000777 m_warnings_issued (),
Jason Molenda69b6b632013-03-05 03:33:59 +0000778 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000780 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000781
Greg Clayton5160ce52013-03-27 23:08:40 +0000782 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000784 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785
Todd Fiala4ceced32014-08-29 17:35:57 +0000786 if (!m_unix_signals_sp)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000787 m_unix_signals_sp = std::make_shared<UnixSignals>();
Todd Fiala4ceced32014-08-29 17:35:57 +0000788
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000789 SetEventName (eBroadcastBitStateChanged, "state-changed");
790 SetEventName (eBroadcastBitInterrupt, "interrupt");
791 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
792 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000793 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000794
Greg Clayton35a4cc52012-10-29 20:52:08 +0000795 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
796 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
797 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
798
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 listener.StartListeningForEvents (this,
800 eBroadcastBitStateChanged |
801 eBroadcastBitInterrupt |
802 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000803 eBroadcastBitSTDERR |
804 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805
806 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000807 eBroadcastBitStateChanged |
808 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809
810 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
811 eBroadcastInternalStateControlStop |
812 eBroadcastInternalStateControlPause |
813 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000814 // We need something valid here, even if just the default UnixSignalsSP.
815 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816}
817
818//----------------------------------------------------------------------
819// Destructor
820//----------------------------------------------------------------------
821Process::~Process()
822{
Greg Clayton5160ce52013-03-27 23:08:40 +0000823 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000825 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000827
828 // ThreadList::Clear() will try to acquire this process's mutex, so
829 // explicitly clear the thread list here to ensure that the mutex
830 // is not destroyed before the thread list.
831 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832}
833
Greg Clayton67cc0632012-08-22 17:17:09 +0000834const ProcessPropertiesSP &
835Process::GetGlobalProperties()
836{
837 static ProcessPropertiesSP g_settings_sp;
838 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000839 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000840 return g_settings_sp;
841}
842
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843void
844Process::Finalize()
845{
Greg Claytonc00ca312015-04-02 18:44:58 +0000846 m_finalizing = true;
847
Ilia Kc7efd562015-03-26 07:40:40 +0000848 // Destroy this process if needed
849 switch (GetPrivateState())
850 {
851 case eStateConnected:
852 case eStateAttaching:
853 case eStateLaunching:
854 case eStateStopped:
855 case eStateRunning:
856 case eStateStepping:
857 case eStateCrashed:
858 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000859 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000860 break;
861
862 case eStateInvalid:
863 case eStateUnloaded:
864 case eStateDetached:
865 case eStateExited:
866 break;
867 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000868
Greg Clayton1ed54f52011-10-01 00:45:15 +0000869 // Clear our broadcaster before we proceed with destroying
870 Broadcaster::Clear();
871
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872 // Do any cleanup needed prior to being destructed... Subclasses
873 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000874
875 // We need to destroy the loader before the derived Process class gets destroyed
876 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000877 m_dynamic_checkers_ap.reset();
878 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000879 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000880 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000881 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000882 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000883 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000884 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000885 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000886 m_queue_list.Clear();
887 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000888 std::vector<Notifications> empty_notifications;
889 m_notifications.swap(empty_notifications);
890 m_image_tokens.clear();
891 m_memory_cache.Clear();
892 m_allocated_memory_cache.Clear();
893 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000894 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000895 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000896 m_stop_info_override_callback = NULL;
Greg Clayton08765fa2015-05-28 03:24:30 +0000897 // Clear the last natural stop ID since it has a strong
898 // reference to this process
899 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000900//#ifdef LLDB_CONFIGURATION_DEBUG
901// StreamFile s(stdout, false);
902// EventSP event_sp;
903// while (m_private_state_listener.GetNextEvent(event_sp))
904// {
905// event_sp->Dump (&s);
906// s.EOL();
907// }
908//#endif
909 // We have to be very careful here as the m_private_state_listener might
910 // contain events that have ProcessSP values in them which can keep this
911 // process around forever. These events need to be cleared out.
912 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000913 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
914 m_public_run_lock.SetStopped();
915 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
916 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000917 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000918}
919
920void
921Process::RegisterNotificationCallbacks (const Notifications& callbacks)
922{
923 m_notifications.push_back(callbacks);
924 if (callbacks.initialize != NULL)
925 callbacks.initialize (callbacks.baton, this);
926}
927
928bool
929Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
930{
931 std::vector<Notifications>::iterator pos, end = m_notifications.end();
932 for (pos = m_notifications.begin(); pos != end; ++pos)
933 {
934 if (pos->baton == callbacks.baton &&
935 pos->initialize == callbacks.initialize &&
936 pos->process_state_changed == callbacks.process_state_changed)
937 {
938 m_notifications.erase(pos);
939 return true;
940 }
941 }
942 return false;
943}
944
945void
946Process::SynchronouslyNotifyStateChanged (StateType state)
947{
948 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
949 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
950 {
951 if (notification_pos->process_state_changed)
952 notification_pos->process_state_changed (notification_pos->baton, this, state);
953 }
954}
955
956// FIXME: We need to do some work on events before the general Listener sees them.
957// For instance if we are continuing from a breakpoint, we need to ensure that we do
958// the little "insert real insn, step & stop" trick. But we can't do that when the
959// event is delivered by the broadcaster - since that is done on the thread that is
960// waiting for new events, so if we needed more than one event for our handling, we would
961// stall. So instead we do it when we fetch the event off of the queue.
962//
963
964StateType
965Process::GetNextEvent (EventSP &event_sp)
966{
967 StateType state = eStateInvalid;
968
969 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
970 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
971
972 return state;
973}
974
Pavel Labath44464872015-05-27 12:40:32 +0000975void
976Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000977{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000978 // don't sync (potentially context switch) in case where there is no process IO
Pavel Labath44464872015-05-27 12:40:32 +0000979 if (! m_process_input_reader)
980 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000981
Pavel Labath44464872015-05-27 12:40:32 +0000982 TimeValue timeout = TimeValue::Now();
983 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
984 uint32_t new_iohandler_id = 0;
985 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000986
Pavel Labath44464872015-05-27 12:40:32 +0000987 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
988 if (log)
989 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 +0000990}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
992StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000993Process::WaitForProcessToStop (const TimeValue *timeout,
994 EventSP *event_sp_ptr,
995 bool wait_always,
996 Listener *hijack_listener,
997 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998{
Jim Ingham4b536182011-08-09 02:12:22 +0000999 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1000 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1001 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001002 if (event_sp_ptr)
1003 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001004 StateType state = GetState();
1005 // If we are exited or detached, we won't ever get back to any
1006 // other valid state...
1007 if (state == eStateDetached || state == eStateExited)
1008 return state;
1009
Daniel Malea9e9919f2013-10-09 16:56:28 +00001010 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1011 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001012 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
1013 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001014
1015 if (!wait_always &&
1016 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +00001017 StateIsStoppedState(GetPrivateState(), true))
1018 {
Daniel Malea9e9919f2013-10-09 16:56:28 +00001019 if (log)
1020 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1021 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001022 // We need to toggle the run lock as this won't get done in
1023 // SetPublicState() if the process is hijacked.
1024 if (hijack_listener)
1025 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001026 return state;
1027 }
1028
Jim Ingham4b536182011-08-09 02:12:22 +00001029 while (state != eStateInvalid)
1030 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001031 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001032 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001033 if (event_sp_ptr && event_sp)
1034 *event_sp_ptr = event_sp;
1035
Greg Claytondc6224e2014-10-21 01:00:42 +00001036 bool pop_process_io_handler = hijack_listener != NULL;
1037 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1038
Jim Ingham4b536182011-08-09 02:12:22 +00001039 switch (state)
1040 {
1041 case eStateCrashed:
1042 case eStateDetached:
1043 case eStateExited:
1044 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001045 // We need to toggle the run lock as this won't get done in
1046 // SetPublicState() if the process is hijacked.
1047 if (hijack_listener)
1048 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001049 return state;
1050 case eStateStopped:
1051 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1052 continue;
1053 else
Greg Clayton44d93782014-01-27 23:43:24 +00001054 {
1055 // We need to toggle the run lock as this won't get done in
1056 // SetPublicState() if the process is hijacked.
1057 if (hijack_listener)
1058 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001059 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001060 }
Jim Ingham4b536182011-08-09 02:12:22 +00001061 default:
1062 continue;
1063 }
1064 }
1065 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001066}
1067
Greg Claytondc6224e2014-10-21 01:00:42 +00001068bool
1069Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1070 Stream *stream,
1071 bool &pop_process_io_handler)
1072{
1073 const bool handle_pop = pop_process_io_handler == true;
1074
1075 pop_process_io_handler = false;
1076 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1077
1078 if (!process_sp)
1079 return false;
1080
1081 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1082 if (event_state == eStateInvalid)
1083 return false;
1084
1085 switch (event_state)
1086 {
1087 case eStateInvalid:
1088 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001089 case eStateAttaching:
1090 case eStateLaunching:
1091 case eStateStepping:
1092 case eStateDetached:
1093 {
1094 if (stream)
1095 stream->Printf ("Process %" PRIu64 " %s\n",
1096 process_sp->GetID(),
1097 StateAsCString (event_state));
1098
1099 if (event_state == eStateDetached)
1100 pop_process_io_handler = true;
1101 }
1102 break;
1103
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001104 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001105 case eStateRunning:
1106 // Don't be chatty when we run...
1107 break;
1108
1109 case eStateExited:
1110 if (stream)
1111 process_sp->GetStatus(*stream);
1112 pop_process_io_handler = true;
1113 break;
1114
1115 case eStateStopped:
1116 case eStateCrashed:
1117 case eStateSuspended:
1118 // Make sure the program hasn't been auto-restarted:
1119 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1120 {
1121 if (stream)
1122 {
1123 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1124 if (num_reasons > 0)
1125 {
1126 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1127 if (num_reasons == 1)
1128 {
1129 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1130 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1131 process_sp->GetID(),
1132 reason ? reason : "<UNKNOWN REASON>");
1133 }
1134 else
1135 {
1136 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1137 process_sp->GetID());
1138
1139
1140 for (size_t i = 0; i < num_reasons; i++)
1141 {
1142 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1143 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1144 }
1145 }
1146 }
1147 }
1148 }
1149 else
1150 {
1151 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1152 {
1153 ThreadList &thread_list = process_sp->GetThreadList();
1154 Mutex::Locker locker (thread_list.GetMutex());
1155
1156 ThreadSP curr_thread (thread_list.GetSelectedThread());
1157 ThreadSP thread;
1158 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1159 if (curr_thread)
1160 curr_thread_stop_reason = curr_thread->GetStopReason();
1161 if (!curr_thread ||
1162 !curr_thread->IsValid() ||
1163 curr_thread_stop_reason == eStopReasonInvalid ||
1164 curr_thread_stop_reason == eStopReasonNone)
1165 {
1166 // Prefer a thread that has just completed its plan over another thread as current thread.
1167 ThreadSP plan_thread;
1168 ThreadSP other_thread;
Jim Inghamce400d92015-07-08 00:06:30 +00001169
Greg Claytondc6224e2014-10-21 01:00:42 +00001170 const size_t num_threads = thread_list.GetSize();
1171 size_t i;
1172 for (i = 0; i < num_threads; ++i)
1173 {
1174 thread = thread_list.GetThreadAtIndex(i);
1175 StopReason thread_stop_reason = thread->GetStopReason();
1176 switch (thread_stop_reason)
1177 {
1178 case eStopReasonInvalid:
1179 case eStopReasonNone:
1180 break;
1181
Jim Inghamce400d92015-07-08 00:06:30 +00001182 case eStopReasonSignal:
1183 {
1184 // Don't select a signal thread if we weren't going to stop at that
1185 // signal. We have to have had another reason for stopping here, and
1186 // the user doesn't want to see this thread.
1187 uint64_t signo = thread->GetStopInfo()->GetValue();
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001188 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
Jim Inghamce400d92015-07-08 00:06:30 +00001189 {
1190 if (!other_thread)
1191 other_thread = thread;
1192 }
1193 break;
1194 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001195 case eStopReasonTrace:
1196 case eStopReasonBreakpoint:
1197 case eStopReasonWatchpoint:
Greg Claytondc6224e2014-10-21 01:00:42 +00001198 case eStopReasonException:
1199 case eStopReasonExec:
1200 case eStopReasonThreadExiting:
1201 case eStopReasonInstrumentation:
1202 if (!other_thread)
1203 other_thread = thread;
1204 break;
1205 case eStopReasonPlanComplete:
1206 if (!plan_thread)
1207 plan_thread = thread;
1208 break;
1209 }
1210 }
1211 if (plan_thread)
1212 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1213 else if (other_thread)
1214 thread_list.SetSelectedThreadByID (other_thread->GetID());
1215 else
1216 {
1217 if (curr_thread && curr_thread->IsValid())
1218 thread = curr_thread;
1219 else
1220 thread = thread_list.GetThreadAtIndex(0);
1221
1222 if (thread)
1223 thread_list.SetSelectedThreadByID (thread->GetID());
1224 }
1225 }
1226 }
1227 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1228 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1229 // have a hard time restarting the process.
1230 if (stream)
1231 {
1232 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1233 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1234 {
1235 const bool only_threads_with_stop_reason = true;
1236 const uint32_t start_frame = 0;
1237 const uint32_t num_frames = 1;
1238 const uint32_t num_frames_with_source = 1;
1239 process_sp->GetStatus(*stream);
1240 process_sp->GetThreadStatus (*stream,
1241 only_threads_with_stop_reason,
1242 start_frame,
1243 num_frames,
1244 num_frames_with_source);
1245 }
1246 else
1247 {
1248 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1249 if (target_idx != UINT32_MAX)
1250 stream->Printf ("Target %d: (", target_idx);
1251 else
1252 stream->Printf ("Target <unknown index>: (");
1253 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1254 stream->Printf (") stopped.\n");
1255 }
1256 }
1257
1258 // Pop the process IO handler
1259 pop_process_io_handler = true;
1260 }
1261 break;
1262 }
1263
1264 if (handle_pop && pop_process_io_handler)
1265 process_sp->PopProcessIOHandler();
1266
1267 return true;
1268}
1269
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270
1271StateType
1272Process::WaitForState
1273(
1274 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001275 const StateType *match_states,
1276 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001277)
1278{
1279 EventSP event_sp;
1280 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001281 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001282 while (state != eStateInvalid)
1283 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001284 // If we are exited or detached, we won't ever get back to any
1285 // other valid state...
1286 if (state == eStateDetached || state == eStateExited)
1287 return state;
1288
Greg Clayton44d93782014-01-27 23:43:24 +00001289 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001290
1291 for (i=0; i<num_match_states; ++i)
1292 {
1293 if (match_states[i] == state)
1294 return state;
1295 }
1296 }
1297 return state;
1298}
1299
Jim Ingham30f9b212010-10-11 23:53:14 +00001300bool
1301Process::HijackProcessEvents (Listener *listener)
1302{
1303 if (listener != NULL)
1304 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001305 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001306 }
1307 else
1308 return false;
1309}
1310
1311void
1312Process::RestoreProcessEvents ()
1313{
1314 RestoreBroadcaster();
1315}
1316
Jim Ingham0f16e732011-02-08 05:20:59 +00001317bool
1318Process::HijackPrivateProcessEvents (Listener *listener)
1319{
1320 if (listener != NULL)
1321 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001322 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001323 }
1324 else
1325 return false;
1326}
1327
1328void
1329Process::RestorePrivateProcessEvents ()
1330{
1331 m_private_state_broadcaster.RestoreBroadcaster();
1332}
1333
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001334StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001335Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001336{
Greg Clayton5160ce52013-03-27 23:08:40 +00001337 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338
1339 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001340 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1341 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342
Greg Clayton44d93782014-01-27 23:43:24 +00001343 Listener *listener = hijack_listener;
1344 if (listener == NULL)
1345 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001348 if (listener->WaitForEventForBroadcasterWithType (timeout,
1349 this,
1350 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1351 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001352 {
1353 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1354 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1355 else if (log)
1356 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1357 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001358
1359 if (log)
1360 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001361 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001362 StateAsCString(state));
1363 return state;
1364}
1365
1366Event *
1367Process::PeekAtStateChangedEvents ()
1368{
Greg Clayton5160ce52013-03-27 23:08:40 +00001369 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370
1371 if (log)
1372 log->Printf ("Process::%s...", __FUNCTION__);
1373
1374 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001375 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1376 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001377 if (log)
1378 {
1379 if (event_ptr)
1380 {
1381 log->Printf ("Process::%s (event_ptr) => %s",
1382 __FUNCTION__,
1383 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1384 }
1385 else
1386 {
1387 log->Printf ("Process::%s no events found",
1388 __FUNCTION__);
1389 }
1390 }
1391 return event_ptr;
1392}
1393
1394StateType
1395Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1396{
Greg Clayton5160ce52013-03-27 23:08:40 +00001397 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398
1399 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001400 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1401 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402
1403 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001404 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1405 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001406 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001407 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001408 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1409 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410
1411 // This is a bit of a hack, but when we wait here we could very well return
1412 // to the command-line, and that could disable the log, which would render the
1413 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001415 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1416 __FUNCTION__, static_cast<const void *>(timeout),
1417 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 return state;
1419}
1420
1421bool
1422Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1423{
Greg Clayton5160ce52013-03-27 23:08:40 +00001424 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425
1426 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001427 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1428 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001429
1430 if (control_only)
1431 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1432 else
1433 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1434}
1435
1436bool
1437Process::IsRunning () const
1438{
1439 return StateIsRunningState (m_public_state.GetValue());
1440}
1441
1442int
1443Process::GetExitStatus ()
1444{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001445 Mutex::Locker locker (m_exit_status_mutex);
1446
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001447 if (m_public_state.GetValue() == eStateExited)
1448 return m_exit_status;
1449 return -1;
1450}
1451
Greg Clayton85851dd2010-12-04 00:10:17 +00001452
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001453const char *
1454Process::GetExitDescription ()
1455{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001456 Mutex::Locker locker (m_exit_status_mutex);
1457
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001458 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1459 return m_exit_string.c_str();
1460 return NULL;
1461}
1462
Greg Clayton6779606a2011-01-22 23:43:18 +00001463bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464Process::SetExitStatus (int status, const char *cstr)
1465{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001466 // Use a mutex to protect setting the exit status.
1467 Mutex::Locker locker (m_exit_status_mutex);
1468
Greg Clayton5160ce52013-03-27 23:08:40 +00001469 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001470 if (log)
1471 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1472 status, status,
1473 cstr ? "\"" : "",
1474 cstr ? cstr : "NULL",
1475 cstr ? "\"" : "");
1476
Greg Clayton6779606a2011-01-22 23:43:18 +00001477 // We were already in the exited state
1478 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001479 {
Greg Clayton385d6032011-01-26 23:47:29 +00001480 if (log)
1481 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001482 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001483 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001484
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001485 m_exit_status = status;
1486 if (cstr)
1487 m_exit_string = cstr;
1488 else
1489 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490
Pavel Labatha9a43372015-09-03 09:30:17 +00001491 // When we exit, we don't need the input reader anymore
Greg Clayton5df78fa2015-05-23 03:54:53 +00001492 if (m_process_input_reader)
1493 {
1494 m_process_input_reader->SetIsDone(true);
1495 m_process_input_reader->Cancel();
1496 m_process_input_reader.reset();
1497 }
Greg Clayton10177aa2010-12-08 05:08:21 +00001498
Greg Clayton08765fa2015-05-28 03:24:30 +00001499 // Clear the last natural stop ID since it has a strong
1500 // reference to this process
1501 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1502
Greg Clayton6779606a2011-01-22 23:43:18 +00001503 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001504
1505 // Allow subclasses to do some cleanup
1506 DidExit ();
1507
Greg Clayton6779606a2011-01-22 23:43:18 +00001508 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001509}
1510
1511// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001512// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001513// found in the global target list (we want to be completely sure that the
1514// lldb_private::Process doesn't go away before we can deliver the signal.
1515bool
Greg Claytone4e45922011-11-16 05:37:56 +00001516Process::SetProcessExitStatus (void *callback_baton,
1517 lldb::pid_t pid,
1518 bool exited,
1519 int signo, // Zero for no signal
1520 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001521)
1522{
Greg Clayton5160ce52013-03-27 23:08:40 +00001523 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001524 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001525 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001526 callback_baton,
1527 pid,
1528 exited,
1529 signo,
1530 exit_status);
1531
1532 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001533 {
Greg Clayton66111032010-06-23 01:19:29 +00001534 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001535 if (target_sp)
1536 {
1537 ProcessSP process_sp (target_sp->GetProcessSP());
1538 if (process_sp)
1539 {
1540 const char *signal_cstr = NULL;
1541 if (signo)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001542 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001543
1544 process_sp->SetExitStatus (exit_status, signal_cstr);
1545 }
1546 }
1547 return true;
1548 }
1549 return false;
1550}
1551
1552
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001553void
1554Process::UpdateThreadListIfNeeded ()
1555{
1556 const uint32_t stop_id = GetStopID();
1557 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1558 {
Greg Clayton2637f822011-11-17 01:23:07 +00001559 const StateType state = GetPrivateState();
1560 if (StateIsStoppedState (state, true))
1561 {
1562 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001563 // m_thread_list does have its own mutex, but we need to
1564 // hold onto the mutex between the call to UpdateThreadList(...)
1565 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001566 ThreadList &old_thread_list = m_thread_list;
1567 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001568 ThreadList new_thread_list(this);
1569 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001570 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001571 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001572 {
Jim Ingham09437922013-03-01 20:04:25 +00001573 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1574 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1575 // shutting us down, causing a deadlock.
1576 if (!m_destroy_in_process)
1577 {
1578 OperatingSystem *os = GetOperatingSystem ();
1579 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001580 {
1581 // Clear any old backing threads where memory threads might have been
1582 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001583 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001584 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001585 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001586
Greg Clayton15484402015-05-15 18:40:24 +00001587 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1588 // can run an expression to determine if a SBValue is a dynamic type or not
1589 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1590 // that require running code...
1591
1592 Target &target = GetTarget();
1593 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1594 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1595 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1596
Greg Claytonb3ae8762013-04-12 20:07:46 +00001597 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001598
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001599 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1600 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1601 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 +00001602
1603 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1604 target.SetPreferDynamicValue(saved_prefer_dynamic);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001605 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001606 else
1607 {
1608 // No OS plug-in, the new thread list is the same as the real thread list
1609 new_thread_list = real_thread_list;
1610 }
Jim Ingham09437922013-03-01 20:04:25 +00001611 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001612
1613 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001614 m_thread_list.Update (new_thread_list);
1615 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001616
Jason Molenda4ff13262013-11-20 00:31:38 +00001617 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1618 {
1619 // Clear any extended threads that we may have accumulated previously
1620 m_extended_thread_list.Clear();
1621 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001622
1623 m_queue_list.Clear();
1624 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001625 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001626 }
Greg Clayton2637f822011-11-17 01:23:07 +00001627 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001628 }
1629}
1630
Jason Molenda5e8dce42013-12-13 00:29:16 +00001631void
1632Process::UpdateQueueListIfNeeded ()
1633{
1634 if (m_system_runtime_ap.get())
1635 {
1636 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1637 {
1638 const StateType state = GetPrivateState();
1639 if (StateIsStoppedState (state, true))
1640 {
1641 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1642 m_queue_list_stop_id = GetLastNaturalStopID();
1643 }
1644 }
1645 }
1646}
1647
Greg Claytona4d87472013-01-18 23:41:08 +00001648ThreadSP
1649Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1650{
1651 OperatingSystem *os = GetOperatingSystem ();
1652 if (os)
1653 return os->CreateThread(tid, context);
1654 return ThreadSP();
1655}
1656
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001657uint32_t
1658Process::GetNextThreadIndexID (uint64_t thread_id)
1659{
1660 return AssignIndexIDToThread(thread_id);
1661}
1662
1663bool
1664Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1665{
1666 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1667 if (iterator == m_thread_id_to_index_id_map.end())
1668 {
1669 return false;
1670 }
1671 else
1672 {
1673 return true;
1674 }
1675}
1676
1677uint32_t
1678Process::AssignIndexIDToThread(uint64_t thread_id)
1679{
1680 uint32_t result = 0;
1681 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1682 if (iterator == m_thread_id_to_index_id_map.end())
1683 {
1684 result = ++m_thread_index_id;
1685 m_thread_id_to_index_id_map[thread_id] = result;
1686 }
1687 else
1688 {
1689 result = iterator->second;
1690 }
1691
1692 return result;
1693}
1694
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001695StateType
1696Process::GetState()
1697{
1698 // If any other threads access this we will need a mutex for it
1699 return m_public_state.GetValue ();
1700}
1701
Greg Claytondc6224e2014-10-21 01:00:42 +00001702bool
1703Process::StateChangedIsExternallyHijacked()
1704{
1705 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1706 {
1707 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1708 return true;
1709 }
1710 return false;
1711}
1712
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713void
Jim Ingham221d51c2013-05-08 00:35:16 +00001714Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715{
Greg Clayton5160ce52013-03-27 23:08:40 +00001716 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001717 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001718 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001719 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001720 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001721
1722 // On the transition from Run to Stopped, we unlock the writer end of the
1723 // run lock. The lock gets locked in Resume, which is the public API
1724 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001725 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001726 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001727 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001728 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001729 if (log)
1730 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001731 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001732 }
1733 else
1734 {
1735 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1736 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001737 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001738 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001739 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001740 {
1741 if (log)
1742 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001743 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001744 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001745 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001746 }
1747 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001748}
1749
Jim Ingham3b8285d2012-04-19 01:40:33 +00001750Error
1751Process::Resume ()
1752{
Greg Clayton5160ce52013-03-27 23:08:40 +00001753 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001754 if (log)
1755 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001756 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001757 {
1758 Error error("Resume request failed - process still running.");
1759 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001760 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001761 return error;
1762 }
1763 return PrivateResume();
1764}
1765
Greg Claytondc6224e2014-10-21 01:00:42 +00001766Error
1767Process::ResumeSynchronous (Stream *stream)
1768{
1769 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1770 if (log)
1771 log->Printf("Process::ResumeSynchronous -- locking run lock");
1772 if (!m_public_run_lock.TrySetRunning())
1773 {
1774 Error error("Resume request failed - process still running.");
1775 if (log)
1776 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1777 return error;
1778 }
1779
1780 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1781 HijackProcessEvents(listener_sp.get());
1782
1783 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001784 if (error.Success())
1785 {
1786 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1787 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1788 if (!StateIsStoppedState(state, must_be_alive))
1789 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1790 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001791
1792 // Undo the hijacking of process events...
1793 RestoreProcessEvents();
1794
Greg Claytondc6224e2014-10-21 01:00:42 +00001795 return error;
1796}
1797
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001798StateType
1799Process::GetPrivateState ()
1800{
1801 return m_private_state.GetValue();
1802}
1803
1804void
1805Process::SetPrivateState (StateType new_state)
1806{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001807 if (m_finalize_called)
1808 return;
1809
Greg Clayton5160ce52013-03-27 23:08:40 +00001810 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811 bool state_changed = false;
1812
1813 if (log)
1814 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1815
Andrew Kaylor29d65742013-05-10 17:19:04 +00001816 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817 Mutex::Locker locker(m_private_state.GetMutex());
1818
1819 const StateType old_state = m_private_state.GetValueNoLock ();
1820 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001821
Greg Claytonaa49c832013-05-03 22:25:56 +00001822 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1823 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1824 if (old_state_is_stopped != new_state_is_stopped)
1825 {
1826 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001827 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001828 else
Ed Maste64fad602013-07-29 20:58:06 +00001829 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001830 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001831
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832 if (state_changed)
1833 {
1834 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001835 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001836 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001838 // Note, this currently assumes that all threads in the list
1839 // stop when the process stops. In the future we will want to
1840 // support a debugging model where some threads continue to run
1841 // while others are stopped. When that happens we will either need
1842 // a way for the thread list to identify which threads are stopping
1843 // or create a special thread list containing only threads which
1844 // actually stopped.
1845 //
1846 // The process plugin is responsible for managing the actual
1847 // behavior of the threads and should have stopped any threads
1848 // that are going to stop before we get here.
1849 m_thread_list.DidStop();
1850
Jim Ingham4b536182011-08-09 02:12:22 +00001851 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001852 if (!m_mod_id.IsLastResumeForUserExpression())
1853 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001854 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001856 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001857 }
Ilia K38810f42015-05-20 10:15:47 +00001858
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001859 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001860 if (m_finalize_called && PrivateStateThreadIsValid() == false)
Ilia K38810f42015-05-20 10:15:47 +00001861 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001862 else
Ilia K38810f42015-05-20 10:15:47 +00001863 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 }
1865 else
1866 {
1867 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001868 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869 }
1870}
1871
Jim Ingham0faa43f2011-11-08 03:00:11 +00001872void
1873Process::SetRunningUserExpression (bool on)
1874{
1875 m_mod_id.SetRunningUserExpression (on);
1876}
1877
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878addr_t
1879Process::GetImageInfoAddress()
1880{
1881 return LLDB_INVALID_ADDRESS;
1882}
1883
Greg Clayton8f343b02010-11-04 01:54:29 +00001884//----------------------------------------------------------------------
1885// LoadImage
1886//
1887// This function provides a default implementation that works for most
1888// unix variants. Any Process subclasses that need to do shared library
1889// loading differently should override LoadImage and UnloadImage and
1890// do what is needed.
1891//----------------------------------------------------------------------
1892uint32_t
1893Process::LoadImage (const FileSpec &image_spec, Error &error)
1894{
Greg Claytonc00ca312015-04-02 18:44:58 +00001895 if (m_finalizing)
1896 {
1897 error.SetErrorString("process is tearing itself down");
1898 return LLDB_INVALID_IMAGE_TOKEN;
1899 }
1900
Greg Claytonac7a3db2012-04-18 00:05:19 +00001901 char path[PATH_MAX];
1902 image_spec.GetPath(path, sizeof(path));
1903
Greg Clayton8f343b02010-11-04 01:54:29 +00001904 DynamicLoader *loader = GetDynamicLoader();
1905 if (loader)
1906 {
1907 error = loader->CanLoadImage();
1908 if (error.Fail())
1909 return LLDB_INVALID_IMAGE_TOKEN;
1910 }
1911
1912 if (error.Success())
1913 {
1914 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001915
1916 if (thread_sp)
1917 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001918 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001919
1920 if (frame_sp)
1921 {
1922 ExecutionContext exe_ctx;
1923 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001924 EvaluateExpressionOptions expr_options;
1925 expr_options.SetUnwindOnError(true);
1926 expr_options.SetIgnoreBreakpoints(true);
1927 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001928 expr_options.SetResultIsInternal(true);
Jim Ingham151c0322015-09-15 21:13:50 +00001929 expr_options.SetLanguage(eLanguageTypeC_plus_plus);
Jim Ingham4ac04432014-07-19 01:09:16 +00001930
Greg Clayton8f343b02010-11-04 01:54:29 +00001931 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001932 expr.Printf(R"(
1933 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1934 the_result.image_ptr = dlopen ("%s", 2);
1935 if (the_result.image_ptr == (void *) 0x0)
1936 {
1937 the_result.error_str = dlerror();
1938 }
1939 else
1940 {
1941 the_result.error_str = (const char *) 0x0;
1942 }
1943 the_result;
1944 )",
1945 path);
1946 const char *prefix = R"(
1947 extern "C" void* dlopen (const char *path, int mode);
1948 extern "C" const char *dlerror (void);
1949 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001950 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001951 Error expr_error;
Jim Ingham151c0322015-09-15 21:13:50 +00001952 UserExpression::Evaluate (exe_ctx,
1953 expr_options,
1954 expr.GetData(),
1955 prefix,
1956 result_valobj_sp,
1957 expr_error);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001958 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001959 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001960 error = result_valobj_sp->GetError();
1961 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001962 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001963 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001964 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1965 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001966 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001967 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1968 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1969 {
1970 uint32_t image_token = m_image_tokens.size();
1971 m_image_tokens.push_back (image_ptr);
1972 return image_token;
1973 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001974 else if (image_ptr == 0)
1975 {
Jim Ingham6971b862014-07-19 00:37:06 +00001976 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1977 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001978 {
Jim Ingham6971b862014-07-19 00:37:06 +00001979 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001980 {
Enrico Granata2206b482014-10-30 18:27:31 +00001981 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1982 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001983 if (error.Success() && num_chars > 0)
1984 {
1985 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001986 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1987 }
1988 else
1989 {
1990 error.Clear();
1991 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001992 }
1993 }
1994 }
1995 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001996 }
1997 }
1998 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001999 else
2000 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00002001 }
2002 }
2003 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00002004 if (!error.AsCString())
2005 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00002006 return LLDB_INVALID_IMAGE_TOKEN;
2007}
2008
2009//----------------------------------------------------------------------
2010// UnloadImage
2011//
2012// This function provides a default implementation that works for most
2013// unix variants. Any Process subclasses that need to do shared library
2014// loading differently should override LoadImage and UnloadImage and
2015// do what is needed.
2016//----------------------------------------------------------------------
2017Error
2018Process::UnloadImage (uint32_t image_token)
2019{
2020 Error error;
Greg Claytonc00ca312015-04-02 18:44:58 +00002021
2022 if (m_finalizing)
2023 {
2024 error.SetErrorString("process is tearing itself down");
2025 return error;
2026 }
2027
Greg Clayton8f343b02010-11-04 01:54:29 +00002028 if (image_token < m_image_tokens.size())
2029 {
2030 const addr_t image_addr = m_image_tokens[image_token];
2031 if (image_addr == LLDB_INVALID_ADDRESS)
2032 {
2033 error.SetErrorString("image already unloaded");
2034 }
2035 else
2036 {
2037 DynamicLoader *loader = GetDynamicLoader();
2038 if (loader)
2039 error = loader->CanLoadImage();
2040
2041 if (error.Success())
2042 {
2043 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00002044
2045 if (thread_sp)
2046 {
Jason Molendab57e4a12013-11-04 09:33:30 +00002047 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00002048
2049 if (frame_sp)
2050 {
2051 ExecutionContext exe_ctx;
2052 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00002053 EvaluateExpressionOptions expr_options;
2054 expr_options.SetUnwindOnError(true);
2055 expr_options.SetIgnoreBreakpoints(true);
2056 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham151c0322015-09-15 21:13:50 +00002057 expr_options.SetLanguage(eLanguageTypeC_plus_plus);
2058
Greg Clayton8f343b02010-11-04 01:54:29 +00002059 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00002060 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00002061 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00002062 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00002063 Error expr_error;
Jim Ingham151c0322015-09-15 21:13:50 +00002064 UserExpression::Evaluate (exe_ctx,
2065 expr_options,
2066 expr.GetData(),
2067 prefix,
2068 result_valobj_sp,
2069 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00002070 if (result_valobj_sp->GetError().Success())
2071 {
2072 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00002073 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00002074 {
2075 if (scalar.UInt(1))
2076 {
2077 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2078 }
2079 else
2080 {
2081 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2082 }
2083 }
2084 }
2085 else
2086 {
2087 error = result_valobj_sp->GetError();
2088 }
2089 }
2090 }
2091 }
2092 }
2093 }
2094 else
2095 {
2096 error.SetErrorString("invalid image token");
2097 }
2098 return error;
2099}
2100
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002101const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102Process::GetABI()
2103{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002104 if (!m_abi_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00002105 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002106 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107}
2108
Jim Ingham22777012010-09-23 02:01:19 +00002109LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002110Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002111{
Greg Claytonc00ca312015-04-02 18:44:58 +00002112 if (m_finalizing)
2113 return nullptr;
2114
Jim Ingham22777012010-09-23 02:01:19 +00002115 LanguageRuntimeCollection::iterator pos;
2116 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002117 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002118 {
Jim Inghamab175242012-03-10 00:22:19 +00002119 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002120
Jim Inghamab175242012-03-10 00:22:19 +00002121 m_language_runtimes[language] = runtime_sp;
2122 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002123 }
2124 else
2125 return (*pos).second.get();
2126}
2127
2128CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002129Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002130{
Jim Inghamab175242012-03-10 00:22:19 +00002131 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002132 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2133 return static_cast<CPPLanguageRuntime *> (runtime);
2134 return NULL;
2135}
2136
2137ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002138Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002139{
Jim Inghamab175242012-03-10 00:22:19 +00002140 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002141 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2142 return static_cast<ObjCLanguageRuntime *> (runtime);
2143 return NULL;
2144}
2145
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002146bool
2147Process::IsPossibleDynamicValue (ValueObject& in_value)
2148{
Greg Claytonc00ca312015-04-02 18:44:58 +00002149 if (m_finalizing)
2150 return false;
2151
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002152 if (in_value.IsDynamic())
2153 return false;
2154 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2155
2156 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2157 {
2158 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2159 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2160 }
2161
2162 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2163 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2164 return true;
2165
2166 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2167 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2168}
2169
Zachary Turner93749ab2015-03-03 21:51:25 +00002170void
2171Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
2172{
2173 m_dynamic_checkers_ap.reset(dynamic_checkers);
2174}
2175
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176BreakpointSiteList &
2177Process::GetBreakpointSiteList()
2178{
2179 return m_breakpoint_site_list;
2180}
2181
2182const BreakpointSiteList &
2183Process::GetBreakpointSiteList() const
2184{
2185 return m_breakpoint_site_list;
2186}
2187
2188
2189void
2190Process::DisableAllBreakpointSites ()
2191{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002192 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2193// bp_site->SetEnabled(true);
2194 DisableBreakpointSite(bp_site);
2195 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002196}
2197
2198Error
2199Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2200{
2201 Error error (DisableBreakpointSiteByID (break_id));
2202
2203 if (error.Success())
2204 m_breakpoint_site_list.Remove(break_id);
2205
2206 return error;
2207}
2208
2209Error
2210Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2211{
2212 Error error;
2213 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2214 if (bp_site_sp)
2215 {
2216 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002217 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218 }
2219 else
2220 {
Daniel Malead01b2952012-11-29 21:49:15 +00002221 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222 }
2223
2224 return error;
2225}
2226
2227Error
2228Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2229{
2230 Error error;
2231 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2232 if (bp_site_sp)
2233 {
2234 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002235 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 }
2237 else
2238 {
Daniel Malead01b2952012-11-29 21:49:15 +00002239 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240 }
2241 return error;
2242}
2243
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002244lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002245Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002247 addr_t load_addr = LLDB_INVALID_ADDRESS;
2248
2249 bool show_error = true;
2250 switch (GetState())
2251 {
2252 case eStateInvalid:
2253 case eStateUnloaded:
2254 case eStateConnected:
2255 case eStateAttaching:
2256 case eStateLaunching:
2257 case eStateDetached:
2258 case eStateExited:
2259 show_error = false;
2260 break;
2261
2262 case eStateStopped:
2263 case eStateRunning:
2264 case eStateStepping:
2265 case eStateCrashed:
2266 case eStateSuspended:
2267 show_error = IsAlive();
2268 break;
2269 }
2270
2271 // Reset the IsIndirect flag here, in case the location changes from
2272 // pointing to a indirect symbol to a regular symbol.
2273 owner->SetIsIndirect (false);
2274
2275 if (owner->ShouldResolveIndirectFunctions())
2276 {
2277 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2278 if (symbol && symbol->IsIndirect())
2279 {
2280 Error error;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002281 Address symbol_address = symbol->GetAddress();
2282 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:59 +00002283 if (!error.Success() && show_error)
2284 {
Zachary Turner7529df92015-09-01 20:02:29 +00002285 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2286 symbol->GetLoadAddress(&GetTarget()),
2287 owner->GetBreakpoint().GetID(),
2288 owner->GetID(),
2289 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002290 return LLDB_INVALID_BREAK_ID;
2291 }
2292 Address resolved_address(load_addr);
Zachary Turner7529df92015-09-01 20:02:29 +00002293 load_addr = resolved_address.GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002294 owner->SetIsIndirect(true);
2295 }
2296 else
Zachary Turner7529df92015-09-01 20:02:29 +00002297 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002298 }
2299 else
Zachary Turner7529df92015-09-01 20:02:29 +00002300 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002302 if (load_addr != LLDB_INVALID_ADDRESS)
2303 {
2304 BreakpointSiteSP bp_site_sp;
2305
2306 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2307 // create a new breakpoint site and add it.
2308
2309 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2310
2311 if (bp_site_sp)
2312 {
2313 bp_site_sp->AddOwner (owner);
2314 owner->SetBreakpointSite (bp_site_sp);
2315 return bp_site_sp->GetID();
2316 }
2317 else
2318 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002319 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002320 if (bp_site_sp)
2321 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002322 Error error = EnableBreakpointSite (bp_site_sp.get());
2323 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324 {
2325 owner->SetBreakpointSite (bp_site_sp);
2326 return m_breakpoint_site_list.Add (bp_site_sp);
2327 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002328 else
2329 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002330 if (show_error)
2331 {
2332 // Report error for setting breakpoint...
Zachary Turner7529df92015-09-01 20:02:29 +00002333 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2334 load_addr,
2335 owner->GetBreakpoint().GetID(),
2336 owner->GetID(),
2337 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002338 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002339 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340 }
2341 }
2342 }
2343 // We failed to enable the breakpoint
2344 return LLDB_INVALID_BREAK_ID;
2345
2346}
2347
2348void
2349Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2350{
2351 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2352 if (num_owners == 0)
2353 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002354 // Don't try to disable the site if we don't have a live process anymore.
2355 if (IsAlive())
2356 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2358 }
2359}
2360
2361
2362size_t
2363Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2364{
2365 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002366 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002367
Jim Ingham20c77192011-06-29 19:42:28 +00002368 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002370 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2371 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002373 addr_t intersect_addr;
2374 size_t intersect_size;
2375 size_t opcode_offset;
2376 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002377 {
2378 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2379 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002380 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002381 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002382 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002383 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002384 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002385 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002386 }
2387 return bytes_removed;
2388}
2389
2390
Greg Claytonded470d2011-03-19 01:12:21 +00002391
2392size_t
2393Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2394{
Zachary Turner7529df92015-09-01 20:02:29 +00002395 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Claytonded470d2011-03-19 01:12:21 +00002396 if (platform_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00002397 return platform_sp->GetSoftwareBreakpointTrapOpcode (GetTarget(), bp_site);
Greg Claytonded470d2011-03-19 01:12:21 +00002398 return 0;
2399}
2400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401Error
2402Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2403{
2404 Error error;
2405 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002406 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407 const addr_t bp_addr = bp_site->GetLoadAddress();
2408 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002409 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 if (bp_site->IsEnabled())
2411 {
2412 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002413 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 +00002414 return error;
2415 }
2416
2417 if (bp_addr == LLDB_INVALID_ADDRESS)
2418 {
2419 error.SetErrorString("BreakpointSite contains an invalid load address.");
2420 return error;
2421 }
2422 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2423 // trap for the breakpoint site
2424 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2425
2426 if (bp_opcode_size == 0)
2427 {
Daniel Malead01b2952012-11-29 21:49:15 +00002428 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 }
2430 else
2431 {
2432 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2433
2434 if (bp_opcode_bytes == NULL)
2435 {
2436 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2437 return error;
2438 }
2439
2440 // Save the original opcode by reading it
2441 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2442 {
2443 // Write a software breakpoint in place of the original opcode
2444 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2445 {
2446 uint8_t verify_bp_opcode_bytes[64];
2447 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2448 {
2449 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2450 {
2451 bp_site->SetEnabled(true);
2452 bp_site->SetType (BreakpointSite::eSoftware);
2453 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002454 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455 bp_site->GetID(),
2456 (uint64_t)bp_addr);
2457 }
2458 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002459 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002460 }
2461 else
2462 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2463 }
2464 else
2465 error.SetErrorString("Unable to write breakpoint trap to memory.");
2466 }
2467 else
2468 error.SetErrorString("Unable to read memory at breakpoint address.");
2469 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002470 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002471 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472 bp_site->GetID(),
2473 (uint64_t)bp_addr,
2474 error.AsCString());
2475 return error;
2476}
2477
2478Error
2479Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2480{
2481 Error error;
2482 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002483 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002484 addr_t bp_addr = bp_site->GetLoadAddress();
2485 lldb::user_id_t breakID = bp_site->GetID();
2486 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002487 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002488
2489 if (bp_site->IsHardware())
2490 {
2491 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2492 }
2493 else if (bp_site->IsEnabled())
2494 {
2495 const size_t break_op_size = bp_site->GetByteSize();
2496 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2497 if (break_op_size > 0)
2498 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002499 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002500 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002501 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502 bool break_op_found = false;
2503
2504 // Read the breakpoint opcode
2505 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2506 {
2507 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002508 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2510 {
2511 break_op_found = true;
2512 // We found a valid breakpoint opcode at this address, now restore
2513 // the saved opcode.
2514 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2515 {
2516 verify = true;
2517 }
2518 else
2519 error.SetErrorString("Memory write failed when restoring original opcode.");
2520 }
2521 else
2522 {
2523 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2524 // Set verify to true and so we can check if the original opcode has already been restored
2525 verify = true;
2526 }
2527
2528 if (verify)
2529 {
Greg Claytonc982c762010-07-09 20:39:50 +00002530 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002531 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532 // Verify that our original opcode made it back to the inferior
2533 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2534 {
2535 // compare the memory we just read with the original opcode
2536 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2537 {
2538 // SUCCESS
2539 bp_site->SetEnabled(false);
2540 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002541 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 +00002542 return error;
2543 }
2544 else
2545 {
2546 if (break_op_found)
2547 error.SetErrorString("Failed to restore original opcode.");
2548 }
2549 }
2550 else
2551 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2552 }
2553 }
2554 else
2555 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2556 }
2557 }
2558 else
2559 {
2560 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002561 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 +00002562 return error;
2563 }
2564
2565 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002566 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002567 bp_site->GetID(),
2568 (uint64_t)bp_addr,
2569 error.AsCString());
2570 return error;
2571
2572}
2573
Greg Clayton58be07b2011-01-07 06:08:19 +00002574// Uncomment to verify memory caching works after making changes to caching code
2575//#define VERIFY_MEMORY_READS
2576
Sean Callanan64c0cf22012-06-07 22:26:42 +00002577size_t
2578Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2579{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002580 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002581 if (!GetDisableMemoryCache())
2582 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002583#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002584 // Memory caching is enabled, with debug verification
2585
2586 if (buf && size)
2587 {
2588 // Uncomment the line below to make sure memory caching is working.
2589 // I ran this through the test suite and got no assertions, so I am
2590 // pretty confident this is working well. If any changes are made to
2591 // memory caching, uncomment the line below and test your changes!
2592
2593 // Verify all memory reads by using the cache first, then redundantly
2594 // reading the same memory from the inferior and comparing to make sure
2595 // everything is exactly the same.
2596 std::string verify_buf (size, '\0');
2597 assert (verify_buf.size() == size);
2598 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2599 Error verify_error;
2600 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2601 assert (cache_bytes_read == verify_bytes_read);
2602 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2603 assert (verify_error.Success() == error.Success());
2604 return cache_bytes_read;
2605 }
2606 return 0;
2607#else // !defined(VERIFY_MEMORY_READS)
2608 // Memory caching is enabled, without debug verification
2609
2610 return m_memory_cache.Read (addr, buf, size, error);
2611#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002612 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002613 else
2614 {
2615 // Memory caching is disabled
2616
2617 return ReadMemoryFromInferior (addr, buf, size, error);
2618 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002619}
Greg Clayton58be07b2011-01-07 06:08:19 +00002620
Greg Clayton4c82d422012-05-18 23:20:01 +00002621size_t
2622Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2623{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002624 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002625 out_str.clear();
2626 addr_t curr_addr = addr;
2627 while (1)
2628 {
2629 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2630 if (length == 0)
2631 break;
2632 out_str.append(buf, length);
2633 // If we got "length - 1" bytes, we didn't get the whole C string, we
2634 // need to read some more characters
2635 if (length == sizeof(buf) - 1)
2636 curr_addr += length;
2637 else
2638 break;
2639 }
2640 return out_str.size();
2641}
2642
Greg Clayton58be07b2011-01-07 06:08:19 +00002643
2644size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002645Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2646 size_t type_width)
2647{
2648 size_t total_bytes_read = 0;
2649 if (dst && max_bytes && type_width && max_bytes >= type_width)
2650 {
2651 // Ensure a null terminator independent of the number of bytes that is read.
2652 memset (dst, 0, max_bytes);
2653 size_t bytes_left = max_bytes - type_width;
2654
2655 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2656 assert(sizeof(terminator) >= type_width &&
2657 "Attempting to validate a string with more than 4 bytes per character!");
2658
2659 addr_t curr_addr = addr;
2660 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2661 char *curr_dst = dst;
2662
2663 error.Clear();
2664 while (bytes_left > 0 && error.Success())
2665 {
2666 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2667 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2668 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2669
2670 if (bytes_read == 0)
2671 break;
2672
2673 // Search for a null terminator of correct size and alignment in bytes_read
2674 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2675 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2676 if (::strncmp(&dst[i], terminator, type_width) == 0)
2677 {
2678 error.Clear();
2679 return i;
2680 }
2681
2682 total_bytes_read += bytes_read;
2683 curr_dst += bytes_read;
2684 curr_addr += bytes_read;
2685 bytes_left -= bytes_read;
2686 }
2687 }
2688 else
2689 {
2690 if (max_bytes)
2691 error.SetErrorString("invalid arguments");
2692 }
2693 return total_bytes_read;
2694}
2695
2696// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2697// null terminators.
2698size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002699Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002700{
2701 size_t total_cstr_len = 0;
2702 if (dst && dst_max_len)
2703 {
Greg Claytone91b7952011-12-15 03:14:23 +00002704 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002705 // NULL out everything just to be safe
2706 memset (dst, 0, dst_max_len);
2707 Error error;
2708 addr_t curr_addr = addr;
2709 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2710 size_t bytes_left = dst_max_len - 1;
2711 char *curr_dst = dst;
2712
2713 while (bytes_left > 0)
2714 {
2715 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2716 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2717 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2718
2719 if (bytes_read == 0)
2720 {
Greg Claytone91b7952011-12-15 03:14:23 +00002721 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002722 dst[total_cstr_len] = '\0';
2723 break;
2724 }
2725 const size_t len = strlen(curr_dst);
2726
2727 total_cstr_len += len;
2728
2729 if (len < bytes_to_read)
2730 break;
2731
2732 curr_dst += bytes_read;
2733 curr_addr += bytes_read;
2734 bytes_left -= bytes_read;
2735 }
2736 }
Greg Claytone91b7952011-12-15 03:14:23 +00002737 else
2738 {
2739 if (dst == NULL)
2740 result_error.SetErrorString("invalid arguments");
2741 else
2742 result_error.Clear();
2743 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002744 return total_cstr_len;
2745}
2746
2747size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002748Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2749{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750 if (buf == NULL || size == 0)
2751 return 0;
2752
2753 size_t bytes_read = 0;
2754 uint8_t *bytes = (uint8_t *)buf;
2755
2756 while (bytes_read < size)
2757 {
2758 const size_t curr_size = size - bytes_read;
2759 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2760 bytes + bytes_read,
2761 curr_size,
2762 error);
2763 bytes_read += curr_bytes_read;
2764 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2765 break;
2766 }
2767
2768 // Replace any software breakpoint opcodes that fall into this range back
2769 // into "buf" before we return
2770 if (bytes_read > 0)
2771 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2772 return bytes_read;
2773}
2774
Greg Clayton58a4c462010-12-16 20:01:20 +00002775uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002776Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002777{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002778 Scalar scalar;
2779 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2780 return scalar.ULongLong(fail_value);
2781 return fail_value;
2782}
2783
2784addr_t
2785Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2786{
2787 Scalar scalar;
2788 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2789 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2790 return LLDB_INVALID_ADDRESS;
2791}
2792
2793
2794bool
2795Process::WritePointerToMemory (lldb::addr_t vm_addr,
2796 lldb::addr_t ptr_value,
2797 Error &error)
2798{
2799 Scalar scalar;
2800 const uint32_t addr_byte_size = GetAddressByteSize();
2801 if (addr_byte_size <= 4)
2802 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002803 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002804 scalar = ptr_value;
2805 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002806}
2807
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808size_t
2809Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2810{
2811 size_t bytes_written = 0;
2812 const uint8_t *bytes = (const uint8_t *)buf;
2813
2814 while (bytes_written < size)
2815 {
2816 const size_t curr_size = size - bytes_written;
2817 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2818 bytes + bytes_written,
2819 curr_size,
2820 error);
2821 bytes_written += curr_bytes_written;
2822 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2823 break;
2824 }
2825 return bytes_written;
2826}
2827
2828size_t
2829Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2830{
Greg Clayton58be07b2011-01-07 06:08:19 +00002831#if defined (ENABLE_MEMORY_CACHING)
2832 m_memory_cache.Flush (addr, size);
2833#endif
2834
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002835 if (buf == NULL || size == 0)
2836 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002837
Jim Ingham4b536182011-08-09 02:12:22 +00002838 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002839
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002840 // We need to write any data that would go where any current software traps
2841 // (enabled software breakpoints) any software traps (breakpoints) that we
2842 // may have placed in our tasks memory.
2843
Greg Claytond8cf1a12013-06-12 00:46:38 +00002844 BreakpointSiteList bp_sites_in_range;
2845
2846 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002847 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002848 // No breakpoint sites overlap
2849 if (bp_sites_in_range.IsEmpty())
2850 return WriteMemoryPrivate (addr, buf, size, error);
2851 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002853 const uint8_t *ubuf = (const uint8_t *)buf;
2854 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855
Greg Claytond8cf1a12013-06-12 00:46:38 +00002856 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2857
2858 if (error.Success())
2859 {
2860 addr_t intersect_addr;
2861 size_t intersect_size;
2862 size_t opcode_offset;
2863 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
Bruce Mitchener8a67bf72015-07-24 00:23:29 +00002864 UNUSED_IF_ASSERT_DISABLED(intersects);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002865 assert(intersects);
2866 assert(addr <= intersect_addr && intersect_addr < addr + size);
2867 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2868 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2869
2870 // Check for bytes before this breakpoint
2871 const addr_t curr_addr = addr + bytes_written;
2872 if (intersect_addr > curr_addr)
2873 {
2874 // There are some bytes before this breakpoint that we need to
2875 // just write to memory
2876 size_t curr_size = intersect_addr - curr_addr;
2877 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2878 ubuf + bytes_written,
2879 curr_size,
2880 error);
2881 bytes_written += curr_bytes_written;
2882 if (curr_bytes_written != curr_size)
2883 {
2884 // We weren't able to write all of the requested bytes, we
2885 // are done looping and will return the number of bytes that
2886 // we have written so far.
2887 if (error.Success())
2888 error.SetErrorToGenericError();
2889 }
2890 }
2891 // Now write any bytes that would cover up any software breakpoints
2892 // directly into the breakpoint opcode buffer
2893 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2894 bytes_written += intersect_size;
2895 }
2896 });
2897
2898 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002899 WriteMemoryPrivate (addr + bytes_written,
2900 ubuf + bytes_written,
2901 size - bytes_written,
2902 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002903 }
2904 }
2905 else
2906 {
2907 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908 }
2909
2910 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002911 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002913
2914size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002915Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002916{
2917 if (byte_size == UINT32_MAX)
2918 byte_size = scalar.GetByteSize();
2919 if (byte_size > 0)
2920 {
2921 uint8_t buf[32];
2922 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2923 if (mem_size > 0)
2924 return WriteMemory(addr, buf, mem_size, error);
2925 else
2926 error.SetErrorString ("failed to get scalar as memory data");
2927 }
2928 else
2929 {
2930 error.SetErrorString ("invalid scalar value");
2931 }
2932 return 0;
2933}
2934
2935size_t
2936Process::ReadScalarIntegerFromMemory (addr_t addr,
2937 uint32_t byte_size,
2938 bool is_signed,
2939 Scalar &scalar,
2940 Error &error)
2941{
Greg Clayton7060f892013-05-01 23:41:30 +00002942 uint64_t uval = 0;
2943 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002944 {
Greg Clayton7060f892013-05-01 23:41:30 +00002945 error.SetErrorString ("byte size is zero");
2946 }
2947 else if (byte_size & (byte_size - 1))
2948 {
2949 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2950 }
2951 else if (byte_size <= sizeof(uval))
2952 {
2953 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002954 if (bytes_read == byte_size)
2955 {
2956 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002957 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002958 if (byte_size <= 4)
2959 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002960 else
Greg Clayton7060f892013-05-01 23:41:30 +00002961 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002962 if (is_signed)
2963 scalar.SignExtend(byte_size * 8);
2964 return bytes_read;
2965 }
2966 }
2967 else
2968 {
2969 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2970 }
2971 return 0;
2972}
2973
Greg Claytond495c532011-05-17 03:37:42 +00002974#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975addr_t
2976Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2977{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002978 if (GetPrivateState() != eStateStopped)
2979 return LLDB_INVALID_ADDRESS;
2980
Greg Claytond495c532011-05-17 03:37:42 +00002981#if defined (USE_ALLOCATE_MEMORY_CACHE)
2982 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2983#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002984 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002985 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002986 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002987 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 +00002988 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002989 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002990 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002991 m_mod_id.GetStopID(),
2992 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002993 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002994#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002995}
2996
Sean Callanan90539452011-09-20 23:01:51 +00002997bool
2998Process::CanJIT ()
2999{
Sean Callanana7b443a2012-02-14 22:50:38 +00003000 if (m_can_jit == eCanJITDontKnow)
3001 {
Todd Fialaaf245d12014-06-30 21:05:18 +00003002 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00003003 Error err;
3004
3005 uint64_t allocated_memory = AllocateMemory(8,
3006 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
3007 err);
3008
3009 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00003010 {
Sean Callanana7b443a2012-02-14 22:50:38 +00003011 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00003012 if (log)
3013 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
3014 }
Sean Callanana7b443a2012-02-14 22:50:38 +00003015 else
Todd Fialaaf245d12014-06-30 21:05:18 +00003016 {
Sean Callanana7b443a2012-02-14 22:50:38 +00003017 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00003018 if (log)
3019 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
3020 }
Sean Callanana7b443a2012-02-14 22:50:38 +00003021
3022 DeallocateMemory (allocated_memory);
3023 }
3024
Sean Callanan90539452011-09-20 23:01:51 +00003025 return m_can_jit == eCanJITYes;
3026}
3027
3028void
3029Process::SetCanJIT (bool can_jit)
3030{
3031 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
3032}
3033
Ewan Crawford90ff7912015-07-14 10:56:58 +00003034void
3035Process::SetCanRunCode (bool can_run_code)
3036{
3037 SetCanJIT(can_run_code);
3038 m_can_interpret_function_calls = can_run_code;
3039}
3040
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003041Error
3042Process::DeallocateMemory (addr_t ptr)
3043{
Greg Claytond495c532011-05-17 03:37:42 +00003044 Error error;
3045#if defined (USE_ALLOCATE_MEMORY_CACHE)
3046 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
3047 {
Daniel Malead01b2952012-11-29 21:49:15 +00003048 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00003049 }
3050#else
3051 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00003052
Greg Clayton5160ce52013-03-27 23:08:40 +00003053 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00003054 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003055 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 +00003056 ptr,
3057 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00003058 m_mod_id.GetStopID(),
3059 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00003060#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00003061 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062}
3063
Han Ming Ongc811d382012-11-17 00:33:14 +00003064
Greg Claytonc9660542012-02-05 02:38:54 +00003065ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00003066Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00003067 lldb::addr_t header_addr,
3068 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00003069{
Jason Molenda08a32582015-07-25 02:39:42 +00003070 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
3071 if (log)
3072 {
3073 log->Printf ("Process::ReadModuleFromMemory reading %s binary from memory", file_spec.GetPath().c_str());
3074 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003075 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00003076 if (module_sp)
3077 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003078 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00003079 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003080 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003081 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00003082 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00003083 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00003084}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085
Zachary Turner93749ab2015-03-03 21:51:25 +00003086bool
3087Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
3088{
3089 MemoryRegionInfo range_info;
3090 permissions = 0;
3091 Error error (GetMemoryRegionInfo (load_addr, range_info));
3092 if (!error.Success())
3093 return false;
3094 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
3095 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
3096 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
3097 {
3098 return false;
3099 }
3100
3101 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
3102 permissions |= lldb::ePermissionsReadable;
3103
3104 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
3105 permissions |= lldb::ePermissionsWritable;
3106
3107 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
3108 permissions |= lldb::ePermissionsExecutable;
3109
3110 return true;
3111}
3112
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003113Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003114Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115{
3116 Error error;
3117 error.SetErrorString("watchpoints are not supported");
3118 return error;
3119}
3120
3121Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00003122Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123{
3124 Error error;
3125 error.SetErrorString("watchpoints are not supported");
3126 return error;
3127}
3128
3129StateType
3130Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3131{
3132 StateType state;
3133 // Now wait for the process to launch and return control to us, and then
3134 // call DidLaunch:
3135 while (1)
3136 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003137 event_sp.reset();
3138 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3139
Greg Clayton2637f822011-11-17 01:23:07 +00003140 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003142
3143 // If state is invalid, then we timed out
3144 if (state == eStateInvalid)
3145 break;
3146
3147 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003148 HandlePrivateEvent (event_sp);
3149 }
3150 return state;
3151}
3152
Greg Clayton332e8b12015-01-13 21:13:08 +00003153void
3154Process::LoadOperatingSystemPlugin(bool flush)
3155{
3156 if (flush)
3157 m_thread_list.Clear();
3158 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3159 if (flush)
3160 Flush();
3161}
3162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003164Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165{
3166 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003167 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003168 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003169 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003170 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003171 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003172 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003173 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003174
Zachary Turner7529df92015-09-01 20:02:29 +00003175 Module *exe_module = GetTarget().GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176 if (exe_module)
3177 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003178 char local_exec_file_path[PATH_MAX];
3179 char platform_exec_file_path[PATH_MAX];
3180 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3181 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003182 if (exe_module->GetFileSpec().Exists())
3183 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003184 // Install anything that might need to be installed prior to launching.
3185 // For host systems, this will do nothing, but if we are connected to a
3186 // remote platform it will install any needed binaries
3187 error = GetTarget().Install(&launch_info);
3188 if (error.Fail())
3189 return error;
3190
Greg Clayton71337622011-02-24 22:24:29 +00003191 if (PrivateStateThreadIsValid ())
3192 PausePrivateStateThread ();
3193
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003194 error = WillLaunch (exe_module);
3195 if (error.Success())
3196 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003197 const bool restarted = false;
3198 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003199 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200
Ed Maste64fad602013-07-29 20:58:06 +00003201 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003202 {
3203 // Now launch using these arguments.
3204 error = DoLaunch (exe_module, launch_info);
3205 }
3206 else
3207 {
3208 // This shouldn't happen
3209 error.SetErrorString("failed to acquire process run lock");
3210 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211
3212 if (error.Fail())
3213 {
3214 if (GetID() != LLDB_INVALID_PROCESS_ID)
3215 {
3216 SetID (LLDB_INVALID_PROCESS_ID);
3217 const char *error_string = error.AsCString();
3218 if (error_string == NULL)
3219 error_string = "launch failed";
3220 SetExitStatus (-1, error_string);
3221 }
3222 }
3223 else
3224 {
3225 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003226 TimeValue timeout_time;
3227 timeout_time = TimeValue::Now();
3228 timeout_time.OffsetWithSeconds(10);
3229 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003230
Greg Clayton1a38ea72011-06-22 01:42:17 +00003231 if (state == eStateInvalid || event_sp.get() == NULL)
3232 {
3233 // We were able to launch the process, but we failed to
3234 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003235 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003236 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003237 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003238 }
3239 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003240 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003241
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003242 DidLaunch ();
3243
Greg Claytonc859e2d2012-02-13 23:10:39 +00003244 DynamicLoader *dyld = GetDynamicLoader ();
3245 if (dyld)
3246 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003247
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003248 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003249
Jason Molendaeef51062013-11-05 03:57:19 +00003250 SystemRuntime *system_runtime = GetSystemRuntime ();
3251 if (system_runtime)
3252 system_runtime->DidLaunch();
3253
Greg Clayton332e8b12015-01-13 21:13:08 +00003254 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003255
3256 // Note, the stop event was consumed above, but not handled. This was done
3257 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3258 // Directly set the state. This is done to prevent a stop message with a bunch
3259 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3260 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003261
3262 if (PrivateStateThreadIsValid ())
3263 ResumePrivateStateThread ();
3264 else
3265 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003266
3267 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003268
3269 // Target was stopped at entry as was intended. Need to notify the listeners
3270 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003271 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003272 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003273 }
3274 else if (state == eStateExited)
3275 {
3276 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3277 // not likely to work, and return an invalid pid.
3278 HandlePrivateEvent (event_sp);
3279 }
3280 }
3281 }
3282 }
3283 else
3284 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003285 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003286 }
3287 }
3288 return error;
3289}
3290
Greg Claytonc3776bf2012-02-09 06:16:32 +00003291
3292Error
3293Process::LoadCore ()
3294{
3295 Error error = DoLoadCore();
3296 if (error.Success())
3297 {
Greg Clayton35824e32015-02-20 20:59:47 +00003298 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003299 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003300
Greg Claytonc3776bf2012-02-09 06:16:32 +00003301 if (PrivateStateThreadIsValid ())
3302 ResumePrivateStateThread ();
3303 else
3304 StartPrivateStateThread ();
3305
Greg Claytonc859e2d2012-02-13 23:10:39 +00003306 DynamicLoader *dyld = GetDynamicLoader ();
3307 if (dyld)
3308 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003309
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003310 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003311
Jason Molendaeef51062013-11-05 03:57:19 +00003312 SystemRuntime *system_runtime = GetSystemRuntime ();
3313 if (system_runtime)
3314 system_runtime->DidAttach();
3315
Greg Claytonc859e2d2012-02-13 23:10:39 +00003316 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003317 // We successfully loaded a core file, now pretend we stopped so we can
3318 // show all of the threads in the core file and explore the crashed
3319 // state.
3320 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003321
3322 // Wait indefinitely for a stopped event since we just posted one above...
3323 lldb::EventSP event_sp;
3324 listener.WaitForEvent (NULL, event_sp);
3325 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3326
3327 if (!StateIsStoppedState (state, false))
3328 {
3329 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3330 if (log)
3331 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3332 error.SetErrorString ("Did not get stopped event after loading the core file.");
3333 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003334 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003335 }
3336 return error;
3337}
3338
Greg Claytonc859e2d2012-02-13 23:10:39 +00003339DynamicLoader *
3340Process::GetDynamicLoader ()
3341{
3342 if (m_dyld_ap.get() == NULL)
3343 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3344 return m_dyld_ap.get();
3345}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003346
Todd Fialaaf245d12014-06-30 21:05:18 +00003347const lldb::DataBufferSP
3348Process::GetAuxvData()
3349{
3350 return DataBufferSP ();
3351}
3352
Andrew MacPherson17220c12014-03-05 10:12:43 +00003353JITLoaderList &
3354Process::GetJITLoaders ()
3355{
3356 if (!m_jit_loaders_ap)
3357 {
3358 m_jit_loaders_ap.reset(new JITLoaderList());
3359 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3360 }
3361 return *m_jit_loaders_ap;
3362}
3363
Jason Molendaeef51062013-11-05 03:57:19 +00003364SystemRuntime *
3365Process::GetSystemRuntime ()
3366{
3367 if (m_system_runtime_ap.get() == NULL)
3368 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3369 return m_system_runtime_ap.get();
3370}
3371
Todd Fiala76e0fc92014-08-27 22:58:26 +00003372Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3373 NextEventAction (process),
3374 m_exec_count (exec_count)
3375{
3376 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3377 if (log)
3378 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3379}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003380
Jim Inghambb3a2832011-01-29 01:49:25 +00003381Process::NextEventAction::EventActionResult
3382Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003383{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003384 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3385
Jim Inghambb3a2832011-01-29 01:49:25 +00003386 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003387 if (log)
3388 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3389
3390 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003391 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003392 case eStateAttaching:
3393 return eEventActionSuccess;
3394
Greg Clayton513c26c2011-01-29 07:10:55 +00003395 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003396 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003397 return eEventActionRetry;
3398
3399 case eStateStopped:
3400 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003401 {
3402 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003403 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003404 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003405 // We don't want these events to be reported, so go set the ShouldReportStop here:
3406 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3407
Greg Claytonc9ed4782011-11-12 02:10:56 +00003408 if (m_exec_count > 0)
3409 {
3410 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003411
3412 if (log)
3413 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3414
Jim Ingham221d51c2013-05-08 00:35:16 +00003415 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003416 return eEventActionRetry;
3417 }
3418 else
3419 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003420 if (log)
3421 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3422
Greg Claytonc9ed4782011-11-12 02:10:56 +00003423 m_process->CompleteAttach ();
3424 return eEventActionSuccess;
3425 }
3426 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003427 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003428
Greg Clayton513c26c2011-01-29 07:10:55 +00003429 default:
3430 case eStateExited:
3431 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003432 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003433 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003434
3435 m_exit_string.assign ("No valid Process");
3436 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003437}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003438
Jim Inghambb3a2832011-01-29 01:49:25 +00003439Process::NextEventAction::EventActionResult
3440Process::AttachCompletionHandler::HandleBeingInterrupted()
3441{
3442 return eEventActionSuccess;
3443}
3444
3445const char *
3446Process::AttachCompletionHandler::GetExitString ()
3447{
3448 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003449}
3450
Greg Clayton8012cad2014-11-17 19:39:20 +00003451Listener &
3452ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3453{
3454 if (m_listener_sp)
3455 return *m_listener_sp;
3456 else
3457 return debugger.GetListener();
3458}
3459
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003460Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003461Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003462{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003463 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003464 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003465 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003466 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003467 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003468 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003469 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003470
Greg Clayton144f3a92011-11-15 03:53:30 +00003471 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003472 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003473 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003474 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003475 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003476
Greg Clayton144f3a92011-11-15 03:53:30 +00003477 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003478 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003479 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3480
3481 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003482 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003483 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3484 if (error.Success())
3485 {
Ed Maste64fad602013-07-29 20:58:06 +00003486 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003487 {
3488 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003489 const bool restarted = false;
3490 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003491 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003492 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003493 }
3494 else
3495 {
3496 // This shouldn't happen
3497 error.SetErrorString("failed to acquire process run lock");
3498 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003499
Greg Clayton144f3a92011-11-15 03:53:30 +00003500 if (error.Fail())
3501 {
3502 if (GetID() != LLDB_INVALID_PROCESS_ID)
3503 {
3504 SetID (LLDB_INVALID_PROCESS_ID);
3505 if (error.AsCString() == NULL)
3506 error.SetErrorString("attach failed");
3507
3508 SetExitStatus(-1, error.AsCString());
3509 }
3510 }
3511 else
3512 {
3513 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3514 StartPrivateStateThread();
3515 }
3516 return error;
3517 }
Greg Claytone996fd32011-03-08 22:40:15 +00003518 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003519 else
Greg Claytone996fd32011-03-08 22:40:15 +00003520 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003521 ProcessInstanceInfoList process_infos;
Zachary Turner7529df92015-09-01 20:02:29 +00003522 PlatformSP platform_sp (GetTarget().GetPlatform ());
Greg Clayton144f3a92011-11-15 03:53:30 +00003523
3524 if (platform_sp)
3525 {
3526 ProcessInstanceInfoMatch match_info;
3527 match_info.GetProcessInfo() = attach_info;
3528 match_info.SetNameMatchType (eNameMatchEquals);
3529 platform_sp->FindProcesses (match_info, process_infos);
3530 const uint32_t num_matches = process_infos.GetSize();
3531 if (num_matches == 1)
3532 {
3533 attach_pid = process_infos.GetProcessIDAtIndex(0);
3534 // Fall through and attach using the above process ID
3535 }
3536 else
3537 {
3538 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3539 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003540 {
3541 StreamString s;
3542 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3543 for (size_t i = 0; i < num_matches; i++)
3544 {
3545 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3546 }
3547 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3548 process_name,
3549 s.GetData());
3550 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003551 else
3552 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3553 }
3554 }
3555 else
3556 {
3557 error.SetErrorString ("invalid platform, can't find processes by name");
3558 return error;
3559 }
Greg Claytone996fd32011-03-08 22:40:15 +00003560 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 }
3562 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003563 {
3564 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003565 }
3566 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003567
3568 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003569 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003570 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003571 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003573
Ed Maste64fad602013-07-29 20:58:06 +00003574 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003575 {
3576 // Now attach using these arguments.
3577 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003578 const bool restarted = false;
3579 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003580 error = DoAttachToProcessWithID (attach_pid, attach_info);
3581 }
3582 else
3583 {
3584 // This shouldn't happen
3585 error.SetErrorString("failed to acquire process run lock");
3586 }
3587
Greg Clayton144f3a92011-11-15 03:53:30 +00003588 if (error.Success())
3589 {
3590
3591 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3592 StartPrivateStateThread();
3593 }
3594 else
Greg Claytone996fd32011-03-08 22:40:15 +00003595 {
3596 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003597 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003598
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003599 const char *error_string = error.AsCString();
3600 if (error_string == NULL)
3601 error_string = "attach failed";
3602
3603 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003604 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003605 }
3606 }
3607 return error;
3608}
3609
Greg Clayton93d3c8332011-02-16 04:46:07 +00003610void
3611Process::CompleteAttach ()
3612{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003613 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3614 if (log)
3615 log->Printf ("Process::%s()", __FUNCTION__);
3616
Greg Clayton93d3c8332011-02-16 04:46:07 +00003617 // Let the process subclass figure out at much as it can about the process
3618 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003619 ArchSpec process_arch;
3620 DidAttach(process_arch);
3621
3622 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003623 {
Zachary Turner7529df92015-09-01 20:02:29 +00003624 GetTarget().SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003625 if (log)
3626 {
3627 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3628 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3629 __FUNCTION__,
3630 triple_str ? triple_str : "<null>");
3631 }
3632 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003633
Jim Ingham4299fdb2011-09-15 01:10:17 +00003634 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3635 // the same as the one we've already set, switch architectures.
Zachary Turner7529df92015-09-01 20:02:29 +00003636 PlatformSP platform_sp (GetTarget().GetPlatform ());
Jim Ingham4299fdb2011-09-15 01:10:17 +00003637 assert (platform_sp.get());
3638 if (platform_sp)
3639 {
Zachary Turner7529df92015-09-01 20:02:29 +00003640 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003641 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003642 {
3643 ArchSpec platform_arch;
3644 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3645 if (platform_sp)
3646 {
Zachary Turner7529df92015-09-01 20:02:29 +00003647 GetTarget().SetPlatform (platform_sp);
3648 GetTarget().SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003649 if (log)
3650 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 +00003651 }
3652 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003653 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003654 {
3655 ProcessInstanceInfo process_info;
3656 platform_sp->GetProcessInfo (GetID(), process_info);
3657 const ArchSpec &process_arch = process_info.GetArchitecture();
Zachary Turner7529df92015-09-01 20:02:29 +00003658 if (process_arch.IsValid() && !GetTarget().GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003659 {
Zachary Turner7529df92015-09-01 20:02:29 +00003660 GetTarget().SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003661 if (log)
3662 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 ());
3663 }
Greg Clayton70512312012-05-08 01:45:38 +00003664 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003665 }
3666
3667 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003668 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003669 DynamicLoader *dyld = GetDynamicLoader ();
3670 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003671 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003672 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003673 if (log)
3674 {
Zachary Turner7529df92015-09-01 20:02:29 +00003675 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003676 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3677 __FUNCTION__,
3678 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3679 dyld->GetPluginName().AsCString ("<unnamed>"));
3680 }
3681 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003682
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003683 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003684
Jason Molendaeef51062013-11-05 03:57:19 +00003685 SystemRuntime *system_runtime = GetSystemRuntime ();
3686 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003687 {
Jason Molendaeef51062013-11-05 03:57:19 +00003688 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003689 if (log)
3690 {
Zachary Turner7529df92015-09-01 20:02:29 +00003691 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003692 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3693 __FUNCTION__,
3694 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3695 system_runtime->GetPluginName().AsCString("<unnamed>"));
3696 }
3697 }
Jason Molendaeef51062013-11-05 03:57:19 +00003698
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003699 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003700 // Figure out which one is the executable, and set that in our target:
Zachary Turner7529df92015-09-01 20:02:29 +00003701 const ModuleList &target_modules = GetTarget().GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003702 Mutex::Locker modules_locker(target_modules.GetMutex());
3703 size_t num_modules = target_modules.GetSize();
3704 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003705
Andy Gibbsa297a972013-06-19 19:04:53 +00003706 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003707 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003708 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003709 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003710 {
Zachary Turner7529df92015-09-01 20:02:29 +00003711 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003712 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003713 break;
3714 }
3715 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003716 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003717 {
Zachary Turner7529df92015-09-01 20:02:29 +00003718 GetTarget().SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003719 if (log)
3720 {
Zachary Turner7529df92015-09-01 20:02:29 +00003721 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003722 log->Printf ("Process::%s after looping through modules, target executable is %s",
3723 __FUNCTION__,
3724 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3725 }
3726 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003727
3728 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003729}
3730
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003731Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003732Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003733{
Greg Claytonb766a732011-02-04 01:58:07 +00003734 m_abi_sp.reset();
3735 m_process_input_reader.reset();
3736
3737 // Find the process and its architecture. Make sure it matches the architecture
3738 // of the current Target, and if not adjust it.
3739
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003740 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003741 if (error.Success())
3742 {
Greg Clayton71337622011-02-24 22:24:29 +00003743 if (GetID() != LLDB_INVALID_PROCESS_ID)
3744 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003745 EventSP event_sp;
3746 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3747
3748 if (state == eStateStopped || state == eStateCrashed)
3749 {
3750 // If we attached and actually have a process on the other end, then
3751 // this ended up being the equivalent of an attach.
3752 CompleteAttach ();
3753
3754 // This delays passing the stopped event to listeners till
3755 // CompleteAttach gets a chance to complete...
3756 HandlePrivateEvent (event_sp);
3757
3758 }
Greg Clayton71337622011-02-24 22:24:29 +00003759 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003760
3761 if (PrivateStateThreadIsValid ())
3762 ResumePrivateStateThread ();
3763 else
3764 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003765 }
3766 return error;
3767}
3768
3769
3770Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003771Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772{
Greg Clayton5160ce52013-03-27 23:08:40 +00003773 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003775 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003776 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003777 StateAsCString(m_public_state.GetValue()),
3778 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003779
3780 Error error (WillResume());
3781 // Tell the process it is about to resume before the thread list
3782 if (error.Success())
3783 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003784 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003785 // can let all of our threads know that they are about to be
3786 // resumed. Threads will each be called with
3787 // Thread::WillResume(StateType) where StateType contains the state
3788 // that they are supposed to have when the process is resumed
3789 // (suspended/running/stepping). Threads should also check
3790 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003791 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003792 if (m_thread_list.WillResume())
3793 {
Jim Ingham372787f2012-04-07 00:00:41 +00003794 // Last thing, do the PreResumeActions.
3795 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003796 {
Jim Ingham0161b492013-02-09 01:29:05 +00003797 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003798 }
3799 else
3800 {
3801 m_mod_id.BumpResumeID();
3802 error = DoResume();
3803 if (error.Success())
3804 {
3805 DidResume();
3806 m_thread_list.DidResume();
3807 if (log)
3808 log->Printf ("Process thinks the process has resumed.");
3809 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810 }
3811 }
3812 else
3813 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003814 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3815 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003816 // and let the world handle them.
3817 if (log)
3818 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3819
3820 SetPrivateState(eStateRunning);
3821 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003822 }
3823 }
Jim Ingham444586b2011-01-24 06:34:17 +00003824 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003825 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826 return error;
3827}
3828
3829Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003830Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003831{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003832 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3833 // in case it was already set and some thread plan logic calls halt on its
3834 // own.
3835 m_clear_thread_plans_on_stop |= clear_thread_plans;
3836
Jim Inghamaacc3182012-06-06 00:29:30 +00003837 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3838 // we could just straightaway get another event. It just narrows the window...
3839 m_currently_handling_event.WaitForValueEqualTo(false);
3840
3841
Jim Inghambb3a2832011-01-29 01:49:25 +00003842 // Pause our private state thread so we can ensure no one else eats
3843 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003844 Listener halt_listener ("lldb.process.halt_listener");
3845 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003846
Jim Inghambb3a2832011-01-29 01:49:25 +00003847 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003848 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003849
Greg Clayton06357c92014-07-30 17:38:47 +00003850 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003851 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003852 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003853
Greg Clayton513c26c2011-01-29 07:10:55 +00003854 bool caused_stop = false;
3855
3856 // Ask the process subclass to actually halt our process
3857 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003858 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003859 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003860 if (m_public_state.GetValue() == eStateAttaching)
3861 {
Greg Clayton06357c92014-07-30 17:38:47 +00003862 // Don't hijack and eat the eStateExited as the code that was doing
3863 // the attach will be waiting for this event...
3864 RestorePrivateProcessEvents();
3865 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003866 SetExitStatus(SIGKILL, "Cancelled async attach.");
Jason Molendaede31932015-04-17 05:01:58 +00003867 Destroy (false);
Greg Clayton513c26c2011-01-29 07:10:55 +00003868 }
3869 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003870 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003871 // If "caused_stop" is true, then DoHalt stopped the process. If
3872 // "caused_stop" is false, the process was already stopped.
3873 // If the DoHalt caused the process to stop, then we want to catch
3874 // this event and set the interrupted bool to true before we pass
3875 // this along so clients know that the process was interrupted by
3876 // a halt command.
3877 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003878 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003879 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003880 TimeValue timeout_time;
3881 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003882 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003883 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3884 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003885
Jim Ingham0f16e732011-02-08 05:20:59 +00003886 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003887 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003888 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003889 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003890 }
3891 else
3892 {
Greg Clayton2637f822011-11-17 01:23:07 +00003893 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003894 {
3895 // We caused the process to interrupt itself, so mark this
3896 // as such in the stop event so clients can tell an interrupted
3897 // process from a natural stop
3898 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3899 }
3900 else
3901 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003902 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003903 if (log)
3904 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3905 error.SetErrorString ("Did not get stopped event after halt.");
3906 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003907 }
3908 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003909 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003910 }
3911 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003912 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003913 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003914 if (!restored_process_events)
3915 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003916
3917 // Post any event we might have consumed. If all goes well, we will have
3918 // stopped the process, intercepted the event and set the interrupted
3919 // bool in the event. Post it to the private event queue and that will end up
3920 // correctly setting the state.
3921 if (event_sp)
3922 m_private_state_broadcaster.BroadcastEvent(event_sp);
3923
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003924 return error;
3925}
3926
3927Error
Pavel Labathfcc7f662015-10-07 15:11:11 +00003928Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003929{
3930 Error error;
3931 if (m_public_state.GetValue() == eStateRunning)
3932 {
3933 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3934 if (log)
Pavel Labathfcc7f662015-10-07 15:11:11 +00003935 log->Printf("Process::%s() About to stop.", __FUNCTION__);
3936
3937 ListenerSP listener_sp (new Listener("lldb.Process.StopForDestroyOrDetach.hijack"));
3938 HijackProcessEvents(listener_sp.get());
3939
3940 SendAsyncInterrupt();
3941
3942 // Consume the interrupt event.
3943 TimeValue timeout (TimeValue::Now());
3944 timeout.OffsetWithSeconds(10);
3945
3946 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp, true, listener_sp.get());
3947
3948 RestoreProcessEvents();
3949
3950 // If the process exited while we were waiting for it to stop, put the exited event into
3951 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3952 // they don't have a process anymore...
3953
3954 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
Pavel Labathc8c77d42015-09-28 09:37:51 +00003955 {
3956 if (log)
Pavel Labathfcc7f662015-10-07 15:11:11 +00003957 log->Printf("Process::%s() Process exited while waiting to stop.", __FUNCTION__);
3958 return error;
3959 }
3960 else
3961 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3962
3963 if (state != eStateStopped)
3964 {
3965 if (log)
3966 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__, StateAsCString(state));
3967 // If we really couldn't stop the process then we should just error out here, but if the
3968 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3969 StateType private_state = m_private_state.GetValue();
3970 if (private_state != eStateStopped)
3971 {
3972 return error;
3973 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003974 }
3975 }
3976 return error;
3977}
3978
3979Error
Jim Inghamacff8952013-05-02 00:27:30 +00003980Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003982 EventSP exit_event_sp;
3983 Error error;
3984 m_destroy_in_process = true;
3985
3986 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003987
3988 if (error.Success())
3989 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003990 if (DetachRequiresHalt())
3991 {
Pavel Labathfcc7f662015-10-07 15:11:11 +00003992 error = StopForDestroyOrDetach (exit_event_sp);
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003993 if (!error.Success())
3994 {
3995 m_destroy_in_process = false;
3996 return error;
3997 }
3998 else if (exit_event_sp)
3999 {
4000 // We shouldn't need to do anything else here. There's no process left to detach from...
4001 StopPrivateStateThread();
4002 m_destroy_in_process = false;
4003 return error;
4004 }
4005 }
4006
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00004007 m_thread_list.DiscardThreadPlans();
4008 DisableAllBreakpointSites();
4009
Jim Inghamacff8952013-05-02 00:27:30 +00004010 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011 if (error.Success())
4012 {
4013 DidDetach();
4014 StopPrivateStateThread();
4015 }
Jim Inghamacff8952013-05-02 00:27:30 +00004016 else
4017 {
4018 return error;
4019 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004020 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004021 m_destroy_in_process = false;
4022
4023 // If we exited when we were waiting for a process to stop, then
4024 // forward the event here so we don't lose the event
4025 if (exit_event_sp)
4026 {
4027 // Directly broadcast our exited event because we shut down our
4028 // private state thread above
4029 BroadcastEvent(exit_event_sp);
4030 }
4031
4032 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4033 // the last events through the event system, in which case we might strand the write lock. Unlock
4034 // it here so when we do to tear down the process we don't get an error destroying the lock.
4035
Ed Maste64fad602013-07-29 20:58:06 +00004036 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004037 return error;
4038}
4039
4040Error
Jason Molendaede31932015-04-17 05:01:58 +00004041Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042{
Jim Ingham09437922013-03-01 20:04:25 +00004043
4044 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
4045 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
4046 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00004047
4048 if (force_kill)
4049 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00004050
Ilia Kfcc89a02015-03-26 07:08:47 +00004051 if (GetShouldDetach())
4052 {
4053 // FIXME: This will have to be a process setting:
4054 bool keep_stopped = false;
4055 Detach(keep_stopped);
4056 }
4057
Jim Ingham09437922013-03-01 20:04:25 +00004058 m_destroy_in_process = true;
4059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004060 Error error (WillDestroy());
4061 if (error.Success())
4062 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00004063 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004064 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00004065 {
Pavel Labathfcc7f662015-10-07 15:11:11 +00004066 error = StopForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00004067 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004068
Jim Inghamaacc3182012-06-06 00:29:30 +00004069 if (m_public_state.GetValue() != eStateRunning)
4070 {
4071 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
4072 // kill it, we don't want it hitting a breakpoint...
4073 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
4074 // we're not going to have much luck doing this now.
4075 m_thread_list.DiscardThreadPlans();
4076 DisableAllBreakpointSites();
4077 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00004078
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004079 error = DoDestroy();
4080 if (error.Success())
4081 {
4082 DidDestroy();
4083 StopPrivateStateThread();
4084 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004085 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00004086 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:04 +00004087 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00004088
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004089 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00004090 {
4091 m_process_input_reader->SetIsDone(true);
4092 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004093 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00004094 }
4095
Greg Clayton85fb1b92012-09-11 02:33:37 +00004096 // If we exited when we were waiting for a process to stop, then
4097 // forward the event here so we don't lose the event
4098 if (exit_event_sp)
4099 {
4100 // Directly broadcast our exited event because we shut down our
4101 // private state thread above
4102 BroadcastEvent(exit_event_sp);
4103 }
4104
Jim Inghamb1e2e842012-04-12 18:49:31 +00004105 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
4106 // the last events through the event system, in which case we might strand the write lock. Unlock
4107 // 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 +00004108 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004109 }
Jim Ingham09437922013-03-01 20:04:25 +00004110
4111 m_destroy_in_process = false;
4112
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004113 return error;
4114}
4115
4116Error
4117Process::Signal (int signal)
4118{
4119 Error error (WillSignal());
4120 if (error.Success())
4121 {
4122 error = DoSignal(signal);
4123 if (error.Success())
4124 DidSignal();
4125 }
4126 return error;
4127}
4128
Zachary Turner93749ab2015-03-03 21:51:25 +00004129void
Chaoren Linc963a222015-09-01 16:58:45 +00004130Process::SetUnixSignals(UnixSignalsSP &&signals_sp)
Zachary Turner93749ab2015-03-03 21:51:25 +00004131{
4132 assert (signals_sp && "null signals_sp");
4133 m_unix_signals_sp = signals_sp;
4134}
4135
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00004136const lldb::UnixSignalsSP &
Zachary Turner93749ab2015-03-03 21:51:25 +00004137Process::GetUnixSignals ()
4138{
4139 assert (m_unix_signals_sp && "null m_unix_signals_sp");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00004140 return m_unix_signals_sp;
Zachary Turner93749ab2015-03-03 21:51:25 +00004141}
4142
Greg Clayton514487e2011-02-15 21:59:32 +00004143lldb::ByteOrder
4144Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145{
Zachary Turner7529df92015-09-01 20:02:29 +00004146 return GetTarget().GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147}
4148
4149uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00004150Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004151{
Zachary Turner7529df92015-09-01 20:02:29 +00004152 return GetTarget().GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004153}
4154
Greg Clayton514487e2011-02-15 21:59:32 +00004155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156bool
4157Process::ShouldBroadcastEvent (Event *event_ptr)
4158{
4159 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
4160 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00004161 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00004162
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004163 switch (state)
4164 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165 case eStateDetached:
4166 case eStateExited:
4167 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00004168 m_stdio_communication.SynchronizeWithReadThread();
Pavel Labatha9a43372015-09-03 09:30:17 +00004169 m_stdio_communication.Disconnect();
4170 m_stdio_communication.StopReadThread();
4171 m_stdin_forward = false;
4172
Pavel Labath3f5df532015-03-12 10:12:41 +00004173 // fall-through
4174 case eStateConnected:
4175 case eStateAttaching:
4176 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004177 // These events indicate changes in the state of the debugging session, always report them.
4178 return_value = true;
4179 break;
4180 case eStateInvalid:
4181 // We stopped for no apparent reason, don't report it.
4182 return_value = false;
4183 break;
4184 case eStateRunning:
4185 case eStateStepping:
4186 // If we've started the target running, we handle the cases where we
4187 // are already running and where there is a transition from stopped to
4188 // running differently.
4189 // running -> running: Automatically suppress extra running events
4190 // stopped -> running: Report except when there is one or more no votes
4191 // and no yes votes.
4192 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004193 if (m_force_next_event_delivery)
4194 return_value = true;
4195 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004196 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004197 switch (m_last_broadcast_state)
4198 {
4199 case eStateRunning:
4200 case eStateStepping:
4201 // We always suppress multiple runnings with no PUBLIC stop in between.
4202 return_value = false;
4203 break;
4204 default:
4205 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004206 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004207 // events. If I run the lldb/test/thread/a.out file and
4208 // break at main.cpp:58, run and hit the breakpoints on
4209 // multiple threads, then somehow during the stepping over
4210 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004211
Jim Ingham1460e4b2014-01-10 23:46:59 +00004212 // This is a transition from stop to run.
4213 switch (m_thread_list.ShouldReportRun (event_ptr))
4214 {
4215 case eVoteYes:
4216 case eVoteNoOpinion:
4217 return_value = true;
4218 break;
4219 case eVoteNo:
4220 return_value = false;
4221 break;
4222 }
4223 break;
4224 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004225 }
4226 break;
4227 case eStateStopped:
4228 case eStateCrashed:
4229 case eStateSuspended:
4230 {
4231 // We've stopped. First see if we're going to restart the target.
4232 // If we are going to stop, then we always broadcast the event.
4233 // 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 +00004234 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004235
Pavel Labath3f5df532015-03-12 10:12:41 +00004236 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00004237 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004238 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004239 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004240 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004241 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004242 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004243 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004244 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4245 // so they can properly set their state.
4246 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004247 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004248 }
4249 else
4250 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004251 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4252 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004253
Jim Ingham0161b492013-02-09 01:29:05 +00004254 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4255 // Asking the thread list is also not likely to go well, since we are running again.
4256 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004257
Jim Ingham0161b492013-02-09 01:29:05 +00004258 if (!was_restarted)
4259 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004260
Jim Ingham221d51c2013-05-08 00:35:16 +00004261 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004262 {
Jim Ingham0161b492013-02-09 01:29:05 +00004263 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4264 if (log)
4265 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004266 should_resume, StateAsCString(state),
4267 was_restarted, stop_vote);
4268
Jim Ingham0161b492013-02-09 01:29:05 +00004269 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004270 {
4271 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004272 return_value = true;
4273 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004274 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004275 case eVoteNo:
4276 return_value = false;
4277 break;
4278 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004279
Jim Inghamcb95f342012-09-05 21:13:56 +00004280 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004281 {
4282 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004283 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4284 static_cast<void*>(event_ptr),
4285 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004286 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004287 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004288 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004289
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004290 }
4291 else
4292 {
4293 return_value = true;
4294 SynchronouslyNotifyStateChanged (state);
4295 }
4296 }
4297 }
Jim Ingham0161b492013-02-09 01:29:05 +00004298 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004299 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004300
Jim Ingham1460e4b2014-01-10 23:46:59 +00004301 // Forcing the next event delivery is a one shot deal. So reset it here.
4302 m_force_next_event_delivery = false;
4303
Jim Ingham0161b492013-02-09 01:29:05 +00004304 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4305 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4306 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4307 // because the PublicState reflects the last event pulled off the queue, and there may be several
4308 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4309 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004310
Jim Ingham0161b492013-02-09 01:29:05 +00004311 if (return_value)
4312 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004314 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004315 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004316 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004317 StateAsCString(m_last_broadcast_state),
4318 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004319 return return_value;
4320}
4321
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004322
4323bool
Jim Ingham60c915e2015-06-23 21:02:45 +00004324Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004325{
Greg Clayton5160ce52013-03-27 23:08:40 +00004326 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004327
Greg Clayton8b82f082011-04-12 05:54:46 +00004328 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004329 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004330 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4331
Jim Ingham60c915e2015-06-23 21:02:45 +00004332 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004333 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004334
4335 // Create a thread that watches our internal state and controls which
4336 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004337 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004338
Zachary Turner39de3112014-09-09 20:54:56 +00004339 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004340 {
Zachary Turner39de3112014-09-09 20:54:56 +00004341 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4342 if (already_running)
4343 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4344 else
4345 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004346 }
Jim Ingham372787f2012-04-07 00:00:41 +00004347 else
Todd Fiala17096d72014-07-16 19:03:16 +00004348 {
4349 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004350 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004351 else
Zachary Turner39de3112014-09-09 20:54:56 +00004352 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004353 }
4354
Jim Ingham076b3042012-04-10 01:21:57 +00004355 // Create the private state thread, and start it running.
Jim Ingham60c915e2015-06-23 21:02:45 +00004356 PrivateStateThreadArgs args = {this, is_secondary_thread};
4357 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) &args, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004358 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004359 {
4360 ResumePrivateStateThread();
4361 return true;
4362 }
4363 else
4364 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004365}
4366
4367void
4368Process::PausePrivateStateThread ()
4369{
4370 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4371}
4372
4373void
4374Process::ResumePrivateStateThread ()
4375{
4376 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4377}
4378
4379void
4380Process::StopPrivateStateThread ()
4381{
Greg Clayton8b82f082011-04-12 05:54:46 +00004382 if (PrivateStateThreadIsValid ())
4383 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004384 else
4385 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004386 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004387 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004388 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004389 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004390}
4391
4392void
4393Process::ControlPrivateStateThread (uint32_t signal)
4394{
Greg Clayton5160ce52013-03-27 23:08:40 +00004395 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004396
4397 assert (signal == eBroadcastInternalStateControlStop ||
4398 signal == eBroadcastInternalStateControlPause ||
4399 signal == eBroadcastInternalStateControlResume);
4400
4401 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004402 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004403
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004404 // Signal the private state thread. First we should copy this is case the
4405 // thread starts exiting since the private state thread will NULL this out
4406 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004407 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004408 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004409 {
4410 TimeValue timeout_time;
4411 bool timed_out;
4412
4413 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4414
4415 timeout_time = TimeValue::Now();
4416 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004417 if (log)
4418 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004419 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4420 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4421
4422 if (signal == eBroadcastInternalStateControlStop)
4423 {
4424 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004425 {
Zachary Turner39de3112014-09-09 20:54:56 +00004426 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004427 if (log)
4428 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4429 }
4430 else
4431 {
4432 if (log)
4433 log->Printf ("The control event killed the private state thread without having to cancel.");
4434 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004435
4436 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004437 private_state_thread.Join(&result);
4438 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004439 }
4440 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004441 else
4442 {
4443 if (log)
4444 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4445 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004446}
4447
4448void
Jim Inghamcfc09352012-07-27 23:57:19 +00004449Process::SendAsyncInterrupt ()
4450{
4451 if (PrivateStateThreadIsValid())
4452 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4453 else
4454 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4455}
4456
4457void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004458Process::HandlePrivateEvent (EventSP &event_sp)
4459{
Greg Clayton5160ce52013-03-27 23:08:40 +00004460 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004461 m_resume_requested = false;
4462
Jim Inghamaacc3182012-06-06 00:29:30 +00004463 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004464
Greg Clayton414f5d32011-01-25 02:58:48 +00004465 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004466
4467 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004468 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004469 {
Jim Ingham754ab982011-01-29 04:05:41 +00004470 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004471 if (log)
4472 log->Printf ("Ran next event action, result was %d.", action_result);
4473
Jim Inghambb3a2832011-01-29 01:49:25 +00004474 switch (action_result)
4475 {
4476 case NextEventAction::eEventActionSuccess:
4477 SetNextEventAction(NULL);
4478 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004479
Jim Inghambb3a2832011-01-29 01:49:25 +00004480 case NextEventAction::eEventActionRetry:
4481 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004482
Jim Inghambb3a2832011-01-29 01:49:25 +00004483 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004484 // Handle Exiting Here. If we already got an exited event,
4485 // we should just propagate it. Otherwise, swallow this event,
4486 // and set our state to exit so the next event will kill us.
4487 if (new_state != eStateExited)
4488 {
4489 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004490 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004491 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004492 SetNextEventAction(NULL);
4493 return;
4494 }
4495 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004496 break;
4497 }
4498 }
4499
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004500 // See if we should broadcast this state to external clients?
4501 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004502
4503 if (should_broadcast)
4504 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004505 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004506 if (log)
4507 {
Daniel Malead01b2952012-11-29 21:49:15 +00004508 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004509 __FUNCTION__,
4510 GetID(),
4511 StateAsCString(new_state),
4512 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004513 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004514 }
Jim Ingham9575d842011-03-11 03:53:59 +00004515 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004516 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004517 {
4518 // Only push the input handler if we aren't fowarding events,
4519 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004520 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004521 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4522 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004523 {
Greg Clayton44d93782014-01-27 23:43:24 +00004524 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004525 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4526 if (log)
4527 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4528 }
Greg Clayton44d93782014-01-27 23:43:24 +00004529 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004530 else if (StateIsStoppedState(new_state, false))
4531 {
4532 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4533 {
4534 // If the lldb_private::Debugger is handling the events, we don't
4535 // want to pop the process IOHandler here, we want to do it when
4536 // we receive the stopped event so we can carefully control when
4537 // the process IOHandler is popped because when we stop we want to
4538 // display some text stating how and why we stopped, then maybe some
4539 // process/thread/frame info, and then we want the "(lldb) " prompt
4540 // to show up. If we pop the process IOHandler here, then we will
4541 // cause the command interpreter to become the top IOHandler after
4542 // the process pops off and it will update its prompt right away...
4543 // See the Debugger.cpp file where it calls the function as
4544 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4545 // Otherwise we end up getting overlapping "(lldb) " prompts and
4546 // garbled output.
4547 //
4548 // If we aren't handling the events in the debugger (which is indicated
4549 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4550 // are hijacked, then we always pop the process IO handler manually.
4551 // Hijacking happens when the internal process state thread is running
4552 // thread plans, or when commands want to run in synchronous mode
4553 // and they call "process->WaitForProcessToStop()". An example of something
4554 // that will hijack the events is a simple expression:
4555 //
4556 // (lldb) expr (int)puts("hello")
4557 //
4558 // This will cause the internal process state thread to resume and halt
4559 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4560 // events) and we do need the IO handler to be pushed and popped
4561 // correctly.
4562
Zachary Turner7529df92015-09-01 20:02:29 +00004563 if (is_hijacked || GetTarget().GetDebugger().IsHandlingEvents() == false)
Greg Claytonb4874f12014-02-28 18:22:24 +00004564 PopProcessIOHandler ();
4565 }
4566 }
Jim Ingham9575d842011-03-11 03:53:59 +00004567
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004568 BroadcastEvent (event_sp);
4569 }
4570 else
4571 {
4572 if (log)
4573 {
Daniel Malead01b2952012-11-29 21:49:15 +00004574 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004575 __FUNCTION__,
4576 GetID(),
4577 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004578 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004579 }
4580 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004581 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004582}
4583
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004584thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004585Process::PrivateStateThread (void *arg)
4586{
Jim Ingham60c915e2015-06-23 21:02:45 +00004587 PrivateStateThreadArgs *real_args = static_cast<PrivateStateThreadArgs *> (arg);
4588 thread_result_t result = real_args->process->RunPrivateStateThread(real_args->is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004589 return result;
4590}
4591
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004592thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004593Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004594{
Jim Ingham076b3042012-04-10 01:21:57 +00004595 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004596 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004597
Greg Clayton5160ce52013-03-27 23:08:40 +00004598 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004599 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004600 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4601 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004602
4603 bool exit_now = false;
4604 while (!exit_now)
4605 {
4606 EventSP event_sp;
4607 WaitForEventsPrivate (NULL, event_sp, control_only);
4608 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4609 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004610 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004611 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4612 __FUNCTION__, static_cast<void*>(this), GetID(),
4613 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004614
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004615 switch (event_sp->GetType())
4616 {
4617 case eBroadcastInternalStateControlStop:
4618 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004619 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004620
4621 case eBroadcastInternalStateControlPause:
4622 control_only = true;
4623 break;
4624
4625 case eBroadcastInternalStateControlResume:
4626 control_only = false;
4627 break;
4628 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004629
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004630 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004631 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004632 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004633 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4634 {
4635 if (m_public_state.GetValue() == eStateAttaching)
4636 {
4637 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004638 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4639 __FUNCTION__, static_cast<void*>(this),
4640 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004641 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4642 }
4643 else
4644 {
4645 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004646 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4647 __FUNCTION__, static_cast<void*>(this),
4648 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004649 Halt();
4650 }
4651 continue;
4652 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004653
4654 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4655
4656 if (internal_state != eStateInvalid)
4657 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004658 if (m_clear_thread_plans_on_stop &&
4659 StateIsStoppedState(internal_state, true))
4660 {
4661 m_clear_thread_plans_on_stop = false;
4662 m_thread_list.DiscardThreadPlans();
4663 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004664 HandlePrivateEvent (event_sp);
4665 }
4666
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004667 if (internal_state == eStateInvalid ||
4668 internal_state == eStateExited ||
4669 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004670 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004671 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004672 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4673 __FUNCTION__, static_cast<void*>(this), GetID(),
4674 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004675
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004676 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004677 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004678 }
4679
Caroline Tice20ad3c42010-10-29 21:48:37 +00004680 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004681 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004682 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4683 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004684
Jim Ingham60c915e2015-06-23 21:02:45 +00004685 // If we are a secondary thread, then the primary thread we are working for will have already
4686 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4687 // try to change it on the way out.
4688 if (!is_secondary_thread)
4689 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004690 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004691 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004692 return NULL;
4693}
4694
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004695//------------------------------------------------------------------
4696// Process Event Data
4697//------------------------------------------------------------------
4698
4699Process::ProcessEventData::ProcessEventData () :
4700 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004701 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004702 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004703 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004704 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004705 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004706{
4707}
4708
4709Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4710 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004711 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004712 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004713 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004714 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004715 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004716{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004717 if (process_sp)
4718 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004719}
4720
4721Process::ProcessEventData::~ProcessEventData()
4722{
4723}
4724
4725const ConstString &
4726Process::ProcessEventData::GetFlavorString ()
4727{
4728 static ConstString g_flavor ("Process::ProcessEventData");
4729 return g_flavor;
4730}
4731
4732const ConstString &
4733Process::ProcessEventData::GetFlavor () const
4734{
4735 return ProcessEventData::GetFlavorString ();
4736}
4737
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004738void
4739Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4740{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004741 ProcessSP process_sp(m_process_wp.lock());
4742
4743 if (!process_sp)
4744 return;
4745
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004746 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004747 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4748 // the public event queue, then other times when we're pretending that this is where we stopped at the
4749 // end of expression evaluation. m_update_state is used to distinguish these
4750 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004751 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004752 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004753 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004754
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004755 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004756
4757 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4758 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4759 // end up restarting the process.
4760 if (m_interrupted)
4761 return;
4762
4763 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004764 if (m_state == eStateStopped && ! m_restarted)
Greg Clayton2e309072015-07-17 23:42:28 +00004765 {
4766 // Let process subclasses know we are about to do a public stop and
4767 // do anything they might need to in order to speed up register and
4768 // memory accesses.
4769 process_sp->WillPublicStop();
4770
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004771 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004772 uint32_t num_threads = curr_thread_list.GetSize();
4773 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004774
Jim Ingham4b536182011-08-09 02:12:22 +00004775 // The actions might change one of the thread's stop_info's opinions about whether we should
4776 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004777
4778 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4779 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4780 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4781 // 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
4782 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004783 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004784 for (idx = 0; idx < num_threads; ++idx)
4785 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4786
Jim Inghamc7078c22012-12-13 22:24:15 +00004787 // Use this to track whether we should continue from here. We will only continue the target running if
4788 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4789 // then it doesn't matter what the other threads say...
4790
4791 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004792
Jim Ingham0ad7e052013-04-25 02:04:59 +00004793 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4794 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4795 // thing to do is, and it's better to let the user decide than continue behind their backs.
4796
4797 bool does_anybody_have_an_opinion = false;
4798
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004799 for (idx = 0; idx < num_threads; ++idx)
4800 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004801 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004802 if (curr_thread_list.GetSize() != num_threads)
4803 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004804 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004805 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004806 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 +00004807 break;
4808 }
4809
4810 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4811
4812 if (thread_sp->GetIndexID() != thread_index_array[idx])
4813 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004814 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004815 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004816 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004817 idx,
4818 thread_index_array[idx],
4819 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004820 break;
4821 }
4822
Jim Inghamb15bfc72010-10-20 00:39:53 +00004823 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004824 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004825 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004826 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004827 bool this_thread_wants_to_stop;
4828 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004829 {
Jim Ingham0161b492013-02-09 01:29:05 +00004830 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4831 }
4832 else
4833 {
4834 stop_info_sp->PerformAction(event_ptr);
4835 // The stop action might restart the target. If it does, then we want to mark that in the
4836 // event so that whoever is receiving it will know to wait for the running event and reflect
4837 // that state appropriately.
4838 // We also need to stop processing actions, since they aren't expecting the target to be running.
4839
4840 // FIXME: we might have run.
4841 if (stop_info_sp->HasTargetRunSinceMe())
4842 {
4843 SetRestarted (true);
4844 break;
4845 }
4846
4847 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004848 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004849
Jim Inghamc7078c22012-12-13 22:24:15 +00004850 if (still_should_stop == false)
4851 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004852 }
4853 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004854
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004855
Jim Inghama8ca6e22013-05-03 23:04:37 +00004856 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004857 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004858 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004859 {
4860 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004861 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004862 // Use the public resume method here, since this is just
4863 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004864 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004865 }
4866 else
4867 {
4868 // If we didn't restart, run the Stop Hooks here:
4869 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004870 process_sp->GetTarget().RunStopHooks();
4871 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004872 SetRestarted(true);
4873 }
Jim Ingham9575d842011-03-11 03:53:59 +00004874 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004875 }
4876}
4877
4878void
4879Process::ProcessEventData::Dump (Stream *s) const
4880{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004881 ProcessSP process_sp(m_process_wp.lock());
4882
4883 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004884 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004885 static_cast<void*>(process_sp.get()), process_sp->GetID());
4886 else
4887 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004888
Greg Clayton8b82f082011-04-12 05:54:46 +00004889 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004890}
4891
4892const Process::ProcessEventData *
4893Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4894{
4895 if (event_ptr)
4896 {
4897 const EventData *event_data = event_ptr->GetData();
4898 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4899 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4900 }
4901 return NULL;
4902}
4903
4904ProcessSP
4905Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4906{
4907 ProcessSP process_sp;
4908 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4909 if (data)
4910 process_sp = data->GetProcessSP();
4911 return process_sp;
4912}
4913
4914StateType
4915Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4916{
4917 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4918 if (data == NULL)
4919 return eStateInvalid;
4920 else
4921 return data->GetState();
4922}
4923
4924bool
4925Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4926{
4927 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4928 if (data == NULL)
4929 return false;
4930 else
4931 return data->GetRestarted();
4932}
4933
4934void
4935Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4936{
4937 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4938 if (data != NULL)
4939 data->SetRestarted(new_value);
4940}
4941
Jim Ingham0161b492013-02-09 01:29:05 +00004942size_t
4943Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4944{
4945 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4946 if (data != NULL)
4947 return data->GetNumRestartedReasons();
4948 else
4949 return 0;
4950}
4951
4952const char *
4953Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4954{
4955 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4956 if (data != NULL)
4957 return data->GetRestartedReasonAtIndex(idx);
4958 else
4959 return NULL;
4960}
4961
4962void
4963Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4964{
4965 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4966 if (data != NULL)
4967 data->AddRestartedReason(reason);
4968}
4969
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004970bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004971Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4972{
4973 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4974 if (data == NULL)
4975 return false;
4976 else
4977 return data->GetInterrupted ();
4978}
4979
4980void
4981Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4982{
4983 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4984 if (data != NULL)
4985 data->SetInterrupted(new_value);
4986}
4987
4988bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004989Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4990{
4991 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4992 if (data)
4993 {
4994 data->SetUpdateStateOnRemoval();
4995 return true;
4996 }
4997 return false;
4998}
4999
Greg Claytond9e416c2012-02-18 05:35:26 +00005000lldb::TargetSP
5001Process::CalculateTarget ()
5002{
Zachary Turner7529df92015-09-01 20:02:29 +00005003 return m_target_sp.lock();
Greg Claytond9e416c2012-02-18 05:35:26 +00005004}
5005
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005006void
Greg Clayton0603aa92010-10-04 01:05:56 +00005007Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005008{
Zachary Turner7529df92015-09-01 20:02:29 +00005009 exe_ctx.SetTargetPtr (&GetTarget());
Greg Claytonc14ee322011-09-22 04:58:26 +00005010 exe_ctx.SetProcessPtr (this);
5011 exe_ctx.SetThreadPtr(NULL);
5012 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00005013}
5014
Greg Claytone996fd32011-03-08 22:40:15 +00005015//uint32_t
5016//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
5017//{
5018// return 0;
5019//}
5020//
5021//ArchSpec
5022//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
5023//{
5024// return Host::GetArchSpecForExistingProcess (pid);
5025//}
5026//
5027//ArchSpec
5028//Process::GetArchSpecForExistingProcess (const char *process_name)
5029//{
5030// return Host::GetArchSpecForExistingProcess (process_name);
5031//}
5032//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005033void
5034Process::AppendSTDOUT (const char * s, size_t len)
5035{
Greg Clayton3af9ea52010-11-18 05:57:03 +00005036 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005037 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00005038 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005039}
5040
5041void
Greg Clayton93e86192011-11-13 04:45:22 +00005042Process::AppendSTDERR (const char * s, size_t len)
5043{
5044 Mutex::Locker locker (m_stdio_communication_mutex);
5045 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00005046 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00005047}
5048
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005049void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005050Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005051{
5052 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005053 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005054 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
5055}
5056
5057size_t
5058Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
5059{
5060 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005061 if (m_profile_data.empty())
5062 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005063
5064 std::string &one_profile_data = m_profile_data.front();
5065 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005066 if (bytes_available > 0)
5067 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005068 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005069 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005070 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
5071 static_cast<void*>(buf),
5072 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005073 if (bytes_available > buf_size)
5074 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005075 memcpy(buf, one_profile_data.c_str(), buf_size);
5076 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005077 bytes_available = buf_size;
5078 }
5079 else
5080 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00005081 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00005082 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00005083 }
5084 }
5085 return bytes_available;
5086}
5087
5088
Greg Clayton93e86192011-11-13 04:45:22 +00005089//------------------------------------------------------------------
5090// Process STDIO
5091//------------------------------------------------------------------
5092
5093size_t
5094Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
5095{
5096 Mutex::Locker locker(m_stdio_communication_mutex);
5097 size_t bytes_available = m_stdout_data.size();
5098 if (bytes_available > 0)
5099 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005100 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005101 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005102 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
5103 static_cast<void*>(buf),
5104 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005105 if (bytes_available > buf_size)
5106 {
5107 memcpy(buf, m_stdout_data.c_str(), buf_size);
5108 m_stdout_data.erase(0, buf_size);
5109 bytes_available = buf_size;
5110 }
5111 else
5112 {
5113 memcpy(buf, m_stdout_data.c_str(), bytes_available);
5114 m_stdout_data.clear();
5115 }
5116 }
5117 return bytes_available;
5118}
5119
5120
5121size_t
5122Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
5123{
5124 Mutex::Locker locker(m_stdio_communication_mutex);
5125 size_t bytes_available = m_stderr_data.size();
5126 if (bytes_available > 0)
5127 {
Greg Clayton5160ce52013-03-27 23:08:40 +00005128 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00005129 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005130 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5131 static_cast<void*>(buf),
5132 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00005133 if (bytes_available > buf_size)
5134 {
5135 memcpy(buf, m_stderr_data.c_str(), buf_size);
5136 m_stderr_data.erase(0, buf_size);
5137 bytes_available = buf_size;
5138 }
5139 else
5140 {
5141 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5142 m_stderr_data.clear();
5143 }
5144 }
5145 return bytes_available;
5146}
5147
5148void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005149Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
5150{
5151 Process *process = (Process *) baton;
5152 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
5153}
5154
Greg Clayton44d93782014-01-27 23:43:24 +00005155class IOHandlerProcessSTDIO :
5156 public IOHandler
5157{
5158public:
5159 IOHandlerProcessSTDIO (Process *process,
5160 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00005161 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00005162 m_process (process),
5163 m_read_file (),
5164 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00005165 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00005166 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005167 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00005168 m_read_file.SetDescriptor(GetInputFD(), false);
5169 }
5170
5171 virtual
5172 ~IOHandlerProcessSTDIO ()
5173 {
5174
5175 }
5176
Greg Clayton44d93782014-01-27 23:43:24 +00005177 // Each IOHandler gets to run until it is done. It should read data
5178 // from the "in" and place output into "out" and "err and return
5179 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00005180 void
5181 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00005182 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005183 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00005184 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005185 SetIsDone(true);
5186 return;
5187 }
5188
5189 SetIsDone(false);
5190 const int read_fd = m_read_file.GetDescriptor();
5191 TerminalState terminal_state;
5192 terminal_state.Save (read_fd, false);
5193 Terminal terminal(read_fd);
5194 terminal.SetCanonical(false);
5195 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005196// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005197#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005198 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
5199 while (!GetIsDone())
5200 {
5201 fd_set read_fdset;
5202 FD_ZERO (&read_fdset);
5203 FD_SET (read_fd, &read_fdset);
5204 FD_SET (pipe_read_fd, &read_fdset);
5205 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5206 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5207 if (num_set_fds < 0)
5208 {
5209 const int select_errno = errno;
5210
5211 if (select_errno != EINTR)
5212 SetIsDone(true);
5213 }
5214 else if (num_set_fds > 0)
5215 {
5216 char ch = 0;
5217 size_t n;
5218 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00005219 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005220 n = 1;
5221 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005222 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005223 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00005224 SetIsDone(true);
5225 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005226 else
5227 SetIsDone(true);
5228 }
5229 if (FD_ISSET (pipe_read_fd, &read_fdset))
5230 {
5231 size_t bytes_read;
5232 // Consume the interrupt byte
5233 Error error = m_pipe.Read(&ch, 1, bytes_read);
5234 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00005235 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005236 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00005237 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005238 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00005239 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005240 break;
5241 case 'i':
5242 if (StateIsRunningState(m_process->GetState()))
Pavel Labathfcc7f662015-10-07 15:11:11 +00005243 m_process->SendAsyncInterrupt();
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005244 break;
Greg Clayton44d93782014-01-27 23:43:24 +00005245 }
5246 }
5247 }
Greg Clayton44d93782014-01-27 23:43:24 +00005248 }
Greg Clayton44d93782014-01-27 23:43:24 +00005249 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005250#endif
5251 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005252 }
5253
Pavel Labath44464872015-05-27 12:40:32 +00005254 void
5255 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005256 {
Greg Clayton19e11352014-02-26 22:47:33 +00005257 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005258 size_t bytes_written = 0;
5259 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005260 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005261
Pavel Labath44464872015-05-27 12:40:32 +00005262 bool
5263 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005264 {
Greg Clayton19e11352014-02-26 22:47:33 +00005265 // Do only things that are safe to do in an interrupt context (like in
5266 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5267 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
Pavel Labathfcc7f662015-10-07 15:11:11 +00005268 // that was written to the pipe and then call m_process->SendAsyncInterrupt()
5269 // from a much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005270 if (m_active)
5271 {
5272 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005273 size_t bytes_written = 0;
5274 Error result = m_pipe.Write(&ch, 1, bytes_written);
5275 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005276 }
5277 else
5278 {
5279 // This IOHandler might be pushed on the stack, but not being run currently
5280 // so do the right thing if we aren't actively watching for STDIN by sending
5281 // the interrupt to the process. Otherwise the write to the pipe above would
5282 // do nothing. This can happen when the command interpreter is running and
5283 // gets a "expression ...". It will be on the IOHandler thread and sending
5284 // the input is complete to the delegate which will cause the expression to
5285 // run, which will push the process IO handler, but not run it.
5286
5287 if (StateIsRunningState(m_process->GetState()))
5288 {
5289 m_process->SendAsyncInterrupt();
5290 return true;
5291 }
5292 }
5293 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005294 }
Greg Clayton44d93782014-01-27 23:43:24 +00005295
Pavel Labath44464872015-05-27 12:40:32 +00005296 void
5297 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005298 {
5299
5300 }
5301
5302protected:
5303 Process *m_process;
5304 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5305 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005306 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005307};
5308
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005309void
Greg Clayton44d93782014-01-27 23:43:24 +00005310Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005311{
5312 // First set up the Read Thread for reading/handling process I/O
5313
Greg Clayton44d93782014-01-27 23:43:24 +00005314 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005315
5316 if (conn_ap.get())
5317 {
5318 m_stdio_communication.SetConnection (conn_ap.release());
5319 if (m_stdio_communication.IsConnected())
5320 {
5321 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5322 m_stdio_communication.StartReadThread();
5323
5324 // Now read thread is set up, set up input reader.
5325
5326 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005327 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005328 }
5329 }
5330}
5331
Greg Claytonb4874f12014-02-28 18:22:24 +00005332bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005333Process::ProcessIOHandlerIsActive ()
5334{
5335 IOHandlerSP io_handler_sp (m_process_input_reader);
5336 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005337 return GetTarget().GetDebugger().IsTopIOHandler (io_handler_sp);
Greg Clayton6fea17e2014-03-03 19:15:20 +00005338 return false;
5339}
5340bool
Greg Clayton44d93782014-01-27 23:43:24 +00005341Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005342{
Greg Clayton44d93782014-01-27 23:43:24 +00005343 IOHandlerSP io_handler_sp (m_process_input_reader);
5344 if (io_handler_sp)
5345 {
Pavel Labath44464872015-05-27 12:40:32 +00005346 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5347 if (log)
5348 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5349
Greg Clayton44d93782014-01-27 23:43:24 +00005350 io_handler_sp->SetIsDone(false);
Zachary Turner7529df92015-09-01 20:02:29 +00005351 GetTarget().GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005352 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005353 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005354 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005355}
5356
Greg Claytonb4874f12014-02-28 18:22:24 +00005357bool
Greg Clayton44d93782014-01-27 23:43:24 +00005358Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005359{
Greg Clayton44d93782014-01-27 23:43:24 +00005360 IOHandlerSP io_handler_sp (m_process_input_reader);
5361 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005362 return GetTarget().GetDebugger().PopIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005363 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005364}
5365
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005366// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005367void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005368Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005369{
Greg Clayton6920b522012-08-22 18:39:03 +00005370 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005371}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005372
Greg Clayton99d0faf2010-11-18 23:32:35 +00005373void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005374Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005375{
Greg Clayton6920b522012-08-22 18:39:03 +00005376 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005377}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005378
Jim Inghamc60963c2015-10-12 19:11:03 +00005379namespace
5380{
5381 // RestorePlanState is used to record the "is private", "is master" and "okay to discard" fields of
5382 // the plan we are running, and reset it on Clean or on destruction.
5383 // It will only reset the state once, so you can call Clean and then monkey with the state and it
5384 // won't get reset on you again.
5385
5386 class RestorePlanState
5387 {
5388 public:
5389 RestorePlanState (lldb::ThreadPlanSP thread_plan_sp) :
5390 m_thread_plan_sp(thread_plan_sp),
5391 m_already_reset(false)
5392 {
5393 if (m_thread_plan_sp)
5394 {
5395 m_private = m_thread_plan_sp->GetPrivate();
5396 m_is_master = m_thread_plan_sp->IsMasterPlan();
5397 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5398 }
5399 }
5400
5401 ~RestorePlanState()
5402 {
5403 Clean();
5404 }
5405
5406 void
5407 Clean ()
5408 {
5409 if (!m_already_reset && m_thread_plan_sp)
5410 {
5411 m_already_reset = true;
5412 m_thread_plan_sp->SetPrivate(m_private);
5413 m_thread_plan_sp->SetIsMasterPlan (m_is_master);
5414 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5415 }
5416 }
5417 private:
5418 lldb::ThreadPlanSP m_thread_plan_sp;
5419 bool m_already_reset;
5420 bool m_private;
5421 bool m_is_master;
5422 bool m_okay_to_discard;
5423 };
5424}
5425
Jim Ingham1624a2d2014-05-05 02:26:40 +00005426ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005427Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005428 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005429 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005430 Stream &errors)
5431{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005432 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005433
Jim Ingham77787032011-01-20 02:03:18 +00005434 if (thread_plan_sp.get() == NULL)
5435 {
5436 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005437 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005438 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005439
Jim Ingham7d7931d2013-03-28 00:05:34 +00005440 if (!thread_plan_sp->ValidatePlan(NULL))
5441 {
5442 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005443 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005444 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005445
Greg Claytonc14ee322011-09-22 04:58:26 +00005446 if (exe_ctx.GetProcessPtr() != this)
5447 {
5448 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005449 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005450 }
5451
5452 Thread *thread = exe_ctx.GetThreadPtr();
5453 if (thread == NULL)
5454 {
5455 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005456 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005457 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005458
Jim Inghamc60963c2015-10-12 19:11:03 +00005459 // We need to change some of the thread plan attributes for the thread plan runner. This will restore them
5460 // when we are done:
5461
5462 RestorePlanState thread_plan_restorer(thread_plan_sp);
5463
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005464 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5465 // For that to be true the plan can't be private - since private plans suppress themselves in the
5466 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005467
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005468 thread_plan_sp->SetPrivate(false);
Jim Inghamc60963c2015-10-12 19:11:03 +00005469
5470 // The plans run with RunThreadPlan also need to be terminal master plans or when they are done we will end
5471 // up asking the plan above us whether we should stop, which may give the wrong answer.
5472
5473 thread_plan_sp->SetIsMasterPlan (true);
5474 thread_plan_sp->SetOkayToDiscard(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005475
Jim Ingham444586b2011-01-24 06:34:17 +00005476 if (m_private_state.GetValue() != eStateStopped)
5477 {
5478 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005479 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005480 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005481
Jim Ingham66243842011-08-13 00:56:10 +00005482 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005483 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005484 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005485 if (!selected_frame_sp)
5486 {
5487 thread->SetSelectedFrame(0);
5488 selected_frame_sp = thread->GetSelectedFrame();
5489 if (!selected_frame_sp)
5490 {
5491 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005492 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005493 }
5494 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005495
Jim Ingham11b0e052013-02-19 23:22:45 +00005496 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005497
5498 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5499 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005500
Greg Claytonc14ee322011-09-22 04:58:26 +00005501 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005502
Jim Ingham66243842011-08-13 00:56:10 +00005503 uint32_t selected_tid;
5504 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005505 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005506 {
5507 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005508 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005509 }
5510 else
5511 {
5512 selected_tid = LLDB_INVALID_THREAD_ID;
5513 }
5514
Zachary Turner39de3112014-09-09 20:54:56 +00005515 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005516 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005517 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005518
Greg Clayton5160ce52013-03-27 23:08:40 +00005519 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005520 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005521 {
Jim Ingham076b3042012-04-10 01:21:57 +00005522 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5523 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005524 // 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 +00005525 // we are fielding public events here.
5526 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005527 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 +00005528
Jim Ingham372787f2012-04-07 00:00:41 +00005529 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005530
5531 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5532 // returning control here.
5533 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5534 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5535 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5536 // do just what we want.
5537 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5538 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5539 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5540 old_state = m_public_state.GetValue();
5541 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005542
Jim Ingham076b3042012-04-10 01:21:57 +00005543 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005544 StartPrivateStateThread(true);
5545 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005546
Jim Ingham372787f2012-04-07 00:00:41 +00005547 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005548
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005549 if (options.GetDebug())
5550 {
5551 // In this case, we aren't actually going to run, we just want to stop right away.
5552 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5553 // FIXME: To make this prettier we should invent some stop reason for this, but that
5554 // is only cosmetic, and this functionality is only of use to lldb developers who can
5555 // live with not pretty...
5556 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005557 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005558 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005559
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005560 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005561
Sean Callanana46ec452012-07-11 21:31:24 +00005562 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005563
Jim Ingham77787032011-01-20 02:03:18 +00005564 {
Sean Callanana46ec452012-07-11 21:31:24 +00005565 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5566 // restored on exit to the function.
5567 //
5568 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5569 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005570
Sean Callanana46ec452012-07-11 21:31:24 +00005571 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005572
Jim Inghamf48169b2010-11-30 02:22:11 +00005573 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005574 {
5575 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005576 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005577 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005578 thread->GetIndexID(),
5579 thread->GetID(),
5580 s.GetData());
5581 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005582
Sean Callanana46ec452012-07-11 21:31:24 +00005583 bool got_event;
5584 lldb::EventSP event_sp;
5585 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005586
Sean Callanana46ec452012-07-11 21:31:24 +00005587 TimeValue* timeout_ptr = NULL;
5588 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005589
Jim Ingham0161b492013-02-09 01:29:05 +00005590 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 +00005591 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005592 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005593 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005594
Jim Ingham0161b492013-02-09 01:29:05 +00005595 // This is just for accounting:
5596 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005597
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005598 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005599 uint32_t one_thread_timeout_usec;
5600 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005601
5602 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5603 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5604 // first timeout already.
5605
5606 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005607 {
5608 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005609 one_thread_timeout_usec = 0;
5610 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005611 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005612 else
Jim Ingham0161b492013-02-09 01:29:05 +00005613 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005614 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005615
Jim Ingham914f4e72014-03-28 21:58:28 +00005616 // If the overall wait is forever, then we only need to set the one thread timeout:
5617 if (timeout_usec == 0)
5618 {
Ed Maste801335c2014-03-31 19:28:14 +00005619 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005620 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005621 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005622 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005623 }
Jim Ingham0161b492013-02-09 01:29:05 +00005624 else
5625 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005626 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5627 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5628 uint64_t computed_one_thread_timeout;
5629 if (option_one_thread_timeout != 0)
5630 {
5631 if (timeout_usec < option_one_thread_timeout)
5632 {
5633 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005634 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005635 }
5636 computed_one_thread_timeout = option_one_thread_timeout;
5637 }
5638 else
5639 {
5640 computed_one_thread_timeout = timeout_usec / 2;
5641 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5642 computed_one_thread_timeout = default_one_thread_timeout_usec;
5643 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005644 one_thread_timeout_usec = computed_one_thread_timeout;
5645 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5646
Jim Ingham0161b492013-02-09 01:29:05 +00005647 }
Jim Ingham0161b492013-02-09 01:29:05 +00005648 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005649
5650 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005651 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 +00005652 options.GetStopOthers(),
5653 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005654 before_first_timeout,
5655 one_thread_timeout_usec,
5656 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005657
Jim Ingham1460e4b2014-01-10 23:46:59 +00005658 // This isn't going to work if there are unfetched events on the queue.
5659 // Are there cases where we might want to run the remaining events here, and then try to
5660 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005661
Jim Ingham1460e4b2014-01-10 23:46:59 +00005662 Event *other_events = listener.PeekAtNextEvent();
5663 if (other_events != NULL)
5664 {
5665 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005666 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005667 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005668
Jim Ingham1460e4b2014-01-10 23:46:59 +00005669 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5670 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5671 // event coalescing to cause us to lose OUR running event...
5672 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005673
Jim Ingham8559a352012-11-26 23:52:18 +00005674 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5675 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005676
5677#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5678 // It's pretty much impossible to write test cases for things like:
5679 // One thread timeout expires, I go to halt, but the process already stopped
5680 // on the function call stop breakpoint. Turning on this define will make us not
5681 // fetch the first event till after the halt. So if you run a quick function, it will have
5682 // completed, and the completion event will be waiting, when you interrupt for halt.
5683 // The expression evaluation should still succeed.
5684 bool miss_first_event = true;
5685#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005686 TimeValue one_thread_timeout;
5687 TimeValue final_timeout;
5688
Jim Ingham35878c42014-04-08 21:33:21 +00005689
Sean Callanana46ec452012-07-11 21:31:24 +00005690 while (1)
5691 {
5692 // We usually want to resume the process if we get to the top of the loop.
5693 // The only exception is if we get two running events with no intervening
5694 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005695 if (log)
5696 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5697 do_resume,
5698 handle_running_event,
5699 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005700
Jim Ingham184e9812013-01-15 02:47:48 +00005701 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005702 {
5703 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005704
Jim Ingham184e9812013-01-15 02:47:48 +00005705 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005706 {
Jim Ingham0161b492013-02-09 01:29:05 +00005707 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005708 Error resume_error = PrivateResume ();
5709 if (!resume_error.Success())
5710 {
Jim Ingham0161b492013-02-09 01:29:05 +00005711 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5712 num_resumes,
5713 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005714 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005715 break;
5716 }
Sean Callanana46ec452012-07-11 21:31:24 +00005717 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005718
Jim Ingham0161b492013-02-09 01:29:05 +00005719 TimeValue resume_timeout = TimeValue::Now();
5720 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005721
Jim Ingham0161b492013-02-09 01:29:05 +00005722 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005723 if (!got_event)
5724 {
5725 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005726 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5727 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005728
Jim Ingham0161b492013-02-09 01:29:05 +00005729 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005730 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005731 break;
5732 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005733
Sean Callanana46ec452012-07-11 21:31:24 +00005734 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005735
Sean Callanana46ec452012-07-11 21:31:24 +00005736 if (stop_state != eStateRunning)
5737 {
Jim Ingham0161b492013-02-09 01:29:05 +00005738 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005739
Jim Ingham0161b492013-02-09 01:29:05 +00005740 if (stop_state == eStateStopped)
5741 {
5742 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5743 if (log)
5744 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5745 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5746 num_resumes,
5747 StateAsCString(stop_state),
5748 restarted,
5749 do_resume,
5750 handle_running_event);
5751 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005752
Jim Ingham0161b492013-02-09 01:29:05 +00005753 if (restarted)
5754 {
5755 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5756 // event here. But if I do, the best thing is to Halt and then get out of here.
5757 Halt();
5758 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005759
Jim Ingham35e1bda2012-10-16 21:41:58 +00005760 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5761 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005762 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005763 break;
5764 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005765
Sean Callanana46ec452012-07-11 21:31:24 +00005766 if (log)
5767 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5768 // We need to call the function synchronously, so spin waiting for it to return.
5769 // If we get interrupted while executing, we're going to lose our context, and
5770 // won't be able to gather the result at this point.
5771 // We set the timeout AFTER the resume, since the resume takes some time and we
5772 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005773 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005774 else
5775 {
Sean Callanana46ec452012-07-11 21:31:24 +00005776 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005777 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005778 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005779
Jim Ingham0161b492013-02-09 01:29:05 +00005780 if (before_first_timeout)
5781 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005782 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005783 {
5784 one_thread_timeout = TimeValue::Now();
5785 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005786 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005787 }
Jim Ingham0161b492013-02-09 01:29:05 +00005788 else
5789 {
5790 if (timeout_usec == 0)
5791 timeout_ptr = NULL;
5792 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005793 {
5794 final_timeout = TimeValue::Now();
5795 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005796 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005797 }
Jim Ingham0161b492013-02-09 01:29:05 +00005798 }
5799 }
5800 else
5801 {
5802 if (timeout_usec == 0)
5803 timeout_ptr = NULL;
5804 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005805 {
5806 final_timeout = TimeValue::Now();
5807 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005808 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005809 }
Jim Ingham0161b492013-02-09 01:29:05 +00005810 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005811
Jim Ingham0161b492013-02-09 01:29:05 +00005812 do_resume = true;
5813 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005814
Sean Callanana46ec452012-07-11 21:31:24 +00005815 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005816 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005817
Jim Ingham0f16e732011-02-08 05:20:59 +00005818 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005819 {
Sean Callanana46ec452012-07-11 21:31:24 +00005820 if (timeout_ptr)
5821 {
Matt Kopec676a4872013-02-21 23:55:31 +00005822 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005823 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5824 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005825 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005826 else
Sean Callanana46ec452012-07-11 21:31:24 +00005827 {
5828 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5829 }
5830 }
Jim Ingham35878c42014-04-08 21:33:21 +00005831
5832#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5833 // See comment above...
5834 if (miss_first_event)
5835 {
5836 usleep(1000);
5837 miss_first_event = false;
5838 got_event = false;
5839 }
5840 else
5841#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005842 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005843
Sean Callanana46ec452012-07-11 21:31:24 +00005844 if (got_event)
5845 {
5846 if (event_sp.get())
5847 {
5848 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005849 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005850 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005851 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005852 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005853 errors.Printf ("Execution halted by user interrupt.");
5854 if (log)
5855 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005856 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005857 }
5858 else
5859 {
5860 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5861 if (log)
5862 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005863
Jim Inghamcfc09352012-07-27 23:57:19 +00005864 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005865 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005866 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005867 {
Jim Ingham0161b492013-02-09 01:29:05 +00005868 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005869 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5870 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005871 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005872 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005873 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005874 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005875 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005876 }
5877 else
5878 {
Jim Ingham0161b492013-02-09 01:29:05 +00005879 // If we were restarted, we just need to go back up to fetch another event.
5880 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005881 {
5882 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005883 {
5884 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5885 }
5886 keep_going = true;
5887 do_resume = false;
5888 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005889
Jim Inghamcfc09352012-07-27 23:57:19 +00005890 }
5891 else
5892 {
Jim Ingham0161b492013-02-09 01:29:05 +00005893 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5894 StopReason stop_reason = eStopReasonInvalid;
5895 if (stop_info_sp)
5896 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005897
Jim Ingham0161b492013-02-09 01:29:05 +00005898 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5899 // it is OUR plan that is complete?
5900 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005901 {
5902 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005903 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
Jim Inghamc60963c2015-10-12 19:11:03 +00005904
5905 // Restore the plan state so it will get reported as intended when we are done.
5906 thread_plan_restorer.Clean();
5907
Jim Ingham8646d3c2014-05-05 02:47:44 +00005908 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005909 }
5910 else
5911 {
Jim Ingham0161b492013-02-09 01:29:05 +00005912 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005913 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005914 {
5915 if (log)
5916 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005917 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005918 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005919 {
Jim Inghamc60963c2015-10-12 19:11:03 +00005920 // Restore the plan state and then force Private to false. We are
5921 // going to stop because of this plan so we need it to become a public
5922 // plan or it won't report correctly when we continue to its termination
5923 // later on.
5924 thread_plan_restorer.Clean();
5925 if (thread_plan_sp)
5926 thread_plan_sp->SetPrivate(false);
Sean Callanan4b388c92013-07-30 19:54:09 +00005927 event_to_broadcast_sp = event_sp;
5928 }
Jim Ingham0161b492013-02-09 01:29:05 +00005929 }
Jim Ingham184e9812013-01-15 02:47:48 +00005930 else
Jim Ingham0161b492013-02-09 01:29:05 +00005931 {
5932 if (log)
5933 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005934 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005935 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005936 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005937 }
Jim Ingham184e9812013-01-15 02:47:48 +00005938 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005939 }
Sean Callanana46ec452012-07-11 21:31:24 +00005940 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005941 }
5942 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005943
Jim Inghamcfc09352012-07-27 23:57:19 +00005944 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005945 // This shouldn't really happen, but sometimes we do get two running events without an
5946 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005947 do_resume = false;
5948 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005949 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005950 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005951
Jim Inghamcfc09352012-07-27 23:57:19 +00005952 default:
5953 if (log)
5954 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005955
Jim Inghamcfc09352012-07-27 23:57:19 +00005956 if (stop_state == eStateExited)
5957 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005958
Sean Callananbf154da2012-08-08 17:35:10 +00005959 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005960 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005961 break;
5962 }
Sean Callanana46ec452012-07-11 21:31:24 +00005963 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005964
Sean Callanana46ec452012-07-11 21:31:24 +00005965 if (keep_going)
5966 continue;
5967 else
5968 break;
5969 }
5970 else
5971 {
5972 if (log)
5973 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005974 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005975 break;
5976 }
5977 }
5978 else
5979 {
5980 // If we didn't get an event that means we've timed out...
5981 // We will interrupt the process here. Depending on what we were asked to do we will
5982 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005983
Sean Callanana46ec452012-07-11 21:31:24 +00005984 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005985 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005986 {
Jim Ingham0161b492013-02-09 01:29:05 +00005987 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005988 {
5989 if (timeout_usec != 0)
5990 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005991 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005992 "running for %" PRIu32 " usec with all threads enabled.",
5993 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005994 }
5995 else
5996 {
5997 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005998 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005999 }
6000 }
Sean Callanana46ec452012-07-11 21:31:24 +00006001 else
6002 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00006003 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00006004 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00006005 }
6006 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00006007 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00006008 "abandoning execution.",
6009 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00006010 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006011
Jim Ingham0161b492013-02-09 01:29:05 +00006012 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
6013 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
6014 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
6015 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
6016 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006017
Jim Ingham0161b492013-02-09 01:29:05 +00006018 bool back_to_top = true;
6019 uint32_t try_halt_again = 0;
6020 bool do_halt = true;
6021 const uint32_t num_retries = 5;
6022 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00006023 {
Jim Ingham0161b492013-02-09 01:29:05 +00006024 Error halt_error;
6025 if (do_halt)
6026 {
6027 if (log)
6028 log->Printf ("Process::RunThreadPlan(): Running Halt.");
6029 halt_error = Halt();
6030 }
6031 if (halt_error.Success())
6032 {
6033 if (log)
6034 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006035
Jim Ingham0161b492013-02-09 01:29:05 +00006036 real_timeout = TimeValue::Now();
6037 real_timeout.OffsetWithMicroSeconds(500000);
6038
6039 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006040
Jim Ingham0161b492013-02-09 01:29:05 +00006041 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00006042 {
Jim Ingham0161b492013-02-09 01:29:05 +00006043 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
6044 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006045 {
Jim Ingham0161b492013-02-09 01:29:05 +00006046 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
6047 if (stop_state == lldb::eStateStopped
6048 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
6049 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00006050 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006051
Jim Ingham0161b492013-02-09 01:29:05 +00006052 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00006053 {
Jim Ingham0161b492013-02-09 01:29:05 +00006054 // Between the time we initiated the Halt and the time we delivered it, the process could have
6055 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006056
Jim Ingham0161b492013-02-09 01:29:05 +00006057 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
6058 {
6059 if (log)
6060 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
6061 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006062 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00006063 back_to_top = false;
6064 break;
6065 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006066
Jim Ingham0161b492013-02-09 01:29:05 +00006067 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
6068 {
6069 if (log)
6070 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
6071 "Exiting wait loop.");
6072 try_halt_again++;
6073 do_halt = false;
6074 continue;
6075 }
Sean Callanana46ec452012-07-11 21:31:24 +00006076
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006077 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00006078 {
6079 if (log)
6080 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006081 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006082 back_to_top = false;
6083 break;
6084 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006085
Jim Ingham0161b492013-02-09 01:29:05 +00006086 if (before_first_timeout)
6087 {
6088 // Set all the other threads to run, and return to the top of the loop, which will continue;
6089 before_first_timeout = false;
6090 thread_plan_sp->SetStopOthers (false);
6091 if (log)
6092 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00006093
Jim Ingham0161b492013-02-09 01:29:05 +00006094 back_to_top = true;
6095 break;
6096 }
6097 else
6098 {
6099 // Running all threads failed, so return Interrupted.
6100 if (log)
6101 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006102 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006103 back_to_top = false;
6104 break;
6105 }
Sean Callanana46ec452012-07-11 21:31:24 +00006106 }
6107 }
6108 else
Jim Ingham0161b492013-02-09 01:29:05 +00006109 { if (log)
6110 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
6111 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006112 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00006113 back_to_top = false;
6114 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006115 }
6116 }
Jim Ingham0161b492013-02-09 01:29:05 +00006117 else
6118 {
6119 try_halt_again++;
6120 continue;
6121 }
Sean Callanana46ec452012-07-11 21:31:24 +00006122 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006123
Jim Ingham0161b492013-02-09 01:29:05 +00006124 if (!back_to_top || try_halt_again > num_retries)
6125 break;
6126 else
6127 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00006128 }
Sean Callanana46ec452012-07-11 21:31:24 +00006129 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006130
Sean Callanana46ec452012-07-11 21:31:24 +00006131 // 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 +00006132 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00006133 {
6134 StopPrivateStateThread();
6135 Error error;
6136 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00006137 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006138 {
6139 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
6140 }
Jason Molenda76513fd2014-10-15 23:39:31 +00006141 if (old_state != eStateInvalid)
6142 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00006143 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006144
Jim Inghamc60963c2015-10-12 19:11:03 +00006145 if (return_value != eExpressionCompleted && log)
6146 {
6147 // Print a backtrace into the log so we can figure out where we are:
6148 StreamString s;
6149 s.PutCString("Thread state after unsuccessful completion: \n");
6150 thread->GetStackFrameStatus (s,
6151 0,
6152 UINT32_MAX,
6153 true,
6154 UINT32_MAX);
6155 log->PutCString(s.GetData());
6156
6157 }
Jim Ingham184e9812013-01-15 02:47:48 +00006158 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
6159 // could happen:
6160 // 1) The execution successfully completed
6161 // 2) We hit a breakpoint, and ignore_breakpoints was true
6162 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00006163 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
6164 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006165
Jim Ingham8646d3c2014-05-05 02:47:44 +00006166 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00006167 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00006168 {
6169 thread_plan_sp->RestoreThreadState();
6170 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006171
Sean Callanana46ec452012-07-11 21:31:24 +00006172 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00006173 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00006174 {
6175 if (log)
6176 {
6177 StreamString s;
6178 if (event_sp)
6179 event_sp->Dump (&s);
6180 else
6181 {
6182 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
6183 }
6184
6185 StreamString ts;
6186
6187 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006188
Sean Callanana46ec452012-07-11 21:31:24 +00006189 do
6190 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006191 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006192 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006193 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00006194 break;
6195 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006196 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00006197 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006198 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00006199 break;
6200 }
Jim Inghamcfc09352012-07-27 23:57:19 +00006201 else
Sean Callanana46ec452012-07-11 21:31:24 +00006202 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006203 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
6204
6205 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00006206 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006207 event_explanation = "<no event data>";
6208 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006209 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006210
Jim Inghamcfc09352012-07-27 23:57:19 +00006211 Process *process = event_data->GetProcessSP().get();
6212
6213 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00006214 {
Jim Inghamcfc09352012-07-27 23:57:19 +00006215 event_explanation = "<no process>";
6216 break;
Sean Callanana46ec452012-07-11 21:31:24 +00006217 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006218
Jim Inghamcfc09352012-07-27 23:57:19 +00006219 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006220
Jim Inghamcfc09352012-07-27 23:57:19 +00006221 uint32_t num_threads = thread_list.GetSize();
6222 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006223
Jim Inghamcfc09352012-07-27 23:57:19 +00006224 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006225
Jim Inghamcfc09352012-07-27 23:57:19 +00006226 for (thread_index = 0;
6227 thread_index < num_threads;
6228 ++thread_index)
6229 {
6230 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006231
Jim Inghamcfc09352012-07-27 23:57:19 +00006232 if (!thread)
6233 {
6234 ts.Printf("<?> ");
6235 continue;
6236 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006237
Daniel Malead01b2952012-11-29 21:49:15 +00006238 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006239 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006240
Jim Inghamcfc09352012-07-27 23:57:19 +00006241 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006242 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006243 else
6244 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006245
Jim Inghamc60963c2015-10-12 19:11:03 +00006246 // Show the private stop info here, the public stop info will be from the last natural stop.
6247 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
Jim Inghamcfc09352012-07-27 23:57:19 +00006248 if (stop_info_sp)
6249 {
6250 const char *stop_desc = stop_info_sp->GetDescription();
6251 if (stop_desc)
6252 ts.PutCString (stop_desc);
6253 }
6254 ts.Printf(">");
6255 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006256
Jim Inghamcfc09352012-07-27 23:57:19 +00006257 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006258 }
Sean Callanana46ec452012-07-11 21:31:24 +00006259 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006260
Jim Inghamcfc09352012-07-27 23:57:19 +00006261 if (event_explanation)
6262 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006263 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006264 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6265 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006266
Jim Inghame4483cf2013-09-27 01:13:01 +00006267 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006268 {
6269 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006270 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6271 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006272 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Inghamcfc09352012-07-27 23:57:19 +00006273 }
6274 else
6275 {
6276 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006277 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6278 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006279 }
6280 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006281 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006282 {
6283 if (log)
6284 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006285
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006286 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006287 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006288 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00006289 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006290 }
6291 else
6292 {
Sean Callanana46ec452012-07-11 21:31:24 +00006293 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006294 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006295 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006296 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006297 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006298 }
6299 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6300 {
6301 if (log)
6302 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006303 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006304 }
6305 else
6306 {
6307 if (log)
6308 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006309 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006310 {
6311 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006312 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006313 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00006314 }
6315 }
6316 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006317
Sean Callanana46ec452012-07-11 21:31:24 +00006318 // Thread we ran the function in may have gone away because we ran the target
6319 // Check that it's still there, and if it is put it back in the context. Also restore the
6320 // frame in the context if it is still present.
6321 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6322 if (thread)
6323 {
6324 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6325 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006326
Sean Callanana46ec452012-07-11 21:31:24 +00006327 // Also restore the current process'es selected frame & thread, since this function calling may
6328 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006329
Sean Callanana46ec452012-07-11 21:31:24 +00006330 if (selected_tid != LLDB_INVALID_THREAD_ID)
6331 {
6332 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6333 {
6334 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006335 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006336 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006337 if (old_frame_sp)
6338 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006339 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006340 }
6341 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006342
Sean Callanana46ec452012-07-11 21:31:24 +00006343 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006344
Sean Callanana46ec452012-07-11 21:31:24 +00006345 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006346 {
Sean Callanana46ec452012-07-11 21:31:24 +00006347 if (log)
6348 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6349 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006350 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006351
Jim Inghamf48169b2010-11-30 02:22:11 +00006352 return return_value;
6353}
6354
6355const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006356Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006357{
6358 const char *result_name;
6359
6360 switch (result)
6361 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006362 case eExpressionCompleted:
6363 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006364 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006365 case eExpressionDiscarded:
6366 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006367 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006368 case eExpressionInterrupted:
6369 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006370 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006371 case eExpressionHitBreakpoint:
6372 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006373 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006374 case eExpressionSetupError:
6375 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006376 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006377 case eExpressionParseError:
6378 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006379 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006380 case eExpressionResultUnavailable:
6381 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006382 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006383 case eExpressionTimedOut:
6384 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006385 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006386 case eExpressionStoppedForDebug:
6387 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006388 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006389 }
6390 return result_name;
6391}
6392
Greg Clayton7260f622011-04-18 08:33:37 +00006393void
6394Process::GetStatus (Stream &strm)
6395{
6396 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006397 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006398 {
6399 if (state == eStateExited)
6400 {
6401 int exit_status = GetExitStatus();
6402 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006403 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006404 GetID(),
6405 exit_status,
6406 exit_status,
6407 exit_description ? exit_description : "");
6408 }
6409 else
6410 {
6411 if (state == eStateConnected)
6412 strm.Printf ("Connected to remote target.\n");
6413 else
Daniel Malead01b2952012-11-29 21:49:15 +00006414 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006415 }
6416 }
6417 else
6418 {
Daniel Malead01b2952012-11-29 21:49:15 +00006419 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006420 }
6421}
6422
6423size_t
6424Process::GetThreadStatus (Stream &strm,
6425 bool only_threads_with_stop_reason,
6426 uint32_t start_frame,
6427 uint32_t num_frames,
6428 uint32_t num_frames_with_source)
6429{
6430 size_t num_thread_infos_dumped = 0;
6431
Jim Ingham4a65fb12014-03-07 11:20:03 +00006432 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6433 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6434 // ID's, and look them up one by one:
6435
6436 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006437 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006438 //Scope for thread list locker;
6439 {
6440 Mutex::Locker locker (GetThreadList().GetMutex());
6441 ThreadList &curr_thread_list = GetThreadList();
6442 num_threads = curr_thread_list.GetSize();
6443 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006444 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006445 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006446 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006447 }
6448
Greg Clayton7260f622011-04-18 08:33:37 +00006449 for (uint32_t i = 0; i < num_threads; i++)
6450 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006451 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006452 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006453 {
6454 if (only_threads_with_stop_reason)
6455 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006456 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006457 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006458 continue;
6459 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006460 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006461 start_frame,
6462 num_frames,
6463 num_frames_with_source);
6464 ++num_thread_infos_dumped;
6465 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006466 else
6467 {
6468 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6469 if (log)
6470 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6471
6472 }
Greg Clayton7260f622011-04-18 08:33:37 +00006473 }
6474 return num_thread_infos_dumped;
6475}
6476
Greg Claytona9f40ad2012-02-22 04:37:26 +00006477void
6478Process::AddInvalidMemoryRegion (const LoadRange &region)
6479{
6480 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6481}
6482
6483bool
6484Process::RemoveInvalidMemoryRange (const LoadRange &region)
6485{
6486 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6487}
6488
Jim Ingham372787f2012-04-07 00:00:41 +00006489void
6490Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6491{
6492 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6493}
6494
6495bool
6496Process::RunPreResumeActions ()
6497{
6498 bool result = true;
6499 while (!m_pre_resume_actions.empty())
6500 {
6501 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6502 m_pre_resume_actions.pop_back();
6503 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006504 if (result == true)
6505 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006506 }
6507 return result;
6508}
6509
6510void
6511Process::ClearPreResumeActions ()
6512{
6513 m_pre_resume_actions.clear();
6514}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006515
Zachary Turner93749ab2015-03-03 21:51:25 +00006516ProcessRunLock &
6517Process::GetRunLock()
6518{
6519 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6520 return m_private_run_lock;
6521 else
6522 return m_public_run_lock;
6523}
6524
Greg Claytonfa559e52012-05-18 02:38:05 +00006525void
6526Process::Flush ()
6527{
6528 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006529 m_extended_thread_list.Flush();
6530 m_extended_thread_stop_id = 0;
6531 m_queue_list.Clear();
6532 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006533}
Greg Clayton90ba8112012-12-05 00:16:59 +00006534
6535void
6536Process::DidExec ()
6537{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006538 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6539 if (log)
6540 log->Printf ("Process::%s()", __FUNCTION__);
6541
Greg Clayton90ba8112012-12-05 00:16:59 +00006542 Target &target = GetTarget();
6543 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006544 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006545 m_dynamic_checkers_ap.reset();
6546 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006547 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006548 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006549 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006550 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006551 m_image_tokens.clear();
6552 m_allocated_memory_cache.Clear();
6553 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006554 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006555 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006556 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006557 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006558 DoDidExec();
6559 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006560 // Flush the process (threads and all stack frames) after running CompleteAttach()
6561 // in case the dynamic loader loaded things in new locations.
6562 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006563
6564 // After we figure out what was loaded/unloaded in CompleteAttach,
6565 // we need to let the target know so it can do any cleanup it needs to.
6566 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006567}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006568
Jim Ingham1460e4b2014-01-10 23:46:59 +00006569addr_t
6570Process::ResolveIndirectFunction(const Address *address, Error &error)
6571{
6572 if (address == nullptr)
6573 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006574 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006575 return LLDB_INVALID_ADDRESS;
6576 }
6577
6578 addr_t function_addr = LLDB_INVALID_ADDRESS;
6579
6580 addr_t addr = address->GetLoadAddress(&GetTarget());
6581 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6582 if (iter != m_resolved_indirect_addresses.end())
6583 {
6584 function_addr = (*iter).second;
6585 }
6586 else
6587 {
6588 if (!InferiorCall(this, address, function_addr))
6589 {
6590 Symbol *symbol = address->CalculateSymbolContextSymbol();
6591 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6592 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6593 function_addr = LLDB_INVALID_ADDRESS;
6594 }
6595 else
6596 {
6597 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6598 }
6599 }
6600 return function_addr;
6601}
6602
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006603void
6604Process::ModulesDidLoad (ModuleList &module_list)
6605{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006606 SystemRuntime *sys_runtime = GetSystemRuntime();
6607 if (sys_runtime)
6608 {
6609 sys_runtime->ModulesDidLoad (module_list);
6610 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006611
Kuba Breckaafdf8422014-10-10 23:43:03 +00006612 GetJITLoaders().ModulesDidLoad (module_list);
6613
6614 // Give runtimes a chance to be created.
6615 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6616
6617 // Tell runtimes about new modules.
6618 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6619 {
6620 InstrumentationRuntimeSP runtime = pos->second;
6621 runtime->ModulesDidLoad(module_list);
6622 }
6623
Greg Clayton35ca64b2015-04-16 17:13:34 +00006624 // Let any language runtimes we have already created know
6625 // about the modules that loaded.
6626
6627 // Iterate over a copy of this language runtime list in case
6628 // the language runtime ModulesDidLoad somehow causes the language
6629 // riuntime to be unloaded.
6630 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6631 for (const auto &pair: language_runtimes)
6632 {
6633 // We must check language_runtime_sp to make sure it is not
6634 // NULL as we might cache the fact that we didn't have a
6635 // language runtime for a language.
6636 LanguageRuntimeSP language_runtime_sp = pair.second;
6637 if (language_runtime_sp)
6638 language_runtime_sp->ModulesDidLoad(module_list);
6639 }
Ryan Brown65d4d5c2015-09-16 21:20:44 +00006640
6641 LoadOperatingSystemPlugin(false);
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006642}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006643
Jason Molendaef7d6412015-08-06 03:27:10 +00006644void
6645Process::PrintWarning (uint64_t warning_type, void *repeat_key, const char *fmt, ...)
6646{
6647 bool print_warning = true;
6648
6649 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
6650 if (stream_sp.get() == nullptr)
6651 return;
6652 if (warning_type == eWarningsOptimization
6653 && GetWarningsOptimization() == false)
6654 {
6655 return;
6656 }
6657
6658 if (repeat_key != nullptr)
6659 {
6660 WarningsCollection::iterator it = m_warnings_issued.find (warning_type);
6661 if (it == m_warnings_issued.end())
6662 {
6663 m_warnings_issued[warning_type] = WarningsPointerSet();
6664 m_warnings_issued[warning_type].insert (repeat_key);
6665 }
6666 else
6667 {
6668 if (it->second.find (repeat_key) != it->second.end())
6669 {
6670 print_warning = false;
6671 }
6672 else
6673 {
6674 it->second.insert (repeat_key);
6675 }
6676 }
6677 }
6678
6679 if (print_warning)
6680 {
6681 va_list args;
6682 va_start (args, fmt);
6683 stream_sp->PrintfVarArg (fmt, args);
6684 va_end (args);
6685 }
6686}
6687
Jason Molenda484900b2015-08-10 07:55:25 +00006688void
6689Process::PrintWarningOptimization (const SymbolContext &sc)
6690{
6691 if (GetWarningsOptimization() == true
6692 && sc.module_sp.get()
6693 && sc.module_sp->GetFileSpec().GetFilename().IsEmpty() == false
6694 && sc.function
6695 && sc.function->GetIsOptimized() == true)
6696 {
6697 PrintWarning (Process::Warnings::eWarningsOptimization, sc.module_sp.get(), "%s was compiled with optimization - stepping may behave oddly; variables may not be available.\n", sc.module_sp->GetFileSpec().GetFilename().GetCString());
6698 }
6699}
6700
Kuba Breckaa51ea382014-09-06 01:33:13 +00006701ThreadCollectionSP
6702Process::GetHistoryThreads(lldb::addr_t addr)
6703{
6704 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006705
Kuba Breckaa51ea382014-09-06 01:33:13 +00006706 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6707
6708 if (! memory_history.get()) {
6709 return threads;
6710 }
6711
6712 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6713
6714 return threads;
6715}
Kuba Brecka63927542014-10-11 01:59:32 +00006716
6717InstrumentationRuntimeSP
6718Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6719{
6720 InstrumentationRuntimeCollection::iterator pos;
6721 pos = m_instrumentation_runtimes.find (type);
6722 if (pos == m_instrumentation_runtimes.end())
6723 {
6724 return InstrumentationRuntimeSP();
6725 }
6726 else
6727 return (*pos).second;
6728}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006729
6730bool
6731Process::GetModuleSpec(const FileSpec& module_file_spec,
6732 const ArchSpec& arch,
6733 ModuleSpec& module_spec)
6734{
6735 module_spec.Clear();
6736 return false;
6737}