blob: 106678da2684ec5345a9dbcdb14cfdfe250f77ff [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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000024#include "lldb/Core/StreamFile.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000025#include "lldb/Expression/ClangUserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000026#include "lldb/Host/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000029#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000030#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000032#include "lldb/Interpreter/CommandInterpreter.h"
33#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"
Andrew MacPherson17220c12014-03-05 10:12:43 +000036#include "lldb/Target/JITLoader.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000037#include "lldb/Target/MemoryHistory.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000038#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000039#include "lldb/Target/LanguageRuntime.h"
40#include "lldb/Target/CPPLanguageRuntime.h"
41#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000042#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000044#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000045#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/Target.h"
47#include "lldb/Target/TargetList.h"
48#include "lldb/Target/Thread.h"
49#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000050#include "lldb/Target/ThreadPlanBase.h"
Kuba Breckaafdf8422014-10-10 23:43:03 +000051#include "lldb/Target/InstrumentationRuntime.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000052#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053
54using namespace lldb;
55using namespace lldb_private;
56
Greg Clayton67cc0632012-08-22 17:17:09 +000057
58// Comment out line below to disable memory caching, overriding the process setting
59// target.process.disable-memory-cache
60#define ENABLE_MEMORY_CACHING
61
62#ifdef ENABLE_MEMORY_CACHING
63#define DISABLE_MEM_CACHE_DEFAULT false
64#else
65#define DISABLE_MEM_CACHE_DEFAULT true
66#endif
67
68class ProcessOptionValueProperties : public OptionValueProperties
69{
70public:
71 ProcessOptionValueProperties (const ConstString &name) :
72 OptionValueProperties (name)
73 {
74 }
75
76 // This constructor is used when creating ProcessOptionValueProperties when it
77 // is part of a new lldb_private::Process instance. It will copy all current
78 // global property values as needed
79 ProcessOptionValueProperties (ProcessProperties *global_properties) :
80 OptionValueProperties(*global_properties->GetValueProperties())
81 {
82 }
83
84 virtual const Property *
85 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
86 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000087 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000088 // try and grab the setting from the current process if there is one. Else we just
89 // use the one from this instance.
90 if (exe_ctx)
91 {
92 Process *process = exe_ctx->GetProcessPtr();
93 if (process)
94 {
95 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
96 if (this != instance_properties)
97 return instance_properties->ProtectedGetPropertyAtIndex (idx);
98 }
99 }
100 return ProtectedGetPropertyAtIndex (idx);
101 }
102};
103
104static PropertyDefinition
105g_properties[] =
106{
107 { "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 +0000108 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
109 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000110 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
111 { "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 +0000112 { "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 +0000113 { "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 +0000114 { "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 +0000115 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, NULL, NULL, "The memory cache line size" },
Greg Clayton67cc0632012-08-22 17:17:09 +0000116 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
117};
118
119enum {
120 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000121 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000122 ePropertyIgnoreBreakpointsInExpressions,
123 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000124 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000125 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000126 ePropertyDetachKeepsStopped,
127 ePropertyMemCacheLineSize
Greg Clayton67cc0632012-08-22 17:17:09 +0000128};
129
Greg Clayton332e8b12015-01-13 21:13:08 +0000130ProcessProperties::ProcessProperties (lldb_private::Process *process) :
131 Properties (),
132 m_process (process) // Can be NULL for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000133{
Greg Clayton332e8b12015-01-13 21:13:08 +0000134 if (process == NULL)
Greg Clayton67cc0632012-08-22 17:17:09 +0000135 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000136 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000137 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
138 m_collection_sp->Initialize(g_properties);
139 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000140 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000141 true,
142 Thread::GetGlobalProperties()->GetValueProperties());
143 }
144 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000145 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000146 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000147 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
148 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000149}
150
151ProcessProperties::~ProcessProperties()
152{
153}
154
Greg Clayton332e8b12015-01-13 21:13:08 +0000155void
156ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
157{
158 ProcessProperties *properties = (ProcessProperties *)baton;
159 if (properties->m_process)
160 properties->m_process->LoadOperatingSystemPlugin(true);
161}
162
Greg Clayton67cc0632012-08-22 17:17:09 +0000163bool
164ProcessProperties::GetDisableMemoryCache() const
165{
166 const uint32_t idx = ePropertyDisableMemCache;
167 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
168}
169
Jason Molendaf0340c92014-09-03 22:30:54 +0000170uint64_t
171ProcessProperties::GetMemoryCacheLineSize() const
172{
173 const uint32_t idx = ePropertyMemCacheLineSize;
174 return m_collection_sp->GetPropertyAtIndexAsUInt64 (NULL, idx, g_properties[idx].default_uint_value);
175}
176
Greg Clayton67cc0632012-08-22 17:17:09 +0000177Args
178ProcessProperties::GetExtraStartupCommands () const
179{
180 Args args;
181 const uint32_t idx = ePropertyExtraStartCommand;
182 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
183 return args;
184}
185
186void
187ProcessProperties::SetExtraStartupCommands (const Args &args)
188{
189 const uint32_t idx = ePropertyExtraStartCommand;
190 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
191}
192
Greg Claytonc9d645d2012-10-18 22:40:37 +0000193FileSpec
194ProcessProperties::GetPythonOSPluginPath () const
195{
196 const uint32_t idx = ePropertyPythonOSPluginPath;
197 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
198}
199
200void
201ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
202{
203 const uint32_t idx = ePropertyPythonOSPluginPath;
204 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
205}
206
Jim Ingham184e9812013-01-15 02:47:48 +0000207
208bool
209ProcessProperties::GetIgnoreBreakpointsInExpressions () const
210{
211 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
212 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
213}
214
215void
216ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
217{
218 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
219 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
220}
221
222bool
223ProcessProperties::GetUnwindOnErrorInExpressions () const
224{
225 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
226 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
227}
228
229void
230ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
231{
232 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
233 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
234}
235
Jim Ingham29950772013-01-26 02:19:28 +0000236bool
237ProcessProperties::GetStopOnSharedLibraryEvents () const
238{
239 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
240 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
241}
242
243void
244ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
245{
246 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
247 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
248}
249
Jim Inghamacff8952013-05-02 00:27:30 +0000250bool
251ProcessProperties::GetDetachKeepsStopped () const
252{
253 const uint32_t idx = ePropertyDetachKeepsStopped;
254 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
255}
256
257void
258ProcessProperties::SetDetachKeepsStopped (bool stop)
259{
260 const uint32_t idx = ePropertyDetachKeepsStopped;
261 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
262}
263
Greg Clayton32e0a752011-03-30 18:16:51 +0000264void
Greg Clayton8b82f082011-04-12 05:54:46 +0000265ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000266{
267 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000268 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000269 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000270
271 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000272 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000273
274 if (m_executable)
275 {
276 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
277 s.PutCString (" file = ");
278 m_executable.Dump(&s);
279 s.EOL();
280 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000281 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000282 if (argc > 0)
283 {
284 for (uint32_t i=0; i<argc; i++)
285 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000286 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000287 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000289 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291 }
292 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000293
294 const uint32_t envc = m_environment.GetArgumentCount();
295 if (envc > 0)
296 {
297 for (uint32_t i=0; i<envc; i++)
298 {
299 const char *env = m_environment.GetArgumentAtIndex(i);
300 if (i < 10)
301 s.Printf (" env[%u] = %s\n", i, env);
302 else
303 s.Printf ("env[%u] = %s\n", i, env);
304 }
305 }
306
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000307 if (m_arch.IsValid())
308 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
309
Greg Clayton8b82f082011-04-12 05:54:46 +0000310 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000311 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000312 cstr = platform->GetUserName (m_uid);
313 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000314 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000315 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000316 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000317 cstr = platform->GetGroupName (m_gid);
318 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000319 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000320 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000321 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000322 cstr = platform->GetUserName (m_euid);
323 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000324 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000325 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000326 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000327 cstr = platform->GetGroupName (m_egid);
328 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000329 }
330}
331
332void
Greg Clayton8b82f082011-04-12 05:54:46 +0000333ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000334{
Greg Clayton8b82f082011-04-12 05:54:46 +0000335 const char *label;
336 if (show_args || verbose)
337 label = "ARGUMENTS";
338 else
339 label = "NAME";
340
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000341 if (verbose)
342 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000343 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000344 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
345 }
346 else
347 {
Jim Ingham368ac222014-08-15 17:05:27 +0000348 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
349 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000350 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000351}
352
353void
Greg Clayton8b82f082011-04-12 05:54:46 +0000354ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000355{
356 if (m_pid != LLDB_INVALID_PROCESS_ID)
357 {
358 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000359 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000360
Greg Clayton32e0a752011-03-30 18:16:51 +0000361
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000362 if (verbose)
363 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000364 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000365 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
366 s.Printf ("%-10s ", cstr);
367 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000368 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000369
Greg Clayton8b82f082011-04-12 05:54:46 +0000370 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000371 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
372 s.Printf ("%-10s ", cstr);
373 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000374 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000375
Greg Clayton8b82f082011-04-12 05:54:46 +0000376 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000377 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
378 s.Printf ("%-10s ", cstr);
379 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000380 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000381
Greg Clayton8b82f082011-04-12 05:54:46 +0000382 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
384 s.Printf ("%-10s ", cstr);
385 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000386 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000387 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
388 }
389 else
390 {
Jim Ingham368ac222014-08-15 17:05:27 +0000391 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000392 platform->GetUserName (m_euid),
Jim Ingham368ac222014-08-15 17:05:27 +0000393 m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000394 }
395
Greg Clayton8b82f082011-04-12 05:54:46 +0000396 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000397 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000398 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000399 if (argc > 0)
400 {
401 for (uint32_t i=0; i<argc; i++)
402 {
403 if (i > 0)
404 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000405 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000406 }
407 }
408 }
409 else
410 {
411 s.PutCString (GetName());
412 }
413
414 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000415 }
416}
417
Greg Clayton8b82f082011-04-12 05:54:46 +0000418Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000419ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000420{
421 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000422 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000423
424 switch (short_option)
425 {
426 case 's': // Stop at program entry point
427 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
428 break;
429
Greg Clayton8b82f082011-04-12 05:54:46 +0000430 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000431 {
432 FileAction action;
433 if (action.Open (STDIN_FILENO, option_arg, true, false))
434 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000435 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000436 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000437
438 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000439 {
440 FileAction action;
441 if (action.Open (STDOUT_FILENO, option_arg, false, true))
442 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000443 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000444 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000445
446 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000447 {
448 FileAction action;
449 if (action.Open (STDERR_FILENO, option_arg, false, true))
450 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000451 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000452 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000453
Greg Clayton8b82f082011-04-12 05:54:46 +0000454 case 'p': // Process plug-in name
455 launch_info.SetProcessPluginName (option_arg);
456 break;
457
458 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000459 {
460 FileAction action;
461 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
462 launch_info.AppendFileAction (action);
463 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
464 launch_info.AppendFileAction (action);
465 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
466 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000467 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000468 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000469
470 case 'w':
471 launch_info.SetWorkingDirectory (option_arg);
472 break;
473
474 case 't': // Open process in new terminal window
475 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
476 break;
477
478 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000479 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
480 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000481 break;
482
Todd Fiala51637922014-08-19 17:40:43 +0000483 case 'A': // Disable ASLR.
484 {
485 bool success;
486 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
487 if (success)
488 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
489 else
490 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000491 break;
Todd Fiala51637922014-08-19 17:40:43 +0000492 }
493
494 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000495 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000496 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000497 else
Zachary Turner10687b02014-10-20 17:46:43 +0000498 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000499 break;
500
Greg Clayton8b82f082011-04-12 05:54:46 +0000501 case 'v':
502 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
503 break;
504
505 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000506 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000507 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000508 }
509 return error;
510}
511
512OptionDefinition
513ProcessLaunchCommandOptions::g_option_table[] =
514{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000515{ 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 +0000516{ 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 +0000517{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
518{ 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."},
519{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
520{ 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."},
521{ LLDB_OPT_SET_ALL, 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 +0000522
Zachary Turnerd37221d2014-07-09 16:31:49 +0000523{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
524{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
525{ 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 +0000526
Zachary Turnerd37221d2014-07-09 16:31:49 +0000527{ 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 +0000528
Zachary Turnerd37221d2014-07-09 16:31:49 +0000529{ 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."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000530
Zachary Turnerd37221d2014-07-09 16:31:49 +0000531{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000532};
533
534
535
536bool
537ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000538{
539 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
540 return true;
541 const char *match_name = m_match_info.GetName();
542 if (!match_name)
543 return true;
544
545 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
546}
547
548bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000549ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000550{
551 if (!NameMatches (proc_info.GetName()))
552 return false;
553
554 if (m_match_info.ProcessIDIsValid() &&
555 m_match_info.GetProcessID() != proc_info.GetProcessID())
556 return false;
557
558 if (m_match_info.ParentProcessIDIsValid() &&
559 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
560 return false;
561
Greg Clayton8b82f082011-04-12 05:54:46 +0000562 if (m_match_info.UserIDIsValid () &&
563 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000564 return false;
565
Greg Clayton8b82f082011-04-12 05:54:46 +0000566 if (m_match_info.GroupIDIsValid () &&
567 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000568 return false;
569
570 if (m_match_info.EffectiveUserIDIsValid () &&
571 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
572 return false;
573
574 if (m_match_info.EffectiveGroupIDIsValid () &&
575 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
576 return false;
577
578 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000579 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000580 return false;
581 return true;
582}
583
584bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000585ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000586{
587 if (m_name_match_type != eNameMatchIgnore)
588 return false;
589
590 if (m_match_info.ProcessIDIsValid())
591 return false;
592
593 if (m_match_info.ParentProcessIDIsValid())
594 return false;
595
Greg Clayton8b82f082011-04-12 05:54:46 +0000596 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000597 return false;
598
Greg Clayton8b82f082011-04-12 05:54:46 +0000599 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000600 return false;
601
602 if (m_match_info.EffectiveUserIDIsValid ())
603 return false;
604
605 if (m_match_info.EffectiveGroupIDIsValid ())
606 return false;
607
608 if (m_match_info.GetArchitecture().IsValid())
609 return false;
610
611 if (m_match_all_users)
612 return false;
613
614 return true;
615
616}
617
618void
Greg Clayton8b82f082011-04-12 05:54:46 +0000619ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000620{
621 m_match_info.Clear();
622 m_name_match_type = eNameMatchIgnore;
623 m_match_all_users = false;
624}
Greg Clayton58be07b2011-01-07 06:08:19 +0000625
Greg Claytonc3776bf2012-02-09 06:16:32 +0000626ProcessSP
627Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628{
Greg Clayton949e8222013-01-16 17:29:04 +0000629 static uint32_t g_process_unique_id = 0;
630
Greg Claytonc3776bf2012-02-09 06:16:32 +0000631 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632 ProcessCreateInstance create_callback = NULL;
633 if (plugin_name)
634 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000635 ConstString const_plugin_name(plugin_name);
636 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637 if (create_callback)
638 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000639 process_sp = create_callback(target, listener, crash_file_path);
640 if (process_sp)
641 {
Greg Clayton949e8222013-01-16 17:29:04 +0000642 if (process_sp->CanDebug(target, true))
643 {
644 process_sp->m_process_unique_id = ++g_process_unique_id;
645 }
646 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000647 process_sp.reset();
648 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 }
650 }
651 else
652 {
Greg Claytonc982c762010-07-09 20:39:50 +0000653 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000654 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000655 process_sp = create_callback(target, listener, crash_file_path);
656 if (process_sp)
657 {
Greg Clayton949e8222013-01-16 17:29:04 +0000658 if (process_sp->CanDebug(target, false))
659 {
660 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000661 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000662 }
663 else
664 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000665 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666 }
667 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000668 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669}
670
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000671ConstString &
672Process::GetStaticBroadcasterClass ()
673{
674 static ConstString class_name ("lldb.process");
675 return class_name;
676}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677
678//----------------------------------------------------------------------
679// Process constructor
680//----------------------------------------------------------------------
681Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000682 Process(target, listener, Host::GetUnixSignals ())
683{
684 // This constructor just delegates to the full Process constructor,
685 // defaulting to using the Host's UnixSignals.
686}
687
688Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000689 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000690 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000691 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000693 m_public_state (eStateUnloaded),
694 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000695 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
696 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697 m_private_state_listener ("lldb.process.internal_state_listener"),
698 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000699 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000700 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000702 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000703 m_exit_status (-1),
704 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000705 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000706 m_thread_mutex (Mutex::eMutexTypeRecursive),
707 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000709 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000710 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000711 m_queue_list (this),
712 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000713 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000714 m_image_tokens (),
715 m_listener (listener),
716 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000717 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000718 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000719 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000720 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000721 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000722 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000723 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000724 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000725 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
726 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000727 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000728 m_memory_cache (*this),
729 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000730 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000731 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000732 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000733 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000734 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000735 m_stop_info_override_callback (NULL),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000736 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000737 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000738 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000739 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000740 m_destroy_in_process (false),
741 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000743 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000744
Greg Clayton5160ce52013-03-27 23:08:40 +0000745 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000747 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748
Todd Fiala4ceced32014-08-29 17:35:57 +0000749 if (!m_unix_signals_sp)
750 m_unix_signals_sp.reset (new UnixSignals ());
751
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000752 SetEventName (eBroadcastBitStateChanged, "state-changed");
753 SetEventName (eBroadcastBitInterrupt, "interrupt");
754 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
755 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000756 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000757
Greg Clayton35a4cc52012-10-29 20:52:08 +0000758 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
759 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
760 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
761
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762 listener.StartListeningForEvents (this,
763 eBroadcastBitStateChanged |
764 eBroadcastBitInterrupt |
765 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000766 eBroadcastBitSTDERR |
767 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000768
769 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000770 eBroadcastBitStateChanged |
771 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772
773 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
774 eBroadcastInternalStateControlStop |
775 eBroadcastInternalStateControlPause |
776 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000777 // We need something valid here, even if just the default UnixSignalsSP.
778 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779}
780
781//----------------------------------------------------------------------
782// Destructor
783//----------------------------------------------------------------------
784Process::~Process()
785{
Greg Clayton5160ce52013-03-27 23:08:40 +0000786 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000788 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000790
791 // ThreadList::Clear() will try to acquire this process's mutex, so
792 // explicitly clear the thread list here to ensure that the mutex
793 // is not destroyed before the thread list.
794 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795}
796
Greg Clayton67cc0632012-08-22 17:17:09 +0000797const ProcessPropertiesSP &
798Process::GetGlobalProperties()
799{
800 static ProcessPropertiesSP g_settings_sp;
801 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000802 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000803 return g_settings_sp;
804}
805
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806void
807Process::Finalize()
808{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000809 switch (GetPrivateState())
810 {
811 case eStateConnected:
812 case eStateAttaching:
813 case eStateLaunching:
814 case eStateStopped:
815 case eStateRunning:
816 case eStateStepping:
817 case eStateCrashed:
818 case eStateSuspended:
819 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000820 {
821 // FIXME: This will have to be a process setting:
822 bool keep_stopped = false;
823 Detach(keep_stopped);
824 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000825 else
826 Destroy();
827 break;
828
829 case eStateInvalid:
830 case eStateUnloaded:
831 case eStateDetached:
832 case eStateExited:
833 break;
834 }
835
Greg Clayton1ed54f52011-10-01 00:45:15 +0000836 // Clear our broadcaster before we proceed with destroying
837 Broadcaster::Clear();
838
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839 // Do any cleanup needed prior to being destructed... Subclasses
840 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000841
842 // We need to destroy the loader before the derived Process class gets destroyed
843 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000844 m_dynamic_checkers_ap.reset();
845 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000846 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000847 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000848 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000849 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000850 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000851 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000852 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000853 m_queue_list.Clear();
854 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000855 std::vector<Notifications> empty_notifications;
856 m_notifications.swap(empty_notifications);
857 m_image_tokens.clear();
858 m_memory_cache.Clear();
859 m_allocated_memory_cache.Clear();
860 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000861 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000862 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000863 m_stop_info_override_callback = NULL;
Greg Clayton35a4cc52012-10-29 20:52:08 +0000864//#ifdef LLDB_CONFIGURATION_DEBUG
865// StreamFile s(stdout, false);
866// EventSP event_sp;
867// while (m_private_state_listener.GetNextEvent(event_sp))
868// {
869// event_sp->Dump (&s);
870// s.EOL();
871// }
872//#endif
873 // We have to be very careful here as the m_private_state_listener might
874 // contain events that have ProcessSP values in them which can keep this
875 // process around forever. These events need to be cleared out.
876 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000877 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
878 m_public_run_lock.SetStopped();
879 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
880 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000881 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882}
883
884void
885Process::RegisterNotificationCallbacks (const Notifications& callbacks)
886{
887 m_notifications.push_back(callbacks);
888 if (callbacks.initialize != NULL)
889 callbacks.initialize (callbacks.baton, this);
890}
891
892bool
893Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
894{
895 std::vector<Notifications>::iterator pos, end = m_notifications.end();
896 for (pos = m_notifications.begin(); pos != end; ++pos)
897 {
898 if (pos->baton == callbacks.baton &&
899 pos->initialize == callbacks.initialize &&
900 pos->process_state_changed == callbacks.process_state_changed)
901 {
902 m_notifications.erase(pos);
903 return true;
904 }
905 }
906 return false;
907}
908
909void
910Process::SynchronouslyNotifyStateChanged (StateType state)
911{
912 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
913 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
914 {
915 if (notification_pos->process_state_changed)
916 notification_pos->process_state_changed (notification_pos->baton, this, state);
917 }
918}
919
920// FIXME: We need to do some work on events before the general Listener sees them.
921// For instance if we are continuing from a breakpoint, we need to ensure that we do
922// the little "insert real insn, step & stop" trick. But we can't do that when the
923// event is delivered by the broadcaster - since that is done on the thread that is
924// waiting for new events, so if we needed more than one event for our handling, we would
925// stall. So instead we do it when we fetch the event off of the queue.
926//
927
928StateType
929Process::GetNextEvent (EventSP &event_sp)
930{
931 StateType state = eStateInvalid;
932
933 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
934 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
935
936 return state;
937}
938
Todd Fialaa3b89e22014-08-12 14:33:19 +0000939bool
940Process::SyncIOHandler (uint64_t timeout_msec)
941{
942 bool timed_out = false;
943
944 // don't sync (potentially context switch) in case where there is no process IO
945 if (m_process_input_reader)
946 {
947 TimeValue timeout = TimeValue::Now();
948 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
949
950 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
951
952 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
953 if(log)
954 {
955 if(timed_out)
956 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
957 else
958 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
959 }
960
Shawn Best1ded74a2014-10-08 01:50:37 +0000961 // reset sync one-shot so it will be ready for next launch
Todd Fialaa3b89e22014-08-12 14:33:19 +0000962 m_iohandler_sync.SetValue(false, eBroadcastNever);
963 }
964
965 return !timed_out;
966}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967
968StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000969Process::WaitForProcessToStop (const TimeValue *timeout,
970 EventSP *event_sp_ptr,
971 bool wait_always,
972 Listener *hijack_listener,
973 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974{
Jim Ingham4b536182011-08-09 02:12:22 +0000975 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
976 // We have to actually check each event, and in the case of a stopped event check the restarted flag
977 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000978 if (event_sp_ptr)
979 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000980 StateType state = GetState();
981 // If we are exited or detached, we won't ever get back to any
982 // other valid state...
983 if (state == eStateDetached || state == eStateExited)
984 return state;
985
Daniel Malea9e9919f2013-10-09 16:56:28 +0000986 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
987 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000988 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
989 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +0000990
991 if (!wait_always &&
992 StateIsStoppedState(state, true) &&
993 StateIsStoppedState(GetPrivateState(), true)) {
994 if (log)
995 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
996 __FUNCTION__);
997 return state;
998 }
999
Jim Ingham4b536182011-08-09 02:12:22 +00001000 while (state != eStateInvalid)
1001 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001002 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001003 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001004 if (event_sp_ptr && event_sp)
1005 *event_sp_ptr = event_sp;
1006
Greg Claytondc6224e2014-10-21 01:00:42 +00001007 bool pop_process_io_handler = hijack_listener != NULL;
1008 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1009
Jim Ingham4b536182011-08-09 02:12:22 +00001010 switch (state)
1011 {
1012 case eStateCrashed:
1013 case eStateDetached:
1014 case eStateExited:
1015 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001016 // We need to toggle the run lock as this won't get done in
1017 // SetPublicState() if the process is hijacked.
1018 if (hijack_listener)
1019 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001020 return state;
1021 case eStateStopped:
1022 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1023 continue;
1024 else
Greg Clayton44d93782014-01-27 23:43:24 +00001025 {
1026 // We need to toggle the run lock as this won't get done in
1027 // SetPublicState() if the process is hijacked.
1028 if (hijack_listener)
1029 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001030 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001031 }
Jim Ingham4b536182011-08-09 02:12:22 +00001032 default:
1033 continue;
1034 }
1035 }
1036 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037}
1038
Greg Claytondc6224e2014-10-21 01:00:42 +00001039bool
1040Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1041 Stream *stream,
1042 bool &pop_process_io_handler)
1043{
1044 const bool handle_pop = pop_process_io_handler == true;
1045
1046 pop_process_io_handler = false;
1047 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1048
1049 if (!process_sp)
1050 return false;
1051
1052 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1053 if (event_state == eStateInvalid)
1054 return false;
1055
1056 switch (event_state)
1057 {
1058 case eStateInvalid:
1059 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001060 case eStateAttaching:
1061 case eStateLaunching:
1062 case eStateStepping:
1063 case eStateDetached:
1064 {
1065 if (stream)
1066 stream->Printf ("Process %" PRIu64 " %s\n",
1067 process_sp->GetID(),
1068 StateAsCString (event_state));
1069
1070 if (event_state == eStateDetached)
1071 pop_process_io_handler = true;
1072 }
1073 break;
1074
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001075 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001076 case eStateRunning:
1077 // Don't be chatty when we run...
1078 break;
1079
1080 case eStateExited:
1081 if (stream)
1082 process_sp->GetStatus(*stream);
1083 pop_process_io_handler = true;
1084 break;
1085
1086 case eStateStopped:
1087 case eStateCrashed:
1088 case eStateSuspended:
1089 // Make sure the program hasn't been auto-restarted:
1090 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1091 {
1092 if (stream)
1093 {
1094 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1095 if (num_reasons > 0)
1096 {
1097 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1098 if (num_reasons == 1)
1099 {
1100 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1101 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1102 process_sp->GetID(),
1103 reason ? reason : "<UNKNOWN REASON>");
1104 }
1105 else
1106 {
1107 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1108 process_sp->GetID());
1109
1110
1111 for (size_t i = 0; i < num_reasons; i++)
1112 {
1113 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1114 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1115 }
1116 }
1117 }
1118 }
1119 }
1120 else
1121 {
1122 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1123 {
1124 ThreadList &thread_list = process_sp->GetThreadList();
1125 Mutex::Locker locker (thread_list.GetMutex());
1126
1127 ThreadSP curr_thread (thread_list.GetSelectedThread());
1128 ThreadSP thread;
1129 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1130 if (curr_thread)
1131 curr_thread_stop_reason = curr_thread->GetStopReason();
1132 if (!curr_thread ||
1133 !curr_thread->IsValid() ||
1134 curr_thread_stop_reason == eStopReasonInvalid ||
1135 curr_thread_stop_reason == eStopReasonNone)
1136 {
1137 // Prefer a thread that has just completed its plan over another thread as current thread.
1138 ThreadSP plan_thread;
1139 ThreadSP other_thread;
1140 const size_t num_threads = thread_list.GetSize();
1141 size_t i;
1142 for (i = 0; i < num_threads; ++i)
1143 {
1144 thread = thread_list.GetThreadAtIndex(i);
1145 StopReason thread_stop_reason = thread->GetStopReason();
1146 switch (thread_stop_reason)
1147 {
1148 case eStopReasonInvalid:
1149 case eStopReasonNone:
1150 break;
1151
1152 case eStopReasonTrace:
1153 case eStopReasonBreakpoint:
1154 case eStopReasonWatchpoint:
1155 case eStopReasonSignal:
1156 case eStopReasonException:
1157 case eStopReasonExec:
1158 case eStopReasonThreadExiting:
1159 case eStopReasonInstrumentation:
1160 if (!other_thread)
1161 other_thread = thread;
1162 break;
1163 case eStopReasonPlanComplete:
1164 if (!plan_thread)
1165 plan_thread = thread;
1166 break;
1167 }
1168 }
1169 if (plan_thread)
1170 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1171 else if (other_thread)
1172 thread_list.SetSelectedThreadByID (other_thread->GetID());
1173 else
1174 {
1175 if (curr_thread && curr_thread->IsValid())
1176 thread = curr_thread;
1177 else
1178 thread = thread_list.GetThreadAtIndex(0);
1179
1180 if (thread)
1181 thread_list.SetSelectedThreadByID (thread->GetID());
1182 }
1183 }
1184 }
1185 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1186 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1187 // have a hard time restarting the process.
1188 if (stream)
1189 {
1190 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1191 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1192 {
1193 const bool only_threads_with_stop_reason = true;
1194 const uint32_t start_frame = 0;
1195 const uint32_t num_frames = 1;
1196 const uint32_t num_frames_with_source = 1;
1197 process_sp->GetStatus(*stream);
1198 process_sp->GetThreadStatus (*stream,
1199 only_threads_with_stop_reason,
1200 start_frame,
1201 num_frames,
1202 num_frames_with_source);
1203 }
1204 else
1205 {
1206 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1207 if (target_idx != UINT32_MAX)
1208 stream->Printf ("Target %d: (", target_idx);
1209 else
1210 stream->Printf ("Target <unknown index>: (");
1211 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1212 stream->Printf (") stopped.\n");
1213 }
1214 }
1215
1216 // Pop the process IO handler
1217 pop_process_io_handler = true;
1218 }
1219 break;
1220 }
1221
1222 if (handle_pop && pop_process_io_handler)
1223 process_sp->PopProcessIOHandler();
1224
1225 return true;
1226}
1227
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001228
1229StateType
1230Process::WaitForState
1231(
1232 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001233 const StateType *match_states,
1234 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235)
1236{
1237 EventSP event_sp;
1238 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001239 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001240 while (state != eStateInvalid)
1241 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001242 // If we are exited or detached, we won't ever get back to any
1243 // other valid state...
1244 if (state == eStateDetached || state == eStateExited)
1245 return state;
1246
Greg Clayton44d93782014-01-27 23:43:24 +00001247 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248
1249 for (i=0; i<num_match_states; ++i)
1250 {
1251 if (match_states[i] == state)
1252 return state;
1253 }
1254 }
1255 return state;
1256}
1257
Jim Ingham30f9b212010-10-11 23:53:14 +00001258bool
1259Process::HijackProcessEvents (Listener *listener)
1260{
1261 if (listener != NULL)
1262 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001263 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001264 }
1265 else
1266 return false;
1267}
1268
1269void
1270Process::RestoreProcessEvents ()
1271{
1272 RestoreBroadcaster();
1273}
1274
Jim Ingham0f16e732011-02-08 05:20:59 +00001275bool
1276Process::HijackPrivateProcessEvents (Listener *listener)
1277{
1278 if (listener != NULL)
1279 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001280 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001281 }
1282 else
1283 return false;
1284}
1285
1286void
1287Process::RestorePrivateProcessEvents ()
1288{
1289 m_private_state_broadcaster.RestoreBroadcaster();
1290}
1291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001292StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001293Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001294{
Greg Clayton5160ce52013-03-27 23:08:40 +00001295 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001296
1297 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001298 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1299 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300
Greg Clayton44d93782014-01-27 23:43:24 +00001301 Listener *listener = hijack_listener;
1302 if (listener == NULL)
1303 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001304
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001306 if (listener->WaitForEventForBroadcasterWithType (timeout,
1307 this,
1308 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1309 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001310 {
1311 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1312 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1313 else if (log)
1314 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1315 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316
1317 if (log)
1318 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001319 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001320 StateAsCString(state));
1321 return state;
1322}
1323
1324Event *
1325Process::PeekAtStateChangedEvents ()
1326{
Greg Clayton5160ce52013-03-27 23:08:40 +00001327 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328
1329 if (log)
1330 log->Printf ("Process::%s...", __FUNCTION__);
1331
1332 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001333 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1334 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 if (log)
1336 {
1337 if (event_ptr)
1338 {
1339 log->Printf ("Process::%s (event_ptr) => %s",
1340 __FUNCTION__,
1341 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1342 }
1343 else
1344 {
1345 log->Printf ("Process::%s no events found",
1346 __FUNCTION__);
1347 }
1348 }
1349 return event_ptr;
1350}
1351
1352StateType
1353Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1354{
Greg Clayton5160ce52013-03-27 23:08:40 +00001355 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356
1357 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001358 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1359 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360
1361 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001362 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1363 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001364 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001365 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001366 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1367 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368
1369 // This is a bit of a hack, but when we wait here we could very well return
1370 // to the command-line, and that could disable the log, which would render the
1371 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001373 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1374 __FUNCTION__, static_cast<const void *>(timeout),
1375 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001376 return state;
1377}
1378
1379bool
1380Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1381{
Greg Clayton5160ce52013-03-27 23:08:40 +00001382 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383
1384 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001385 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1386 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387
1388 if (control_only)
1389 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1390 else
1391 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1392}
1393
1394bool
1395Process::IsRunning () const
1396{
1397 return StateIsRunningState (m_public_state.GetValue());
1398}
1399
1400int
1401Process::GetExitStatus ()
1402{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001403 Mutex::Locker locker (m_exit_status_mutex);
1404
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405 if (m_public_state.GetValue() == eStateExited)
1406 return m_exit_status;
1407 return -1;
1408}
1409
Greg Clayton85851dd2010-12-04 00:10:17 +00001410
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001411const char *
1412Process::GetExitDescription ()
1413{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001414 Mutex::Locker locker (m_exit_status_mutex);
1415
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1417 return m_exit_string.c_str();
1418 return NULL;
1419}
1420
Greg Clayton6779606a2011-01-22 23:43:18 +00001421bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001422Process::SetExitStatus (int status, const char *cstr)
1423{
Greg Clayton5160ce52013-03-27 23:08:40 +00001424 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001425 if (log)
1426 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1427 status, status,
1428 cstr ? "\"" : "",
1429 cstr ? cstr : "NULL",
1430 cstr ? "\"" : "");
1431
Greg Clayton6779606a2011-01-22 23:43:18 +00001432 // We were already in the exited state
1433 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001434 {
Greg Clayton385d6032011-01-26 23:47:29 +00001435 if (log)
1436 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001437 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001438 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001439
Todd Fiala7b0917a2014-09-15 20:07:33 +00001440 // use a mutex to protect the status and string during updating
1441 {
1442 Mutex::Locker locker (m_exit_status_mutex);
1443
1444 m_exit_status = status;
1445 if (cstr)
1446 m_exit_string = cstr;
1447 else
1448 m_exit_string.clear();
1449 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001450
Greg Clayton6779606a2011-01-22 23:43:18 +00001451 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001452
Greg Clayton6779606a2011-01-22 23:43:18 +00001453 SetPrivateState (eStateExited);
1454 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001455}
1456
1457// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001458// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001459// found in the global target list (we want to be completely sure that the
1460// lldb_private::Process doesn't go away before we can deliver the signal.
1461bool
Greg Claytone4e45922011-11-16 05:37:56 +00001462Process::SetProcessExitStatus (void *callback_baton,
1463 lldb::pid_t pid,
1464 bool exited,
1465 int signo, // Zero for no signal
1466 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467)
1468{
Greg Clayton5160ce52013-03-27 23:08:40 +00001469 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001470 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001471 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001472 callback_baton,
1473 pid,
1474 exited,
1475 signo,
1476 exit_status);
1477
1478 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001479 {
Greg Clayton66111032010-06-23 01:19:29 +00001480 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481 if (target_sp)
1482 {
1483 ProcessSP process_sp (target_sp->GetProcessSP());
1484 if (process_sp)
1485 {
1486 const char *signal_cstr = NULL;
1487 if (signo)
1488 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1489
1490 process_sp->SetExitStatus (exit_status, signal_cstr);
1491 }
1492 }
1493 return true;
1494 }
1495 return false;
1496}
1497
1498
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001499void
1500Process::UpdateThreadListIfNeeded ()
1501{
1502 const uint32_t stop_id = GetStopID();
1503 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1504 {
Greg Clayton2637f822011-11-17 01:23:07 +00001505 const StateType state = GetPrivateState();
1506 if (StateIsStoppedState (state, true))
1507 {
1508 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001509 // m_thread_list does have its own mutex, but we need to
1510 // hold onto the mutex between the call to UpdateThreadList(...)
1511 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001512 ThreadList &old_thread_list = m_thread_list;
1513 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001514 ThreadList new_thread_list(this);
1515 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001516 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001517 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001518 {
Jim Ingham09437922013-03-01 20:04:25 +00001519 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1520 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1521 // shutting us down, causing a deadlock.
1522 if (!m_destroy_in_process)
1523 {
1524 OperatingSystem *os = GetOperatingSystem ();
1525 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001526 {
1527 // Clear any old backing threads where memory threads might have been
1528 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001529 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001530 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001531 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001532
1533 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001534 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1535 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1536 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Claytonb3ae8762013-04-12 20:07:46 +00001537 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001538 else
1539 {
1540 // No OS plug-in, the new thread list is the same as the real thread list
1541 new_thread_list = real_thread_list;
1542 }
Jim Ingham09437922013-03-01 20:04:25 +00001543 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001544
1545 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001546 m_thread_list.Update (new_thread_list);
1547 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001548
Jason Molenda4ff13262013-11-20 00:31:38 +00001549 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1550 {
1551 // Clear any extended threads that we may have accumulated previously
1552 m_extended_thread_list.Clear();
1553 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001554
1555 m_queue_list.Clear();
1556 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001557 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001558 }
Greg Clayton2637f822011-11-17 01:23:07 +00001559 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001560 }
1561}
1562
Jason Molenda5e8dce42013-12-13 00:29:16 +00001563void
1564Process::UpdateQueueListIfNeeded ()
1565{
1566 if (m_system_runtime_ap.get())
1567 {
1568 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1569 {
1570 const StateType state = GetPrivateState();
1571 if (StateIsStoppedState (state, true))
1572 {
1573 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1574 m_queue_list_stop_id = GetLastNaturalStopID();
1575 }
1576 }
1577 }
1578}
1579
Greg Claytona4d87472013-01-18 23:41:08 +00001580ThreadSP
1581Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1582{
1583 OperatingSystem *os = GetOperatingSystem ();
1584 if (os)
1585 return os->CreateThread(tid, context);
1586 return ThreadSP();
1587}
1588
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001589uint32_t
1590Process::GetNextThreadIndexID (uint64_t thread_id)
1591{
1592 return AssignIndexIDToThread(thread_id);
1593}
1594
1595bool
1596Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1597{
1598 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1599 if (iterator == m_thread_id_to_index_id_map.end())
1600 {
1601 return false;
1602 }
1603 else
1604 {
1605 return true;
1606 }
1607}
1608
1609uint32_t
1610Process::AssignIndexIDToThread(uint64_t thread_id)
1611{
1612 uint32_t result = 0;
1613 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1614 if (iterator == m_thread_id_to_index_id_map.end())
1615 {
1616 result = ++m_thread_index_id;
1617 m_thread_id_to_index_id_map[thread_id] = result;
1618 }
1619 else
1620 {
1621 result = iterator->second;
1622 }
1623
1624 return result;
1625}
1626
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001627StateType
1628Process::GetState()
1629{
1630 // If any other threads access this we will need a mutex for it
1631 return m_public_state.GetValue ();
1632}
1633
Greg Claytondc6224e2014-10-21 01:00:42 +00001634bool
1635Process::StateChangedIsExternallyHijacked()
1636{
1637 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1638 {
1639 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1640 return true;
1641 }
1642 return false;
1643}
1644
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001645void
Jim Ingham221d51c2013-05-08 00:35:16 +00001646Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001647{
Greg Clayton5160ce52013-03-27 23:08:40 +00001648 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001649 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001650 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001651 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001652 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001653
1654 // On the transition from Run to Stopped, we unlock the writer end of the
1655 // run lock. The lock gets locked in Resume, which is the public API
1656 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001657 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001658 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001659 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001660 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001661 if (log)
1662 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001663 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001664 }
1665 else
1666 {
1667 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1668 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001669 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001670 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001671 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001672 {
1673 if (log)
1674 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001675 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001676 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001677 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001678 }
1679 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680}
1681
Jim Ingham3b8285d2012-04-19 01:40:33 +00001682Error
1683Process::Resume ()
1684{
Greg Clayton5160ce52013-03-27 23:08:40 +00001685 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001686 if (log)
1687 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001688 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001689 {
1690 Error error("Resume request failed - process still running.");
1691 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001692 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001693 return error;
1694 }
1695 return PrivateResume();
1696}
1697
Greg Claytondc6224e2014-10-21 01:00:42 +00001698Error
1699Process::ResumeSynchronous (Stream *stream)
1700{
1701 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1702 if (log)
1703 log->Printf("Process::ResumeSynchronous -- locking run lock");
1704 if (!m_public_run_lock.TrySetRunning())
1705 {
1706 Error error("Resume request failed - process still running.");
1707 if (log)
1708 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1709 return error;
1710 }
1711
1712 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1713 HijackProcessEvents(listener_sp.get());
1714
1715 Error error = PrivateResume();
1716
1717 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1718
1719 // Undo the hijacking of process events...
1720 RestoreProcessEvents();
1721
1722 if (error.Success() && !StateIsStoppedState(state, false))
1723 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1724
1725 return error;
1726}
1727
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728StateType
1729Process::GetPrivateState ()
1730{
1731 return m_private_state.GetValue();
1732}
1733
1734void
1735Process::SetPrivateState (StateType new_state)
1736{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001737 if (m_finalize_called)
1738 return;
1739
Greg Clayton5160ce52013-03-27 23:08:40 +00001740 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741 bool state_changed = false;
1742
1743 if (log)
1744 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1745
Andrew Kaylor29d65742013-05-10 17:19:04 +00001746 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001747 Mutex::Locker locker(m_private_state.GetMutex());
1748
1749 const StateType old_state = m_private_state.GetValueNoLock ();
1750 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001751
Greg Claytonaa49c832013-05-03 22:25:56 +00001752 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1753 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1754 if (old_state_is_stopped != new_state_is_stopped)
1755 {
1756 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001757 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001758 else
Ed Maste64fad602013-07-29 20:58:06 +00001759 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001760 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001761
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762 if (state_changed)
1763 {
1764 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001765 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001766 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001767 // Note, this currently assumes that all threads in the list
1768 // stop when the process stops. In the future we will want to
1769 // support a debugging model where some threads continue to run
1770 // while others are stopped. When that happens we will either need
1771 // a way for the thread list to identify which threads are stopping
1772 // or create a special thread list containing only threads which
1773 // actually stopped.
1774 //
1775 // The process plugin is responsible for managing the actual
1776 // behavior of the threads and should have stopped any threads
1777 // that are going to stop before we get here.
1778 m_thread_list.DidStop();
1779
Jim Ingham4b536182011-08-09 02:12:22 +00001780 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001781 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001782 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001783 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784 }
1785 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001786 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1787 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1788 else
1789 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790 }
1791 else
1792 {
1793 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001794 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 }
1796}
1797
Jim Ingham0faa43f2011-11-08 03:00:11 +00001798void
1799Process::SetRunningUserExpression (bool on)
1800{
1801 m_mod_id.SetRunningUserExpression (on);
1802}
1803
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804addr_t
1805Process::GetImageInfoAddress()
1806{
1807 return LLDB_INVALID_ADDRESS;
1808}
1809
Greg Clayton8f343b02010-11-04 01:54:29 +00001810//----------------------------------------------------------------------
1811// LoadImage
1812//
1813// This function provides a default implementation that works for most
1814// unix variants. Any Process subclasses that need to do shared library
1815// loading differently should override LoadImage and UnloadImage and
1816// do what is needed.
1817//----------------------------------------------------------------------
1818uint32_t
1819Process::LoadImage (const FileSpec &image_spec, Error &error)
1820{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001821 char path[PATH_MAX];
1822 image_spec.GetPath(path, sizeof(path));
1823
Greg Clayton8f343b02010-11-04 01:54:29 +00001824 DynamicLoader *loader = GetDynamicLoader();
1825 if (loader)
1826 {
1827 error = loader->CanLoadImage();
1828 if (error.Fail())
1829 return LLDB_INVALID_IMAGE_TOKEN;
1830 }
1831
1832 if (error.Success())
1833 {
1834 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001835
1836 if (thread_sp)
1837 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001838 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001839
1840 if (frame_sp)
1841 {
1842 ExecutionContext exe_ctx;
1843 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001844 EvaluateExpressionOptions expr_options;
1845 expr_options.SetUnwindOnError(true);
1846 expr_options.SetIgnoreBreakpoints(true);
1847 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001848 expr_options.SetResultIsInternal(true);
1849
Greg Clayton8f343b02010-11-04 01:54:29 +00001850 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001851 expr.Printf(R"(
1852 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1853 the_result.image_ptr = dlopen ("%s", 2);
1854 if (the_result.image_ptr == (void *) 0x0)
1855 {
1856 the_result.error_str = dlerror();
1857 }
1858 else
1859 {
1860 the_result.error_str = (const char *) 0x0;
1861 }
1862 the_result;
1863 )",
1864 path);
1865 const char *prefix = R"(
1866 extern "C" void* dlopen (const char *path, int mode);
1867 extern "C" const char *dlerror (void);
1868 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001869 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001870 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001871 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001872 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001873 expr.GetData(),
1874 prefix,
1875 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001876 expr_error);
1877 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001878 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001879 error = result_valobj_sp->GetError();
1880 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001881 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001882 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001883 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1884 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001885 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001886 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1887 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1888 {
1889 uint32_t image_token = m_image_tokens.size();
1890 m_image_tokens.push_back (image_ptr);
1891 return image_token;
1892 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001893 else if (image_ptr == 0)
1894 {
Jim Ingham6971b862014-07-19 00:37:06 +00001895 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1896 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001897 {
Jim Ingham6971b862014-07-19 00:37:06 +00001898 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001899 {
Enrico Granata2206b482014-10-30 18:27:31 +00001900 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1901 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001902 if (error.Success() && num_chars > 0)
1903 {
1904 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001905 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1906 }
1907 else
1908 {
1909 error.Clear();
1910 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001911 }
1912 }
1913 }
1914 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001915 }
1916 }
1917 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001918 else
1919 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001920 }
1921 }
1922 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001923 if (!error.AsCString())
1924 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001925 return LLDB_INVALID_IMAGE_TOKEN;
1926}
1927
1928//----------------------------------------------------------------------
1929// UnloadImage
1930//
1931// This function provides a default implementation that works for most
1932// unix variants. Any Process subclasses that need to do shared library
1933// loading differently should override LoadImage and UnloadImage and
1934// do what is needed.
1935//----------------------------------------------------------------------
1936Error
1937Process::UnloadImage (uint32_t image_token)
1938{
1939 Error error;
1940 if (image_token < m_image_tokens.size())
1941 {
1942 const addr_t image_addr = m_image_tokens[image_token];
1943 if (image_addr == LLDB_INVALID_ADDRESS)
1944 {
1945 error.SetErrorString("image already unloaded");
1946 }
1947 else
1948 {
1949 DynamicLoader *loader = GetDynamicLoader();
1950 if (loader)
1951 error = loader->CanLoadImage();
1952
1953 if (error.Success())
1954 {
1955 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001956
1957 if (thread_sp)
1958 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001959 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001960
1961 if (frame_sp)
1962 {
1963 ExecutionContext exe_ctx;
1964 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001965 EvaluateExpressionOptions expr_options;
1966 expr_options.SetUnwindOnError(true);
1967 expr_options.SetIgnoreBreakpoints(true);
1968 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001969 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001970 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001971 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001972 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001973 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001974 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001975 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001976 expr.GetData(),
1977 prefix,
1978 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001979 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001980 if (result_valobj_sp->GetError().Success())
1981 {
1982 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001983 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001984 {
1985 if (scalar.UInt(1))
1986 {
1987 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1988 }
1989 else
1990 {
1991 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1992 }
1993 }
1994 }
1995 else
1996 {
1997 error = result_valobj_sp->GetError();
1998 }
1999 }
2000 }
2001 }
2002 }
2003 }
2004 else
2005 {
2006 error.SetErrorString("invalid image token");
2007 }
2008 return error;
2009}
2010
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002011const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012Process::GetABI()
2013{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002014 if (!m_abi_sp)
2015 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2016 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002017}
2018
Jim Ingham22777012010-09-23 02:01:19 +00002019LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002020Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002021{
2022 LanguageRuntimeCollection::iterator pos;
2023 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002024 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002025 {
Jim Inghamab175242012-03-10 00:22:19 +00002026 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002027
Jim Inghamab175242012-03-10 00:22:19 +00002028 m_language_runtimes[language] = runtime_sp;
2029 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002030 }
2031 else
2032 return (*pos).second.get();
2033}
2034
2035CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002036Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002037{
Jim Inghamab175242012-03-10 00:22:19 +00002038 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002039 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2040 return static_cast<CPPLanguageRuntime *> (runtime);
2041 return NULL;
2042}
2043
2044ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002045Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002046{
Jim Inghamab175242012-03-10 00:22:19 +00002047 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002048 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2049 return static_cast<ObjCLanguageRuntime *> (runtime);
2050 return NULL;
2051}
2052
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002053bool
2054Process::IsPossibleDynamicValue (ValueObject& in_value)
2055{
2056 if (in_value.IsDynamic())
2057 return false;
2058 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2059
2060 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2061 {
2062 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2063 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2064 }
2065
2066 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2067 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2068 return true;
2069
2070 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2071 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2072}
2073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074BreakpointSiteList &
2075Process::GetBreakpointSiteList()
2076{
2077 return m_breakpoint_site_list;
2078}
2079
2080const BreakpointSiteList &
2081Process::GetBreakpointSiteList() const
2082{
2083 return m_breakpoint_site_list;
2084}
2085
2086
2087void
2088Process::DisableAllBreakpointSites ()
2089{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002090 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2091// bp_site->SetEnabled(true);
2092 DisableBreakpointSite(bp_site);
2093 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002094}
2095
2096Error
2097Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2098{
2099 Error error (DisableBreakpointSiteByID (break_id));
2100
2101 if (error.Success())
2102 m_breakpoint_site_list.Remove(break_id);
2103
2104 return error;
2105}
2106
2107Error
2108Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2109{
2110 Error error;
2111 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2112 if (bp_site_sp)
2113 {
2114 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002115 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116 }
2117 else
2118 {
Daniel Malead01b2952012-11-29 21:49:15 +00002119 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002120 }
2121
2122 return error;
2123}
2124
2125Error
2126Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2127{
2128 Error error;
2129 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2130 if (bp_site_sp)
2131 {
2132 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002133 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134 }
2135 else
2136 {
Daniel Malead01b2952012-11-29 21:49:15 +00002137 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 }
2139 return error;
2140}
2141
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002142lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002143Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002145 addr_t load_addr = LLDB_INVALID_ADDRESS;
2146
2147 bool show_error = true;
2148 switch (GetState())
2149 {
2150 case eStateInvalid:
2151 case eStateUnloaded:
2152 case eStateConnected:
2153 case eStateAttaching:
2154 case eStateLaunching:
2155 case eStateDetached:
2156 case eStateExited:
2157 show_error = false;
2158 break;
2159
2160 case eStateStopped:
2161 case eStateRunning:
2162 case eStateStepping:
2163 case eStateCrashed:
2164 case eStateSuspended:
2165 show_error = IsAlive();
2166 break;
2167 }
2168
2169 // Reset the IsIndirect flag here, in case the location changes from
2170 // pointing to a indirect symbol to a regular symbol.
2171 owner->SetIsIndirect (false);
2172
2173 if (owner->ShouldResolveIndirectFunctions())
2174 {
2175 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2176 if (symbol && symbol->IsIndirect())
2177 {
2178 Error error;
2179 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2180 if (!error.Success() && show_error)
2181 {
Greg Clayton44d93782014-01-27 23:43:24 +00002182 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2183 symbol->GetAddress().GetLoadAddress(&m_target),
2184 owner->GetBreakpoint().GetID(),
2185 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002186 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002187 return LLDB_INVALID_BREAK_ID;
2188 }
2189 Address resolved_address(load_addr);
2190 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2191 owner->SetIsIndirect(true);
2192 }
2193 else
2194 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2195 }
2196 else
2197 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2198
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002199 if (load_addr != LLDB_INVALID_ADDRESS)
2200 {
2201 BreakpointSiteSP bp_site_sp;
2202
2203 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2204 // create a new breakpoint site and add it.
2205
2206 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2207
2208 if (bp_site_sp)
2209 {
2210 bp_site_sp->AddOwner (owner);
2211 owner->SetBreakpointSite (bp_site_sp);
2212 return bp_site_sp->GetID();
2213 }
2214 else
2215 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002216 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217 if (bp_site_sp)
2218 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002219 Error error = EnableBreakpointSite (bp_site_sp.get());
2220 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002221 {
2222 owner->SetBreakpointSite (bp_site_sp);
2223 return m_breakpoint_site_list.Add (bp_site_sp);
2224 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002225 else
2226 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002227 if (show_error)
2228 {
2229 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002230 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2231 load_addr,
2232 owner->GetBreakpoint().GetID(),
2233 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002234 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002235 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002236 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237 }
2238 }
2239 }
2240 // We failed to enable the breakpoint
2241 return LLDB_INVALID_BREAK_ID;
2242
2243}
2244
2245void
2246Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2247{
2248 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2249 if (num_owners == 0)
2250 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002251 // Don't try to disable the site if we don't have a live process anymore.
2252 if (IsAlive())
2253 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2255 }
2256}
2257
2258
2259size_t
2260Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2261{
2262 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002263 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002264
Jim Ingham20c77192011-06-29 19:42:28 +00002265 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002267 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2268 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002270 addr_t intersect_addr;
2271 size_t intersect_size;
2272 size_t opcode_offset;
2273 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002274 {
2275 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2276 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002277 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002278 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002279 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002280 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002282 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283 }
2284 return bytes_removed;
2285}
2286
2287
Greg Claytonded470d2011-03-19 01:12:21 +00002288
2289size_t
2290Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2291{
2292 PlatformSP platform_sp (m_target.GetPlatform());
2293 if (platform_sp)
2294 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2295 return 0;
2296}
2297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298Error
2299Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2300{
2301 Error error;
2302 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002303 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 const addr_t bp_addr = bp_site->GetLoadAddress();
2305 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002306 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307 if (bp_site->IsEnabled())
2308 {
2309 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002310 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 +00002311 return error;
2312 }
2313
2314 if (bp_addr == LLDB_INVALID_ADDRESS)
2315 {
2316 error.SetErrorString("BreakpointSite contains an invalid load address.");
2317 return error;
2318 }
2319 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2320 // trap for the breakpoint site
2321 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2322
2323 if (bp_opcode_size == 0)
2324 {
Daniel Malead01b2952012-11-29 21:49:15 +00002325 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 }
2327 else
2328 {
2329 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2330
2331 if (bp_opcode_bytes == NULL)
2332 {
2333 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2334 return error;
2335 }
2336
2337 // Save the original opcode by reading it
2338 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2339 {
2340 // Write a software breakpoint in place of the original opcode
2341 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2342 {
2343 uint8_t verify_bp_opcode_bytes[64];
2344 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2345 {
2346 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2347 {
2348 bp_site->SetEnabled(true);
2349 bp_site->SetType (BreakpointSite::eSoftware);
2350 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002351 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352 bp_site->GetID(),
2353 (uint64_t)bp_addr);
2354 }
2355 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002356 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 }
2358 else
2359 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2360 }
2361 else
2362 error.SetErrorString("Unable to write breakpoint trap to memory.");
2363 }
2364 else
2365 error.SetErrorString("Unable to read memory at breakpoint address.");
2366 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002367 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002368 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369 bp_site->GetID(),
2370 (uint64_t)bp_addr,
2371 error.AsCString());
2372 return error;
2373}
2374
2375Error
2376Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2377{
2378 Error error;
2379 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002380 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 addr_t bp_addr = bp_site->GetLoadAddress();
2382 lldb::user_id_t breakID = bp_site->GetID();
2383 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002384 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385
2386 if (bp_site->IsHardware())
2387 {
2388 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2389 }
2390 else if (bp_site->IsEnabled())
2391 {
2392 const size_t break_op_size = bp_site->GetByteSize();
2393 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2394 if (break_op_size > 0)
2395 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002396 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002397 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002398 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002399 bool break_op_found = false;
2400
2401 // Read the breakpoint opcode
2402 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2403 {
2404 bool verify = false;
2405 // Make sure we have the a breakpoint opcode exists at this address
2406 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2407 {
2408 break_op_found = true;
2409 // We found a valid breakpoint opcode at this address, now restore
2410 // the saved opcode.
2411 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2412 {
2413 verify = true;
2414 }
2415 else
2416 error.SetErrorString("Memory write failed when restoring original opcode.");
2417 }
2418 else
2419 {
2420 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2421 // Set verify to true and so we can check if the original opcode has already been restored
2422 verify = true;
2423 }
2424
2425 if (verify)
2426 {
Greg Claytonc982c762010-07-09 20:39:50 +00002427 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002428 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002429 // Verify that our original opcode made it back to the inferior
2430 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2431 {
2432 // compare the memory we just read with the original opcode
2433 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2434 {
2435 // SUCCESS
2436 bp_site->SetEnabled(false);
2437 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002438 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 +00002439 return error;
2440 }
2441 else
2442 {
2443 if (break_op_found)
2444 error.SetErrorString("Failed to restore original opcode.");
2445 }
2446 }
2447 else
2448 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2449 }
2450 }
2451 else
2452 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2453 }
2454 }
2455 else
2456 {
2457 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002458 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 +00002459 return error;
2460 }
2461
2462 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002463 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002464 bp_site->GetID(),
2465 (uint64_t)bp_addr,
2466 error.AsCString());
2467 return error;
2468
2469}
2470
Greg Clayton58be07b2011-01-07 06:08:19 +00002471// Uncomment to verify memory caching works after making changes to caching code
2472//#define VERIFY_MEMORY_READS
2473
Sean Callanan64c0cf22012-06-07 22:26:42 +00002474size_t
2475Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2476{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002477 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002478 if (!GetDisableMemoryCache())
2479 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002480#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002481 // Memory caching is enabled, with debug verification
2482
2483 if (buf && size)
2484 {
2485 // Uncomment the line below to make sure memory caching is working.
2486 // I ran this through the test suite and got no assertions, so I am
2487 // pretty confident this is working well. If any changes are made to
2488 // memory caching, uncomment the line below and test your changes!
2489
2490 // Verify all memory reads by using the cache first, then redundantly
2491 // reading the same memory from the inferior and comparing to make sure
2492 // everything is exactly the same.
2493 std::string verify_buf (size, '\0');
2494 assert (verify_buf.size() == size);
2495 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2496 Error verify_error;
2497 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2498 assert (cache_bytes_read == verify_bytes_read);
2499 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2500 assert (verify_error.Success() == error.Success());
2501 return cache_bytes_read;
2502 }
2503 return 0;
2504#else // !defined(VERIFY_MEMORY_READS)
2505 // Memory caching is enabled, without debug verification
2506
2507 return m_memory_cache.Read (addr, buf, size, error);
2508#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002509 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002510 else
2511 {
2512 // Memory caching is disabled
2513
2514 return ReadMemoryFromInferior (addr, buf, size, error);
2515 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002516}
Greg Clayton58be07b2011-01-07 06:08:19 +00002517
Greg Clayton4c82d422012-05-18 23:20:01 +00002518size_t
2519Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2520{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002521 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002522 out_str.clear();
2523 addr_t curr_addr = addr;
2524 while (1)
2525 {
2526 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2527 if (length == 0)
2528 break;
2529 out_str.append(buf, length);
2530 // If we got "length - 1" bytes, we didn't get the whole C string, we
2531 // need to read some more characters
2532 if (length == sizeof(buf) - 1)
2533 curr_addr += length;
2534 else
2535 break;
2536 }
2537 return out_str.size();
2538}
2539
Greg Clayton58be07b2011-01-07 06:08:19 +00002540
2541size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002542Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2543 size_t type_width)
2544{
2545 size_t total_bytes_read = 0;
2546 if (dst && max_bytes && type_width && max_bytes >= type_width)
2547 {
2548 // Ensure a null terminator independent of the number of bytes that is read.
2549 memset (dst, 0, max_bytes);
2550 size_t bytes_left = max_bytes - type_width;
2551
2552 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2553 assert(sizeof(terminator) >= type_width &&
2554 "Attempting to validate a string with more than 4 bytes per character!");
2555
2556 addr_t curr_addr = addr;
2557 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2558 char *curr_dst = dst;
2559
2560 error.Clear();
2561 while (bytes_left > 0 && error.Success())
2562 {
2563 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2564 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2565 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2566
2567 if (bytes_read == 0)
2568 break;
2569
2570 // Search for a null terminator of correct size and alignment in bytes_read
2571 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2572 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2573 if (::strncmp(&dst[i], terminator, type_width) == 0)
2574 {
2575 error.Clear();
2576 return i;
2577 }
2578
2579 total_bytes_read += bytes_read;
2580 curr_dst += bytes_read;
2581 curr_addr += bytes_read;
2582 bytes_left -= bytes_read;
2583 }
2584 }
2585 else
2586 {
2587 if (max_bytes)
2588 error.SetErrorString("invalid arguments");
2589 }
2590 return total_bytes_read;
2591}
2592
2593// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2594// null terminators.
2595size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002596Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002597{
2598 size_t total_cstr_len = 0;
2599 if (dst && dst_max_len)
2600 {
Greg Claytone91b7952011-12-15 03:14:23 +00002601 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002602 // NULL out everything just to be safe
2603 memset (dst, 0, dst_max_len);
2604 Error error;
2605 addr_t curr_addr = addr;
2606 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2607 size_t bytes_left = dst_max_len - 1;
2608 char *curr_dst = dst;
2609
2610 while (bytes_left > 0)
2611 {
2612 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2613 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2614 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2615
2616 if (bytes_read == 0)
2617 {
Greg Claytone91b7952011-12-15 03:14:23 +00002618 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002619 dst[total_cstr_len] = '\0';
2620 break;
2621 }
2622 const size_t len = strlen(curr_dst);
2623
2624 total_cstr_len += len;
2625
2626 if (len < bytes_to_read)
2627 break;
2628
2629 curr_dst += bytes_read;
2630 curr_addr += bytes_read;
2631 bytes_left -= bytes_read;
2632 }
2633 }
Greg Claytone91b7952011-12-15 03:14:23 +00002634 else
2635 {
2636 if (dst == NULL)
2637 result_error.SetErrorString("invalid arguments");
2638 else
2639 result_error.Clear();
2640 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002641 return total_cstr_len;
2642}
2643
2644size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002645Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2646{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647 if (buf == NULL || size == 0)
2648 return 0;
2649
2650 size_t bytes_read = 0;
2651 uint8_t *bytes = (uint8_t *)buf;
2652
2653 while (bytes_read < size)
2654 {
2655 const size_t curr_size = size - bytes_read;
2656 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2657 bytes + bytes_read,
2658 curr_size,
2659 error);
2660 bytes_read += curr_bytes_read;
2661 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2662 break;
2663 }
2664
2665 // Replace any software breakpoint opcodes that fall into this range back
2666 // into "buf" before we return
2667 if (bytes_read > 0)
2668 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2669 return bytes_read;
2670}
2671
Greg Clayton58a4c462010-12-16 20:01:20 +00002672uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002673Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002674{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002675 Scalar scalar;
2676 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2677 return scalar.ULongLong(fail_value);
2678 return fail_value;
2679}
2680
2681addr_t
2682Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2683{
2684 Scalar scalar;
2685 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2686 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2687 return LLDB_INVALID_ADDRESS;
2688}
2689
2690
2691bool
2692Process::WritePointerToMemory (lldb::addr_t vm_addr,
2693 lldb::addr_t ptr_value,
2694 Error &error)
2695{
2696 Scalar scalar;
2697 const uint32_t addr_byte_size = GetAddressByteSize();
2698 if (addr_byte_size <= 4)
2699 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002700 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002701 scalar = ptr_value;
2702 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002703}
2704
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705size_t
2706Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2707{
2708 size_t bytes_written = 0;
2709 const uint8_t *bytes = (const uint8_t *)buf;
2710
2711 while (bytes_written < size)
2712 {
2713 const size_t curr_size = size - bytes_written;
2714 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2715 bytes + bytes_written,
2716 curr_size,
2717 error);
2718 bytes_written += curr_bytes_written;
2719 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2720 break;
2721 }
2722 return bytes_written;
2723}
2724
2725size_t
2726Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2727{
Greg Clayton58be07b2011-01-07 06:08:19 +00002728#if defined (ENABLE_MEMORY_CACHING)
2729 m_memory_cache.Flush (addr, size);
2730#endif
2731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002732 if (buf == NULL || size == 0)
2733 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002734
Jim Ingham4b536182011-08-09 02:12:22 +00002735 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002736
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737 // We need to write any data that would go where any current software traps
2738 // (enabled software breakpoints) any software traps (breakpoints) that we
2739 // may have placed in our tasks memory.
2740
Greg Claytond8cf1a12013-06-12 00:46:38 +00002741 BreakpointSiteList bp_sites_in_range;
2742
2743 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002745 // No breakpoint sites overlap
2746 if (bp_sites_in_range.IsEmpty())
2747 return WriteMemoryPrivate (addr, buf, size, error);
2748 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002750 const uint8_t *ubuf = (const uint8_t *)buf;
2751 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002752
Greg Claytond8cf1a12013-06-12 00:46:38 +00002753 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2754
2755 if (error.Success())
2756 {
2757 addr_t intersect_addr;
2758 size_t intersect_size;
2759 size_t opcode_offset;
2760 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2761 assert(intersects);
2762 assert(addr <= intersect_addr && intersect_addr < addr + size);
2763 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2764 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2765
2766 // Check for bytes before this breakpoint
2767 const addr_t curr_addr = addr + bytes_written;
2768 if (intersect_addr > curr_addr)
2769 {
2770 // There are some bytes before this breakpoint that we need to
2771 // just write to memory
2772 size_t curr_size = intersect_addr - curr_addr;
2773 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2774 ubuf + bytes_written,
2775 curr_size,
2776 error);
2777 bytes_written += curr_bytes_written;
2778 if (curr_bytes_written != curr_size)
2779 {
2780 // We weren't able to write all of the requested bytes, we
2781 // are done looping and will return the number of bytes that
2782 // we have written so far.
2783 if (error.Success())
2784 error.SetErrorToGenericError();
2785 }
2786 }
2787 // Now write any bytes that would cover up any software breakpoints
2788 // directly into the breakpoint opcode buffer
2789 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2790 bytes_written += intersect_size;
2791 }
2792 });
2793
2794 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002795 WriteMemoryPrivate (addr + bytes_written,
2796 ubuf + bytes_written,
2797 size - bytes_written,
2798 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002799 }
2800 }
2801 else
2802 {
2803 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804 }
2805
2806 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002807 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002809
2810size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002811Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002812{
2813 if (byte_size == UINT32_MAX)
2814 byte_size = scalar.GetByteSize();
2815 if (byte_size > 0)
2816 {
2817 uint8_t buf[32];
2818 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2819 if (mem_size > 0)
2820 return WriteMemory(addr, buf, mem_size, error);
2821 else
2822 error.SetErrorString ("failed to get scalar as memory data");
2823 }
2824 else
2825 {
2826 error.SetErrorString ("invalid scalar value");
2827 }
2828 return 0;
2829}
2830
2831size_t
2832Process::ReadScalarIntegerFromMemory (addr_t addr,
2833 uint32_t byte_size,
2834 bool is_signed,
2835 Scalar &scalar,
2836 Error &error)
2837{
Greg Clayton7060f892013-05-01 23:41:30 +00002838 uint64_t uval = 0;
2839 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002840 {
Greg Clayton7060f892013-05-01 23:41:30 +00002841 error.SetErrorString ("byte size is zero");
2842 }
2843 else if (byte_size & (byte_size - 1))
2844 {
2845 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2846 }
2847 else if (byte_size <= sizeof(uval))
2848 {
2849 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002850 if (bytes_read == byte_size)
2851 {
2852 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002853 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002854 if (byte_size <= 4)
2855 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002856 else
Greg Clayton7060f892013-05-01 23:41:30 +00002857 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002858 if (is_signed)
2859 scalar.SignExtend(byte_size * 8);
2860 return bytes_read;
2861 }
2862 }
2863 else
2864 {
2865 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2866 }
2867 return 0;
2868}
2869
Greg Claytond495c532011-05-17 03:37:42 +00002870#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002871addr_t
2872Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2873{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002874 if (GetPrivateState() != eStateStopped)
2875 return LLDB_INVALID_ADDRESS;
2876
Greg Claytond495c532011-05-17 03:37:42 +00002877#if defined (USE_ALLOCATE_MEMORY_CACHE)
2878 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2879#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002880 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002881 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002882 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002883 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 +00002884 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002885 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002886 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002887 m_mod_id.GetStopID(),
2888 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002889 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002890#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891}
2892
Sean Callanan90539452011-09-20 23:01:51 +00002893bool
2894Process::CanJIT ()
2895{
Sean Callanana7b443a2012-02-14 22:50:38 +00002896 if (m_can_jit == eCanJITDontKnow)
2897 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002898 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002899 Error err;
2900
2901 uint64_t allocated_memory = AllocateMemory(8,
2902 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2903 err);
2904
2905 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002906 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002907 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002908 if (log)
2909 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2910 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002911 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002912 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002913 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002914 if (log)
2915 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2916 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002917
2918 DeallocateMemory (allocated_memory);
2919 }
2920
Sean Callanan90539452011-09-20 23:01:51 +00002921 return m_can_jit == eCanJITYes;
2922}
2923
2924void
2925Process::SetCanJIT (bool can_jit)
2926{
2927 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2928}
2929
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930Error
2931Process::DeallocateMemory (addr_t ptr)
2932{
Greg Claytond495c532011-05-17 03:37:42 +00002933 Error error;
2934#if defined (USE_ALLOCATE_MEMORY_CACHE)
2935 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2936 {
Daniel Malead01b2952012-11-29 21:49:15 +00002937 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002938 }
2939#else
2940 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002941
Greg Clayton5160ce52013-03-27 23:08:40 +00002942 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002943 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002944 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 +00002945 ptr,
2946 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002947 m_mod_id.GetStopID(),
2948 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002949#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002950 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951}
2952
Han Ming Ongc811d382012-11-17 00:33:14 +00002953
Greg Claytonc9660542012-02-05 02:38:54 +00002954ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002955Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002956 lldb::addr_t header_addr,
2957 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002958{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002959 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002960 if (module_sp)
2961 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002962 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002963 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002964 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002965 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002966 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002967 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002968}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002969
2970Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002971Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972{
2973 Error error;
2974 error.SetErrorString("watchpoints are not supported");
2975 return error;
2976}
2977
2978Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002979Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002980{
2981 Error error;
2982 error.SetErrorString("watchpoints are not supported");
2983 return error;
2984}
2985
2986StateType
2987Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2988{
2989 StateType state;
2990 // Now wait for the process to launch and return control to us, and then
2991 // call DidLaunch:
2992 while (1)
2993 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002994 event_sp.reset();
2995 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2996
Greg Clayton2637f822011-11-17 01:23:07 +00002997 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002998 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002999
3000 // If state is invalid, then we timed out
3001 if (state == eStateInvalid)
3002 break;
3003
3004 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003005 HandlePrivateEvent (event_sp);
3006 }
3007 return state;
3008}
3009
Greg Clayton332e8b12015-01-13 21:13:08 +00003010void
3011Process::LoadOperatingSystemPlugin(bool flush)
3012{
3013 if (flush)
3014 m_thread_list.Clear();
3015 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3016 if (flush)
3017 Flush();
3018}
3019
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003020Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003021Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022{
3023 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003024 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003025 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003026 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003027 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003028 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003029 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003030 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003031
Greg Claytonaa149cb2011-08-11 02:48:45 +00003032 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033 if (exe_module)
3034 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003035 char local_exec_file_path[PATH_MAX];
3036 char platform_exec_file_path[PATH_MAX];
3037 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3038 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003039 if (exe_module->GetFileSpec().Exists())
3040 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003041 // Install anything that might need to be installed prior to launching.
3042 // For host systems, this will do nothing, but if we are connected to a
3043 // remote platform it will install any needed binaries
3044 error = GetTarget().Install(&launch_info);
3045 if (error.Fail())
3046 return error;
3047
Greg Clayton71337622011-02-24 22:24:29 +00003048 if (PrivateStateThreadIsValid ())
3049 PausePrivateStateThread ();
3050
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051 error = WillLaunch (exe_module);
3052 if (error.Success())
3053 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003054 const bool restarted = false;
3055 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003056 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057
Ed Maste64fad602013-07-29 20:58:06 +00003058 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003059 {
3060 // Now launch using these arguments.
3061 error = DoLaunch (exe_module, launch_info);
3062 }
3063 else
3064 {
3065 // This shouldn't happen
3066 error.SetErrorString("failed to acquire process run lock");
3067 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068
3069 if (error.Fail())
3070 {
3071 if (GetID() != LLDB_INVALID_PROCESS_ID)
3072 {
3073 SetID (LLDB_INVALID_PROCESS_ID);
3074 const char *error_string = error.AsCString();
3075 if (error_string == NULL)
3076 error_string = "launch failed";
3077 SetExitStatus (-1, error_string);
3078 }
3079 }
3080 else
3081 {
3082 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003083 TimeValue timeout_time;
3084 timeout_time = TimeValue::Now();
3085 timeout_time.OffsetWithSeconds(10);
3086 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003087
Greg Clayton1a38ea72011-06-22 01:42:17 +00003088 if (state == eStateInvalid || event_sp.get() == NULL)
3089 {
3090 // We were able to launch the process, but we failed to
3091 // catch the initial stop.
3092 SetExitStatus (0, "failed to catch stop after launch");
3093 Destroy();
3094 }
3095 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003097
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003098 DidLaunch ();
3099
Greg Claytonc859e2d2012-02-13 23:10:39 +00003100 DynamicLoader *dyld = GetDynamicLoader ();
3101 if (dyld)
3102 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003103
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003104 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003105
Jason Molendaeef51062013-11-05 03:57:19 +00003106 SystemRuntime *system_runtime = GetSystemRuntime ();
3107 if (system_runtime)
3108 system_runtime->DidLaunch();
3109
Greg Clayton332e8b12015-01-13 21:13:08 +00003110 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003111
3112 // Note, the stop event was consumed above, but not handled. This was done
3113 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3114 // Directly set the state. This is done to prevent a stop message with a bunch
3115 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3116 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003117
3118 if (PrivateStateThreadIsValid ())
3119 ResumePrivateStateThread ();
3120 else
3121 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003122
3123 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003124 }
3125 else if (state == eStateExited)
3126 {
3127 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3128 // not likely to work, and return an invalid pid.
3129 HandlePrivateEvent (event_sp);
3130 }
3131 }
3132 }
3133 }
3134 else
3135 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003136 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 }
3138 }
3139 return error;
3140}
3141
Greg Claytonc3776bf2012-02-09 06:16:32 +00003142
3143Error
3144Process::LoadCore ()
3145{
3146 Error error = DoLoadCore();
3147 if (error.Success())
3148 {
3149 if (PrivateStateThreadIsValid ())
3150 ResumePrivateStateThread ();
3151 else
3152 StartPrivateStateThread ();
3153
Greg Claytonc859e2d2012-02-13 23:10:39 +00003154 DynamicLoader *dyld = GetDynamicLoader ();
3155 if (dyld)
3156 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003157
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003158 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003159
Jason Molendaeef51062013-11-05 03:57:19 +00003160 SystemRuntime *system_runtime = GetSystemRuntime ();
3161 if (system_runtime)
3162 system_runtime->DidAttach();
3163
Greg Claytonc859e2d2012-02-13 23:10:39 +00003164 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003165 // We successfully loaded a core file, now pretend we stopped so we can
3166 // show all of the threads in the core file and explore the crashed
3167 // state.
3168 SetPrivateState (eStateStopped);
3169
3170 }
3171 return error;
3172}
3173
Greg Claytonc859e2d2012-02-13 23:10:39 +00003174DynamicLoader *
3175Process::GetDynamicLoader ()
3176{
3177 if (m_dyld_ap.get() == NULL)
3178 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3179 return m_dyld_ap.get();
3180}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003181
Todd Fialaaf245d12014-06-30 21:05:18 +00003182const lldb::DataBufferSP
3183Process::GetAuxvData()
3184{
3185 return DataBufferSP ();
3186}
3187
Andrew MacPherson17220c12014-03-05 10:12:43 +00003188JITLoaderList &
3189Process::GetJITLoaders ()
3190{
3191 if (!m_jit_loaders_ap)
3192 {
3193 m_jit_loaders_ap.reset(new JITLoaderList());
3194 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3195 }
3196 return *m_jit_loaders_ap;
3197}
3198
Jason Molendaeef51062013-11-05 03:57:19 +00003199SystemRuntime *
3200Process::GetSystemRuntime ()
3201{
3202 if (m_system_runtime_ap.get() == NULL)
3203 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3204 return m_system_runtime_ap.get();
3205}
3206
Todd Fiala76e0fc92014-08-27 22:58:26 +00003207Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3208 NextEventAction (process),
3209 m_exec_count (exec_count)
3210{
3211 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3212 if (log)
3213 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3214}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003215
Jim Inghambb3a2832011-01-29 01:49:25 +00003216Process::NextEventAction::EventActionResult
3217Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003219 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3220
Jim Inghambb3a2832011-01-29 01:49:25 +00003221 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003222 if (log)
3223 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3224
3225 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003226 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003227 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003228 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003229 return eEventActionRetry;
3230
3231 case eStateStopped:
3232 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003233 {
3234 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003235 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003236 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003237 // We don't want these events to be reported, so go set the ShouldReportStop here:
3238 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3239
Greg Claytonc9ed4782011-11-12 02:10:56 +00003240 if (m_exec_count > 0)
3241 {
3242 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003243
3244 if (log)
3245 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3246
Jim Ingham221d51c2013-05-08 00:35:16 +00003247 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003248 return eEventActionRetry;
3249 }
3250 else
3251 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003252 if (log)
3253 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3254
Greg Claytonc9ed4782011-11-12 02:10:56 +00003255 m_process->CompleteAttach ();
3256 return eEventActionSuccess;
3257 }
3258 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003259 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003260
Greg Clayton513c26c2011-01-29 07:10:55 +00003261 default:
3262 case eStateExited:
3263 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003264 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003265 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003266
3267 m_exit_string.assign ("No valid Process");
3268 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003269}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270
Jim Inghambb3a2832011-01-29 01:49:25 +00003271Process::NextEventAction::EventActionResult
3272Process::AttachCompletionHandler::HandleBeingInterrupted()
3273{
3274 return eEventActionSuccess;
3275}
3276
3277const char *
3278Process::AttachCompletionHandler::GetExitString ()
3279{
3280 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003281}
3282
Greg Clayton8012cad2014-11-17 19:39:20 +00003283Listener &
3284ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3285{
3286 if (m_listener_sp)
3287 return *m_listener_sp;
3288 else
3289 return debugger.GetListener();
3290}
3291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003293Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003296 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003297 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003298 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003299 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003300 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003301 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003302
Greg Clayton144f3a92011-11-15 03:53:30 +00003303 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003304 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003305 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003306 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003307 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003308
Greg Clayton144f3a92011-11-15 03:53:30 +00003309 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003310 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003311 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3312
3313 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003314 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003315 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3316 if (error.Success())
3317 {
Ed Maste64fad602013-07-29 20:58:06 +00003318 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003319 {
3320 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003321 const bool restarted = false;
3322 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003323 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003324 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003325 }
3326 else
3327 {
3328 // This shouldn't happen
3329 error.SetErrorString("failed to acquire process run lock");
3330 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003331
Greg Clayton144f3a92011-11-15 03:53:30 +00003332 if (error.Fail())
3333 {
3334 if (GetID() != LLDB_INVALID_PROCESS_ID)
3335 {
3336 SetID (LLDB_INVALID_PROCESS_ID);
3337 if (error.AsCString() == NULL)
3338 error.SetErrorString("attach failed");
3339
3340 SetExitStatus(-1, error.AsCString());
3341 }
3342 }
3343 else
3344 {
3345 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3346 StartPrivateStateThread();
3347 }
3348 return error;
3349 }
Greg Claytone996fd32011-03-08 22:40:15 +00003350 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003351 else
Greg Claytone996fd32011-03-08 22:40:15 +00003352 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003353 ProcessInstanceInfoList process_infos;
3354 PlatformSP platform_sp (m_target.GetPlatform ());
3355
3356 if (platform_sp)
3357 {
3358 ProcessInstanceInfoMatch match_info;
3359 match_info.GetProcessInfo() = attach_info;
3360 match_info.SetNameMatchType (eNameMatchEquals);
3361 platform_sp->FindProcesses (match_info, process_infos);
3362 const uint32_t num_matches = process_infos.GetSize();
3363 if (num_matches == 1)
3364 {
3365 attach_pid = process_infos.GetProcessIDAtIndex(0);
3366 // Fall through and attach using the above process ID
3367 }
3368 else
3369 {
3370 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3371 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003372 {
3373 StreamString s;
3374 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3375 for (size_t i = 0; i < num_matches; i++)
3376 {
3377 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3378 }
3379 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3380 process_name,
3381 s.GetData());
3382 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003383 else
3384 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3385 }
3386 }
3387 else
3388 {
3389 error.SetErrorString ("invalid platform, can't find processes by name");
3390 return error;
3391 }
Greg Claytone996fd32011-03-08 22:40:15 +00003392 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393 }
3394 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003395 {
3396 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003397 }
3398 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003399
3400 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003401 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003402 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003403 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003405
Ed Maste64fad602013-07-29 20:58:06 +00003406 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003407 {
3408 // Now attach using these arguments.
3409 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003410 const bool restarted = false;
3411 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003412 error = DoAttachToProcessWithID (attach_pid, attach_info);
3413 }
3414 else
3415 {
3416 // This shouldn't happen
3417 error.SetErrorString("failed to acquire process run lock");
3418 }
3419
Greg Clayton144f3a92011-11-15 03:53:30 +00003420 if (error.Success())
3421 {
3422
3423 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3424 StartPrivateStateThread();
3425 }
3426 else
Greg Claytone996fd32011-03-08 22:40:15 +00003427 {
3428 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003429 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003430
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003431 const char *error_string = error.AsCString();
3432 if (error_string == NULL)
3433 error_string = "attach failed";
3434
3435 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003436 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 }
3438 }
3439 return error;
3440}
3441
Greg Clayton93d3c8332011-02-16 04:46:07 +00003442void
3443Process::CompleteAttach ()
3444{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003445 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3446 if (log)
3447 log->Printf ("Process::%s()", __FUNCTION__);
3448
Greg Clayton93d3c8332011-02-16 04:46:07 +00003449 // Let the process subclass figure out at much as it can about the process
3450 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003451 ArchSpec process_arch;
3452 DidAttach(process_arch);
3453
3454 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003455 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003456 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003457 if (log)
3458 {
3459 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3460 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3461 __FUNCTION__,
3462 triple_str ? triple_str : "<null>");
3463 }
3464 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003465
Jim Ingham4299fdb2011-09-15 01:10:17 +00003466 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3467 // the same as the one we've already set, switch architectures.
3468 PlatformSP platform_sp (m_target.GetPlatform ());
3469 assert (platform_sp.get());
3470 if (platform_sp)
3471 {
Greg Clayton70512312012-05-08 01:45:38 +00003472 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003473 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003474 {
3475 ArchSpec platform_arch;
3476 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3477 if (platform_sp)
3478 {
3479 m_target.SetPlatform (platform_sp);
3480 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003481 if (log)
3482 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 +00003483 }
3484 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003485 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003486 {
3487 ProcessInstanceInfo process_info;
3488 platform_sp->GetProcessInfo (GetID(), process_info);
3489 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003490 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003491 {
Greg Clayton70512312012-05-08 01:45:38 +00003492 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003493 if (log)
3494 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 ());
3495 }
Greg Clayton70512312012-05-08 01:45:38 +00003496 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003497 }
3498
3499 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003500 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003501 DynamicLoader *dyld = GetDynamicLoader ();
3502 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003503 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003504 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003505 if (log)
3506 {
3507 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3508 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3509 __FUNCTION__,
3510 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3511 dyld->GetPluginName().AsCString ("<unnamed>"));
3512 }
3513 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003514
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003515 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003516
Jason Molendaeef51062013-11-05 03:57:19 +00003517 SystemRuntime *system_runtime = GetSystemRuntime ();
3518 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003519 {
Jason Molendaeef51062013-11-05 03:57:19 +00003520 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003521 if (log)
3522 {
3523 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3524 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3525 __FUNCTION__,
3526 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3527 system_runtime->GetPluginName().AsCString("<unnamed>"));
3528 }
3529 }
Jason Molendaeef51062013-11-05 03:57:19 +00003530
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003531 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003532 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003533 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003534 Mutex::Locker modules_locker(target_modules.GetMutex());
3535 size_t num_modules = target_modules.GetSize();
3536 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003537
Andy Gibbsa297a972013-06-19 19:04:53 +00003538 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003539 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003540 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003541 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003542 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003543 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003544 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003545 break;
3546 }
3547 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003548 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003549 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003550 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003551 if (log)
3552 {
3553 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3554 log->Printf ("Process::%s after looping through modules, target executable is %s",
3555 __FUNCTION__,
3556 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3557 }
3558 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003559
3560 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003561}
3562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003563Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003564Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003565{
Greg Claytonb766a732011-02-04 01:58:07 +00003566 m_abi_sp.reset();
3567 m_process_input_reader.reset();
3568
3569 // Find the process and its architecture. Make sure it matches the architecture
3570 // of the current Target, and if not adjust it.
3571
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003572 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003573 if (error.Success())
3574 {
Greg Clayton71337622011-02-24 22:24:29 +00003575 if (GetID() != LLDB_INVALID_PROCESS_ID)
3576 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003577 EventSP event_sp;
3578 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3579
3580 if (state == eStateStopped || state == eStateCrashed)
3581 {
3582 // If we attached and actually have a process on the other end, then
3583 // this ended up being the equivalent of an attach.
3584 CompleteAttach ();
3585
3586 // This delays passing the stopped event to listeners till
3587 // CompleteAttach gets a chance to complete...
3588 HandlePrivateEvent (event_sp);
3589
3590 }
Greg Clayton71337622011-02-24 22:24:29 +00003591 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003592
3593 if (PrivateStateThreadIsValid ())
3594 ResumePrivateStateThread ();
3595 else
3596 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003597 }
3598 return error;
3599}
3600
3601
3602Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003603Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003604{
Greg Clayton5160ce52013-03-27 23:08:40 +00003605 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003606 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003607 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003608 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003609 StateAsCString(m_public_state.GetValue()),
3610 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003611
3612 Error error (WillResume());
3613 // Tell the process it is about to resume before the thread list
3614 if (error.Success())
3615 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003616 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617 // can let all of our threads know that they are about to be
3618 // resumed. Threads will each be called with
3619 // Thread::WillResume(StateType) where StateType contains the state
3620 // that they are supposed to have when the process is resumed
3621 // (suspended/running/stepping). Threads should also check
3622 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003623 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003624 if (m_thread_list.WillResume())
3625 {
Jim Ingham372787f2012-04-07 00:00:41 +00003626 // Last thing, do the PreResumeActions.
3627 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003628 {
Jim Ingham0161b492013-02-09 01:29:05 +00003629 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003630 }
3631 else
3632 {
3633 m_mod_id.BumpResumeID();
3634 error = DoResume();
3635 if (error.Success())
3636 {
3637 DidResume();
3638 m_thread_list.DidResume();
3639 if (log)
3640 log->Printf ("Process thinks the process has resumed.");
3641 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003642 }
3643 }
3644 else
3645 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003646 // Somebody wanted to run without running. So generate a continue & a stopped event,
3647 // and let the world handle them.
3648 if (log)
3649 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3650
3651 SetPrivateState(eStateRunning);
3652 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003653 }
3654 }
Jim Ingham444586b2011-01-24 06:34:17 +00003655 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003656 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003657 return error;
3658}
3659
3660Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003661Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003662{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003663 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3664 // in case it was already set and some thread plan logic calls halt on its
3665 // own.
3666 m_clear_thread_plans_on_stop |= clear_thread_plans;
3667
Jim Inghamaacc3182012-06-06 00:29:30 +00003668 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3669 // we could just straightaway get another event. It just narrows the window...
3670 m_currently_handling_event.WaitForValueEqualTo(false);
3671
3672
Jim Inghambb3a2832011-01-29 01:49:25 +00003673 // Pause our private state thread so we can ensure no one else eats
3674 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003675 Listener halt_listener ("lldb.process.halt_listener");
3676 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003677
Jim Inghambb3a2832011-01-29 01:49:25 +00003678 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003679 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003680
Greg Clayton06357c92014-07-30 17:38:47 +00003681 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003682 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003683 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003684
Greg Clayton513c26c2011-01-29 07:10:55 +00003685 bool caused_stop = false;
3686
3687 // Ask the process subclass to actually halt our process
3688 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003689 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003690 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003691 if (m_public_state.GetValue() == eStateAttaching)
3692 {
Greg Clayton06357c92014-07-30 17:38:47 +00003693 // Don't hijack and eat the eStateExited as the code that was doing
3694 // the attach will be waiting for this event...
3695 RestorePrivateProcessEvents();
3696 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003697 SetExitStatus(SIGKILL, "Cancelled async attach.");
3698 Destroy ();
3699 }
3700 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003701 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003702 // If "caused_stop" is true, then DoHalt stopped the process. If
3703 // "caused_stop" is false, the process was already stopped.
3704 // If the DoHalt caused the process to stop, then we want to catch
3705 // this event and set the interrupted bool to true before we pass
3706 // this along so clients know that the process was interrupted by
3707 // a halt command.
3708 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003709 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003710 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003711 TimeValue timeout_time;
3712 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003713 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003714 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3715 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003716
Jim Ingham0f16e732011-02-08 05:20:59 +00003717 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003718 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003719 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003720 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003721 }
3722 else
3723 {
Greg Clayton2637f822011-11-17 01:23:07 +00003724 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003725 {
3726 // We caused the process to interrupt itself, so mark this
3727 // as such in the stop event so clients can tell an interrupted
3728 // process from a natural stop
3729 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3730 }
3731 else
3732 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003733 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003734 if (log)
3735 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3736 error.SetErrorString ("Did not get stopped event after halt.");
3737 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003738 }
3739 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003740 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003741 }
3742 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003743 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003744 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003745 if (!restored_process_events)
3746 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003747
3748 // Post any event we might have consumed. If all goes well, we will have
3749 // stopped the process, intercepted the event and set the interrupted
3750 // bool in the event. Post it to the private event queue and that will end up
3751 // correctly setting the state.
3752 if (event_sp)
3753 m_private_state_broadcaster.BroadcastEvent(event_sp);
3754
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003755 return error;
3756}
3757
3758Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003759Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3760{
3761 Error error;
3762 if (m_public_state.GetValue() == eStateRunning)
3763 {
3764 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3765 if (log)
3766 log->Printf("Process::Destroy() About to halt.");
3767 error = Halt();
3768 if (error.Success())
3769 {
3770 // Consume the halt event.
3771 TimeValue timeout (TimeValue::Now());
3772 timeout.OffsetWithSeconds(1);
3773 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3774
3775 // If the process exited while we were waiting for it to stop, put the exited event into
3776 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3777 // they don't have a process anymore...
3778
3779 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3780 {
3781 if (log)
3782 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3783 return error;
3784 }
3785 else
3786 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3787
3788 if (state != eStateStopped)
3789 {
3790 if (log)
3791 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3792 // If we really couldn't stop the process then we should just error out here, but if the
3793 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3794 StateType private_state = m_private_state.GetValue();
3795 if (private_state != eStateStopped)
3796 {
3797 return error;
3798 }
3799 }
3800 }
3801 else
3802 {
3803 if (log)
3804 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3805 }
3806 }
3807 return error;
3808}
3809
3810Error
Jim Inghamacff8952013-05-02 00:27:30 +00003811Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003812{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003813 EventSP exit_event_sp;
3814 Error error;
3815 m_destroy_in_process = true;
3816
3817 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003818
3819 if (error.Success())
3820 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003821 if (DetachRequiresHalt())
3822 {
3823 error = HaltForDestroyOrDetach (exit_event_sp);
3824 if (!error.Success())
3825 {
3826 m_destroy_in_process = false;
3827 return error;
3828 }
3829 else if (exit_event_sp)
3830 {
3831 // We shouldn't need to do anything else here. There's no process left to detach from...
3832 StopPrivateStateThread();
3833 m_destroy_in_process = false;
3834 return error;
3835 }
3836 }
3837
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003838 m_thread_list.DiscardThreadPlans();
3839 DisableAllBreakpointSites();
3840
Jim Inghamacff8952013-05-02 00:27:30 +00003841 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003842 if (error.Success())
3843 {
3844 DidDetach();
3845 StopPrivateStateThread();
3846 }
Jim Inghamacff8952013-05-02 00:27:30 +00003847 else
3848 {
3849 return error;
3850 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003851 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003852 m_destroy_in_process = false;
3853
3854 // If we exited when we were waiting for a process to stop, then
3855 // forward the event here so we don't lose the event
3856 if (exit_event_sp)
3857 {
3858 // Directly broadcast our exited event because we shut down our
3859 // private state thread above
3860 BroadcastEvent(exit_event_sp);
3861 }
3862
3863 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3864 // the last events through the event system, in which case we might strand the write lock. Unlock
3865 // it here so when we do to tear down the process we don't get an error destroying the lock.
3866
Ed Maste64fad602013-07-29 20:58:06 +00003867 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003868 return error;
3869}
3870
3871Error
3872Process::Destroy ()
3873{
Jim Ingham09437922013-03-01 20:04:25 +00003874
3875 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3876 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3877 // failed and the process stays around for some reason it won't be in a confused state.
3878
3879 m_destroy_in_process = true;
3880
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003881 Error error (WillDestroy());
3882 if (error.Success())
3883 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003884 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003885 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003886 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003887 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003888 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003889
Jim Inghamaacc3182012-06-06 00:29:30 +00003890 if (m_public_state.GetValue() != eStateRunning)
3891 {
3892 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3893 // kill it, we don't want it hitting a breakpoint...
3894 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3895 // we're not going to have much luck doing this now.
3896 m_thread_list.DiscardThreadPlans();
3897 DisableAllBreakpointSites();
3898 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003899
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003900 error = DoDestroy();
3901 if (error.Success())
3902 {
3903 DidDestroy();
3904 StopPrivateStateThread();
3905 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003906 m_stdio_communication.StopReadThread();
3907 m_stdio_communication.Disconnect();
Greg Claytonb4874f12014-02-28 18:22:24 +00003908
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003909 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003910 {
3911 m_process_input_reader->SetIsDone(true);
3912 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003913 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003914 }
3915
Greg Clayton85fb1b92012-09-11 02:33:37 +00003916 // If we exited when we were waiting for a process to stop, then
3917 // forward the event here so we don't lose the event
3918 if (exit_event_sp)
3919 {
3920 // Directly broadcast our exited event because we shut down our
3921 // private state thread above
3922 BroadcastEvent(exit_event_sp);
3923 }
3924
Jim Inghamb1e2e842012-04-12 18:49:31 +00003925 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3926 // the last events through the event system, in which case we might strand the write lock. Unlock
3927 // 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 +00003928 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003929 }
Jim Ingham09437922013-03-01 20:04:25 +00003930
3931 m_destroy_in_process = false;
3932
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003933 return error;
3934}
3935
3936Error
3937Process::Signal (int signal)
3938{
3939 Error error (WillSignal());
3940 if (error.Success())
3941 {
3942 error = DoSignal(signal);
3943 if (error.Success())
3944 DidSignal();
3945 }
3946 return error;
3947}
3948
Greg Clayton514487e2011-02-15 21:59:32 +00003949lldb::ByteOrder
3950Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003951{
Greg Clayton514487e2011-02-15 21:59:32 +00003952 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003953}
3954
3955uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003956Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957{
Greg Clayton514487e2011-02-15 21:59:32 +00003958 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003959}
3960
Greg Clayton514487e2011-02-15 21:59:32 +00003961
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003962bool
3963Process::ShouldBroadcastEvent (Event *event_ptr)
3964{
3965 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3966 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003967 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003968
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003969 switch (state)
3970 {
Greg Claytonb766a732011-02-04 01:58:07 +00003971 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003972 case eStateAttaching:
3973 case eStateLaunching:
3974 case eStateDetached:
3975 case eStateExited:
3976 case eStateUnloaded:
3977 // These events indicate changes in the state of the debugging session, always report them.
3978 return_value = true;
3979 break;
3980 case eStateInvalid:
3981 // We stopped for no apparent reason, don't report it.
3982 return_value = false;
3983 break;
3984 case eStateRunning:
3985 case eStateStepping:
3986 // If we've started the target running, we handle the cases where we
3987 // are already running and where there is a transition from stopped to
3988 // running differently.
3989 // running -> running: Automatically suppress extra running events
3990 // stopped -> running: Report except when there is one or more no votes
3991 // and no yes votes.
3992 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003993 if (m_force_next_event_delivery)
3994 return_value = true;
3995 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003996 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003997 switch (m_last_broadcast_state)
3998 {
3999 case eStateRunning:
4000 case eStateStepping:
4001 // We always suppress multiple runnings with no PUBLIC stop in between.
4002 return_value = false;
4003 break;
4004 default:
4005 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004006 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004007 // events. If I run the lldb/test/thread/a.out file and
4008 // break at main.cpp:58, run and hit the breakpoints on
4009 // multiple threads, then somehow during the stepping over
4010 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011
Jim Ingham1460e4b2014-01-10 23:46:59 +00004012 // This is a transition from stop to run.
4013 switch (m_thread_list.ShouldReportRun (event_ptr))
4014 {
4015 case eVoteYes:
4016 case eVoteNoOpinion:
4017 return_value = true;
4018 break;
4019 case eVoteNo:
4020 return_value = false;
4021 break;
4022 }
4023 break;
4024 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004025 }
4026 break;
4027 case eStateStopped:
4028 case eStateCrashed:
4029 case eStateSuspended:
4030 {
4031 // We've stopped. First see if we're going to restart the target.
4032 // If we are going to stop, then we always broadcast the event.
4033 // 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 +00004034 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004035
Jim Inghamcb4ca112012-05-16 01:32:14 +00004036 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004037 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004038 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004039 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004040 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004041 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004042 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004043 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4044 // so they can properly set their state.
4045 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004046 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004047 }
4048 else
4049 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004050 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4051 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004052
Jim Ingham0161b492013-02-09 01:29:05 +00004053 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4054 // Asking the thread list is also not likely to go well, since we are running again.
4055 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004056
Jim Ingham0161b492013-02-09 01:29:05 +00004057 if (!was_restarted)
4058 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004059
Jim Ingham221d51c2013-05-08 00:35:16 +00004060 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004061 {
Jim Ingham0161b492013-02-09 01:29:05 +00004062 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4063 if (log)
4064 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004065 should_resume, StateAsCString(state),
4066 was_restarted, stop_vote);
4067
Jim Ingham0161b492013-02-09 01:29:05 +00004068 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004069 {
4070 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004071 return_value = true;
4072 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004073 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004074 case eVoteNo:
4075 return_value = false;
4076 break;
4077 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004078
Jim Inghamcb95f342012-09-05 21:13:56 +00004079 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004080 {
4081 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004082 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4083 static_cast<void*>(event_ptr),
4084 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004085 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004086 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004087 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004088
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004089 }
4090 else
4091 {
4092 return_value = true;
4093 SynchronouslyNotifyStateChanged (state);
4094 }
4095 }
4096 }
Jim Ingham0161b492013-02-09 01:29:05 +00004097 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004099
Jim Ingham1460e4b2014-01-10 23:46:59 +00004100 // Forcing the next event delivery is a one shot deal. So reset it here.
4101 m_force_next_event_delivery = false;
4102
Jim Ingham0161b492013-02-09 01:29:05 +00004103 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4104 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4105 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4106 // because the PublicState reflects the last event pulled off the queue, and there may be several
4107 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4108 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004109
Jim Ingham0161b492013-02-09 01:29:05 +00004110 if (return_value)
4111 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004112
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004113 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004114 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004115 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004116 StateAsCString(m_last_broadcast_state),
4117 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004118 return return_value;
4119}
4120
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121
4122bool
Jim Ingham372787f2012-04-07 00:00:41 +00004123Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004124{
Greg Clayton5160ce52013-03-27 23:08:40 +00004125 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004126
Greg Clayton8b82f082011-04-12 05:54:46 +00004127 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004129 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4130
Jim Ingham372787f2012-04-07 00:00:41 +00004131 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004132 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004133
4134 // Create a thread that watches our internal state and controls which
4135 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004136 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004137
Zachary Turner39de3112014-09-09 20:54:56 +00004138 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004139 {
Zachary Turner39de3112014-09-09 20:54:56 +00004140 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4141 if (already_running)
4142 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4143 else
4144 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004145 }
Jim Ingham372787f2012-04-07 00:00:41 +00004146 else
Todd Fiala17096d72014-07-16 19:03:16 +00004147 {
4148 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004149 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004150 else
Zachary Turner39de3112014-09-09 20:54:56 +00004151 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004152 }
4153
Jim Ingham076b3042012-04-10 01:21:57 +00004154 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00004155 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004156 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004157 {
4158 ResumePrivateStateThread();
4159 return true;
4160 }
4161 else
4162 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004163}
4164
4165void
4166Process::PausePrivateStateThread ()
4167{
4168 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4169}
4170
4171void
4172Process::ResumePrivateStateThread ()
4173{
4174 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4175}
4176
4177void
4178Process::StopPrivateStateThread ()
4179{
Greg Clayton8b82f082011-04-12 05:54:46 +00004180 if (PrivateStateThreadIsValid ())
4181 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004182 else
4183 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004184 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004185 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004186 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004187 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004188}
4189
4190void
4191Process::ControlPrivateStateThread (uint32_t signal)
4192{
Greg Clayton5160ce52013-03-27 23:08:40 +00004193 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004194
4195 assert (signal == eBroadcastInternalStateControlStop ||
4196 signal == eBroadcastInternalStateControlPause ||
4197 signal == eBroadcastInternalStateControlResume);
4198
4199 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004200 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004201
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004202 // Signal the private state thread. First we should copy this is case the
4203 // thread starts exiting since the private state thread will NULL this out
4204 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004205 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004206 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004207 {
4208 TimeValue timeout_time;
4209 bool timed_out;
4210
4211 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4212
4213 timeout_time = TimeValue::Now();
4214 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004215 if (log)
4216 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004217 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4218 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4219
4220 if (signal == eBroadcastInternalStateControlStop)
4221 {
4222 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004223 {
Zachary Turner39de3112014-09-09 20:54:56 +00004224 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004225 if (log)
4226 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4227 }
4228 else
4229 {
4230 if (log)
4231 log->Printf ("The control event killed the private state thread without having to cancel.");
4232 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004233
4234 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004235 private_state_thread.Join(&result);
4236 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004237 }
4238 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004239 else
4240 {
4241 if (log)
4242 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4243 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004244}
4245
4246void
Jim Inghamcfc09352012-07-27 23:57:19 +00004247Process::SendAsyncInterrupt ()
4248{
4249 if (PrivateStateThreadIsValid())
4250 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4251 else
4252 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4253}
4254
4255void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004256Process::HandlePrivateEvent (EventSP &event_sp)
4257{
Greg Clayton5160ce52013-03-27 23:08:40 +00004258 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004259 m_resume_requested = false;
4260
Jim Inghamaacc3182012-06-06 00:29:30 +00004261 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004262
Greg Clayton414f5d32011-01-25 02:58:48 +00004263 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004264
4265 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004266 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004267 {
Jim Ingham754ab982011-01-29 04:05:41 +00004268 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004269 if (log)
4270 log->Printf ("Ran next event action, result was %d.", action_result);
4271
Jim Inghambb3a2832011-01-29 01:49:25 +00004272 switch (action_result)
4273 {
4274 case NextEventAction::eEventActionSuccess:
4275 SetNextEventAction(NULL);
4276 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004277
Jim Inghambb3a2832011-01-29 01:49:25 +00004278 case NextEventAction::eEventActionRetry:
4279 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004280
Jim Inghambb3a2832011-01-29 01:49:25 +00004281 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004282 // Handle Exiting Here. If we already got an exited event,
4283 // we should just propagate it. Otherwise, swallow this event,
4284 // and set our state to exit so the next event will kill us.
4285 if (new_state != eStateExited)
4286 {
4287 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004288 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004289 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004290 SetNextEventAction(NULL);
4291 return;
4292 }
4293 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004294 break;
4295 }
4296 }
4297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004298 // See if we should broadcast this state to external clients?
4299 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004300
4301 if (should_broadcast)
4302 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004303 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004304 if (log)
4305 {
Daniel Malead01b2952012-11-29 21:49:15 +00004306 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004307 __FUNCTION__,
4308 GetID(),
4309 StateAsCString(new_state),
4310 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004311 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004312 }
Jim Ingham9575d842011-03-11 03:53:59 +00004313 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004314 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004315 {
4316 // Only push the input handler if we aren't fowarding events,
4317 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004318 // Or don't push it if we are launching since it will come up stopped.
4319 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004320 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004321 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004322 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004323 else if (StateIsStoppedState(new_state, false))
4324 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004325 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004326 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4327 {
4328 // If the lldb_private::Debugger is handling the events, we don't
4329 // want to pop the process IOHandler here, we want to do it when
4330 // we receive the stopped event so we can carefully control when
4331 // the process IOHandler is popped because when we stop we want to
4332 // display some text stating how and why we stopped, then maybe some
4333 // process/thread/frame info, and then we want the "(lldb) " prompt
4334 // to show up. If we pop the process IOHandler here, then we will
4335 // cause the command interpreter to become the top IOHandler after
4336 // the process pops off and it will update its prompt right away...
4337 // See the Debugger.cpp file where it calls the function as
4338 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4339 // Otherwise we end up getting overlapping "(lldb) " prompts and
4340 // garbled output.
4341 //
4342 // If we aren't handling the events in the debugger (which is indicated
4343 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4344 // are hijacked, then we always pop the process IO handler manually.
4345 // Hijacking happens when the internal process state thread is running
4346 // thread plans, or when commands want to run in synchronous mode
4347 // and they call "process->WaitForProcessToStop()". An example of something
4348 // that will hijack the events is a simple expression:
4349 //
4350 // (lldb) expr (int)puts("hello")
4351 //
4352 // This will cause the internal process state thread to resume and halt
4353 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4354 // events) and we do need the IO handler to be pushed and popped
4355 // correctly.
4356
4357 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4358 PopProcessIOHandler ();
4359 }
4360 }
Jim Ingham9575d842011-03-11 03:53:59 +00004361
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004362 BroadcastEvent (event_sp);
4363 }
4364 else
4365 {
4366 if (log)
4367 {
Daniel Malead01b2952012-11-29 21:49:15 +00004368 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004369 __FUNCTION__,
4370 GetID(),
4371 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004372 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004373 }
4374 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004375 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004376}
4377
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004378thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004379Process::PrivateStateThread (void *arg)
4380{
4381 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004382 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004383 return result;
4384}
4385
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004386thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004387Process::RunPrivateStateThread ()
4388{
Jim Ingham076b3042012-04-10 01:21:57 +00004389 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004390 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004391
Greg Clayton5160ce52013-03-27 23:08:40 +00004392 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004393 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004394 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4395 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004396
4397 bool exit_now = false;
4398 while (!exit_now)
4399 {
4400 EventSP event_sp;
4401 WaitForEventsPrivate (NULL, event_sp, control_only);
4402 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4403 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004404 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004405 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4406 __FUNCTION__, static_cast<void*>(this), GetID(),
4407 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004408
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004409 switch (event_sp->GetType())
4410 {
4411 case eBroadcastInternalStateControlStop:
4412 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004413 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004414
4415 case eBroadcastInternalStateControlPause:
4416 control_only = true;
4417 break;
4418
4419 case eBroadcastInternalStateControlResume:
4420 control_only = false;
4421 break;
4422 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004423
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004424 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004425 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004426 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004427 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4428 {
4429 if (m_public_state.GetValue() == eStateAttaching)
4430 {
4431 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004432 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4433 __FUNCTION__, static_cast<void*>(this),
4434 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004435 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4436 }
4437 else
4438 {
4439 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004440 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4441 __FUNCTION__, static_cast<void*>(this),
4442 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004443 Halt();
4444 }
4445 continue;
4446 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004447
4448 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4449
4450 if (internal_state != eStateInvalid)
4451 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004452 if (m_clear_thread_plans_on_stop &&
4453 StateIsStoppedState(internal_state, true))
4454 {
4455 m_clear_thread_plans_on_stop = false;
4456 m_thread_list.DiscardThreadPlans();
4457 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004458 HandlePrivateEvent (event_sp);
4459 }
4460
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004461 if (internal_state == eStateInvalid ||
4462 internal_state == eStateExited ||
4463 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004464 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004465 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004466 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4467 __FUNCTION__, static_cast<void*>(this), GetID(),
4468 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004469
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004470 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004471 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004472 }
4473
Caroline Tice20ad3c42010-10-29 21:48:37 +00004474 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004475 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004476 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4477 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004478
Ed Maste64fad602013-07-29 20:58:06 +00004479 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004480 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004481 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004482 return NULL;
4483}
4484
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004485//------------------------------------------------------------------
4486// Process Event Data
4487//------------------------------------------------------------------
4488
4489Process::ProcessEventData::ProcessEventData () :
4490 EventData (),
4491 m_process_sp (),
4492 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004493 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004494 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004495 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004496{
4497}
4498
4499Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4500 EventData (),
4501 m_process_sp (process_sp),
4502 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004503 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004504 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004505 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004506{
4507}
4508
4509Process::ProcessEventData::~ProcessEventData()
4510{
4511}
4512
4513const ConstString &
4514Process::ProcessEventData::GetFlavorString ()
4515{
4516 static ConstString g_flavor ("Process::ProcessEventData");
4517 return g_flavor;
4518}
4519
4520const ConstString &
4521Process::ProcessEventData::GetFlavor () const
4522{
4523 return ProcessEventData::GetFlavorString ();
4524}
4525
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004526void
4527Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4528{
4529 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004530 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4531 // the public event queue, then other times when we're pretending that this is where we stopped at the
4532 // end of expression evaluation. m_update_state is used to distinguish these
4533 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004534 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004535 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004536 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004537
Jim Ingham221d51c2013-05-08 00:35:16 +00004538 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004539
4540 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4541 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4542 // end up restarting the process.
4543 if (m_interrupted)
4544 return;
4545
4546 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004547 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004548 {
4549 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004550 uint32_t num_threads = curr_thread_list.GetSize();
4551 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004552
Jim Ingham4b536182011-08-09 02:12:22 +00004553 // The actions might change one of the thread's stop_info's opinions about whether we should
4554 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004555
4556 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4557 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4558 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4559 // 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
4560 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004561 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004562 for (idx = 0; idx < num_threads; ++idx)
4563 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4564
Jim Inghamc7078c22012-12-13 22:24:15 +00004565 // Use this to track whether we should continue from here. We will only continue the target running if
4566 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4567 // then it doesn't matter what the other threads say...
4568
4569 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004570
Jim Ingham0ad7e052013-04-25 02:04:59 +00004571 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4572 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4573 // thing to do is, and it's better to let the user decide than continue behind their backs.
4574
4575 bool does_anybody_have_an_opinion = false;
4576
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004577 for (idx = 0; idx < num_threads; ++idx)
4578 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004579 curr_thread_list = m_process_sp->GetThreadList();
4580 if (curr_thread_list.GetSize() != num_threads)
4581 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004582 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004583 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004584 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 +00004585 break;
4586 }
4587
4588 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4589
4590 if (thread_sp->GetIndexID() != thread_index_array[idx])
4591 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004592 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004593 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004594 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004595 idx,
4596 thread_index_array[idx],
4597 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004598 break;
4599 }
4600
Jim Inghamb15bfc72010-10-20 00:39:53 +00004601 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004602 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004603 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004604 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004605 bool this_thread_wants_to_stop;
4606 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004607 {
Jim Ingham0161b492013-02-09 01:29:05 +00004608 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4609 }
4610 else
4611 {
4612 stop_info_sp->PerformAction(event_ptr);
4613 // The stop action might restart the target. If it does, then we want to mark that in the
4614 // event so that whoever is receiving it will know to wait for the running event and reflect
4615 // that state appropriately.
4616 // We also need to stop processing actions, since they aren't expecting the target to be running.
4617
4618 // FIXME: we might have run.
4619 if (stop_info_sp->HasTargetRunSinceMe())
4620 {
4621 SetRestarted (true);
4622 break;
4623 }
4624
4625 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004626 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004627
Jim Inghamc7078c22012-12-13 22:24:15 +00004628 if (still_should_stop == false)
4629 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004630 }
4631 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004632
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004633
Jim Inghama8ca6e22013-05-03 23:04:37 +00004634 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004635 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004636 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004637 {
4638 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004639 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004640 // Use the public resume method here, since this is just
4641 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004642 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004643 }
4644 else
4645 {
4646 // If we didn't restart, run the Stop Hooks here:
4647 // They might also restart the target, so watch for that.
4648 m_process_sp->GetTarget().RunStopHooks();
4649 if (m_process_sp->GetPrivateState() == eStateRunning)
4650 SetRestarted(true);
4651 }
Jim Ingham9575d842011-03-11 03:53:59 +00004652 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004653 }
4654}
4655
4656void
4657Process::ProcessEventData::Dump (Stream *s) const
4658{
4659 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004660 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4661 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004662
Greg Clayton8b82f082011-04-12 05:54:46 +00004663 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004664}
4665
4666const Process::ProcessEventData *
4667Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4668{
4669 if (event_ptr)
4670 {
4671 const EventData *event_data = event_ptr->GetData();
4672 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4673 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4674 }
4675 return NULL;
4676}
4677
4678ProcessSP
4679Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4680{
4681 ProcessSP process_sp;
4682 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4683 if (data)
4684 process_sp = data->GetProcessSP();
4685 return process_sp;
4686}
4687
4688StateType
4689Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4690{
4691 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4692 if (data == NULL)
4693 return eStateInvalid;
4694 else
4695 return data->GetState();
4696}
4697
4698bool
4699Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4700{
4701 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4702 if (data == NULL)
4703 return false;
4704 else
4705 return data->GetRestarted();
4706}
4707
4708void
4709Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4710{
4711 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4712 if (data != NULL)
4713 data->SetRestarted(new_value);
4714}
4715
Jim Ingham0161b492013-02-09 01:29:05 +00004716size_t
4717Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4718{
4719 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4720 if (data != NULL)
4721 return data->GetNumRestartedReasons();
4722 else
4723 return 0;
4724}
4725
4726const char *
4727Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4728{
4729 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4730 if (data != NULL)
4731 return data->GetRestartedReasonAtIndex(idx);
4732 else
4733 return NULL;
4734}
4735
4736void
4737Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4738{
4739 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4740 if (data != NULL)
4741 data->AddRestartedReason(reason);
4742}
4743
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004744bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004745Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4746{
4747 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4748 if (data == NULL)
4749 return false;
4750 else
4751 return data->GetInterrupted ();
4752}
4753
4754void
4755Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4756{
4757 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4758 if (data != NULL)
4759 data->SetInterrupted(new_value);
4760}
4761
4762bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004763Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4764{
4765 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4766 if (data)
4767 {
4768 data->SetUpdateStateOnRemoval();
4769 return true;
4770 }
4771 return false;
4772}
4773
Greg Claytond9e416c2012-02-18 05:35:26 +00004774lldb::TargetSP
4775Process::CalculateTarget ()
4776{
4777 return m_target.shared_from_this();
4778}
4779
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004780void
Greg Clayton0603aa92010-10-04 01:05:56 +00004781Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004782{
Greg Claytonc14ee322011-09-22 04:58:26 +00004783 exe_ctx.SetTargetPtr (&m_target);
4784 exe_ctx.SetProcessPtr (this);
4785 exe_ctx.SetThreadPtr(NULL);
4786 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004787}
4788
Greg Claytone996fd32011-03-08 22:40:15 +00004789//uint32_t
4790//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4791//{
4792// return 0;
4793//}
4794//
4795//ArchSpec
4796//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4797//{
4798// return Host::GetArchSpecForExistingProcess (pid);
4799//}
4800//
4801//ArchSpec
4802//Process::GetArchSpecForExistingProcess (const char *process_name)
4803//{
4804// return Host::GetArchSpecForExistingProcess (process_name);
4805//}
4806//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004807void
4808Process::AppendSTDOUT (const char * s, size_t len)
4809{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004810 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004811 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004812 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004813}
4814
4815void
Greg Clayton93e86192011-11-13 04:45:22 +00004816Process::AppendSTDERR (const char * s, size_t len)
4817{
4818 Mutex::Locker locker (m_stdio_communication_mutex);
4819 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004820 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004821}
4822
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004823void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004824Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004825{
4826 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004827 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004828 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4829}
4830
4831size_t
4832Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4833{
4834 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004835 if (m_profile_data.empty())
4836 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004837
4838 std::string &one_profile_data = m_profile_data.front();
4839 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004840 if (bytes_available > 0)
4841 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004842 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004843 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004844 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4845 static_cast<void*>(buf),
4846 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004847 if (bytes_available > buf_size)
4848 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004849 memcpy(buf, one_profile_data.c_str(), buf_size);
4850 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004851 bytes_available = buf_size;
4852 }
4853 else
4854 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004855 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004856 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004857 }
4858 }
4859 return bytes_available;
4860}
4861
4862
Greg Clayton93e86192011-11-13 04:45:22 +00004863//------------------------------------------------------------------
4864// Process STDIO
4865//------------------------------------------------------------------
4866
4867size_t
4868Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4869{
4870 Mutex::Locker locker(m_stdio_communication_mutex);
4871 size_t bytes_available = m_stdout_data.size();
4872 if (bytes_available > 0)
4873 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004874 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004875 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004876 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4877 static_cast<void*>(buf),
4878 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004879 if (bytes_available > buf_size)
4880 {
4881 memcpy(buf, m_stdout_data.c_str(), buf_size);
4882 m_stdout_data.erase(0, buf_size);
4883 bytes_available = buf_size;
4884 }
4885 else
4886 {
4887 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4888 m_stdout_data.clear();
4889 }
4890 }
4891 return bytes_available;
4892}
4893
4894
4895size_t
4896Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4897{
4898 Mutex::Locker locker(m_stdio_communication_mutex);
4899 size_t bytes_available = m_stderr_data.size();
4900 if (bytes_available > 0)
4901 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004902 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004903 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004904 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4905 static_cast<void*>(buf),
4906 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004907 if (bytes_available > buf_size)
4908 {
4909 memcpy(buf, m_stderr_data.c_str(), buf_size);
4910 m_stderr_data.erase(0, buf_size);
4911 bytes_available = buf_size;
4912 }
4913 else
4914 {
4915 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4916 m_stderr_data.clear();
4917 }
4918 }
4919 return bytes_available;
4920}
4921
4922void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004923Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4924{
4925 Process *process = (Process *) baton;
4926 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4927}
4928
Greg Clayton44d93782014-01-27 23:43:24 +00004929class IOHandlerProcessSTDIO :
4930 public IOHandler
4931{
4932public:
4933 IOHandlerProcessSTDIO (Process *process,
4934 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00004935 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00004936 m_process (process),
4937 m_read_file (),
4938 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004939 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004940 {
4941 m_read_file.SetDescriptor(GetInputFD(), false);
4942 }
4943
4944 virtual
4945 ~IOHandlerProcessSTDIO ()
4946 {
4947
4948 }
4949
4950 bool
4951 OpenPipes ()
4952 {
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00004953 if (m_pipe.CanRead() && m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00004954 return true;
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00004955 Error result = m_pipe.CreateNew(false);
4956 return result.Success();
Greg Clayton44d93782014-01-27 23:43:24 +00004957 }
4958
4959 void
4960 ClosePipes()
4961 {
Greg Clayton100eb932014-07-02 21:10:39 +00004962 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004963 }
4964
4965 // Each IOHandler gets to run until it is done. It should read data
4966 // from the "in" and place output into "out" and "err and return
4967 // when done.
4968 virtual void
4969 Run ()
4970 {
4971 if (m_read_file.IsValid() && m_write_file.IsValid())
4972 {
4973 SetIsDone(false);
4974 if (OpenPipes())
4975 {
4976 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004977 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004978 TerminalState terminal_state;
4979 terminal_state.Save (read_fd, false);
4980 Terminal terminal(read_fd);
4981 terminal.SetCanonical(false);
4982 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004983// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004984#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00004985 while (!GetIsDone())
4986 {
4987 fd_set read_fdset;
4988 FD_ZERO (&read_fdset);
4989 FD_SET (read_fd, &read_fdset);
4990 FD_SET (pipe_read_fd, &read_fdset);
4991 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
4992 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
4993 if (num_set_fds < 0)
4994 {
4995 const int select_errno = errno;
4996
4997 if (select_errno != EINTR)
4998 SetIsDone(true);
4999 }
5000 else if (num_set_fds > 0)
5001 {
5002 char ch = 0;
5003 size_t n;
5004 if (FD_ISSET (read_fd, &read_fdset))
5005 {
5006 n = 1;
5007 if (m_read_file.Read(&ch, n).Success() && n == 1)
5008 {
5009 if (m_write_file.Write(&ch, n).Fail() || n != 1)
5010 SetIsDone(true);
5011 }
5012 else
5013 SetIsDone(true);
5014 }
5015 if (FD_ISSET (pipe_read_fd, &read_fdset))
5016 {
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005017 size_t bytes_read;
Greg Clayton44d93782014-01-27 23:43:24 +00005018 // Consume the interrupt byte
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005019 Error error = m_pipe.Read(&ch, 1, bytes_read);
5020 if (error.Success())
Greg Clayton19e11352014-02-26 22:47:33 +00005021 {
Greg Clayton100eb932014-07-02 21:10:39 +00005022 switch (ch)
5023 {
5024 case 'q':
5025 SetIsDone(true);
5026 break;
5027 case 'i':
5028 if (StateIsRunningState(m_process->GetState()))
5029 m_process->Halt();
5030 break;
5031 }
Greg Clayton19e11352014-02-26 22:47:33 +00005032 }
Greg Clayton44d93782014-01-27 23:43:24 +00005033 }
5034 }
5035 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00005036#endif
Greg Clayton44d93782014-01-27 23:43:24 +00005037 terminal_state.Restore();
5038
5039 }
5040 else
5041 SetIsDone(true);
5042 }
5043 else
5044 SetIsDone(true);
5045 }
5046
5047 // Hide any characters that have been displayed so far so async
5048 // output can be displayed. Refresh() will be called after the
5049 // output has been displayed.
5050 virtual void
5051 Hide ()
5052 {
5053
5054 }
5055 // Called when the async output has been received in order to update
5056 // the input reader (refresh the prompt and redisplay any current
5057 // line(s) that are being edited
5058 virtual void
5059 Refresh ()
5060 {
5061
5062 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005063
Greg Clayton44d93782014-01-27 23:43:24 +00005064 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00005065 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00005066 {
Greg Clayton19e11352014-02-26 22:47:33 +00005067 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005068 size_t bytes_written = 0;
5069 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005070 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005071
Greg Claytonf0066ad2014-05-02 00:45:31 +00005072 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00005073 Interrupt ()
5074 {
Greg Clayton19e11352014-02-26 22:47:33 +00005075 // Do only things that are safe to do in an interrupt context (like in
5076 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5077 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5078 // that was written to the pipe and then call m_process->Halt() from a
5079 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005080 if (m_active)
5081 {
5082 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005083 size_t bytes_written = 0;
5084 Error result = m_pipe.Write(&ch, 1, bytes_written);
5085 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005086 }
5087 else
5088 {
5089 // This IOHandler might be pushed on the stack, but not being run currently
5090 // so do the right thing if we aren't actively watching for STDIN by sending
5091 // the interrupt to the process. Otherwise the write to the pipe above would
5092 // do nothing. This can happen when the command interpreter is running and
5093 // gets a "expression ...". It will be on the IOHandler thread and sending
5094 // the input is complete to the delegate which will cause the expression to
5095 // run, which will push the process IO handler, but not run it.
5096
5097 if (StateIsRunningState(m_process->GetState()))
5098 {
5099 m_process->SendAsyncInterrupt();
5100 return true;
5101 }
5102 }
5103 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005104 }
Greg Clayton44d93782014-01-27 23:43:24 +00005105
5106 virtual void
5107 GotEOF()
5108 {
5109
5110 }
5111
5112protected:
5113 Process *m_process;
5114 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5115 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005116 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005117};
5118
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005119void
Greg Clayton44d93782014-01-27 23:43:24 +00005120Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005121{
5122 // First set up the Read Thread for reading/handling process I/O
5123
Greg Clayton44d93782014-01-27 23:43:24 +00005124 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005125
5126 if (conn_ap.get())
5127 {
5128 m_stdio_communication.SetConnection (conn_ap.release());
5129 if (m_stdio_communication.IsConnected())
5130 {
5131 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5132 m_stdio_communication.StartReadThread();
5133
5134 // Now read thread is set up, set up input reader.
5135
5136 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005137 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005138 }
5139 }
5140}
5141
Greg Claytonb4874f12014-02-28 18:22:24 +00005142bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005143Process::ProcessIOHandlerIsActive ()
5144{
5145 IOHandlerSP io_handler_sp (m_process_input_reader);
5146 if (io_handler_sp)
5147 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5148 return false;
5149}
5150bool
Greg Clayton44d93782014-01-27 23:43:24 +00005151Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005152{
Greg Clayton44d93782014-01-27 23:43:24 +00005153 IOHandlerSP io_handler_sp (m_process_input_reader);
5154 if (io_handler_sp)
5155 {
5156 io_handler_sp->SetIsDone(false);
5157 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005158 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005159 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005160 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005161}
5162
Greg Claytonb4874f12014-02-28 18:22:24 +00005163bool
Greg Clayton44d93782014-01-27 23:43:24 +00005164Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005165{
Greg Clayton44d93782014-01-27 23:43:24 +00005166 IOHandlerSP io_handler_sp (m_process_input_reader);
5167 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005168 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5169 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005170}
5171
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005172// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005173void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005174Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005175{
Greg Clayton6920b522012-08-22 18:39:03 +00005176 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005177}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005178
Greg Clayton99d0faf2010-11-18 23:32:35 +00005179void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005180Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005181{
Greg Clayton6920b522012-08-22 18:39:03 +00005182 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005183}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005184
Jim Ingham1624a2d2014-05-05 02:26:40 +00005185ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005186Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005187 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005188 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005189 Stream &errors)
5190{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005191 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005192
Jim Ingham77787032011-01-20 02:03:18 +00005193 if (thread_plan_sp.get() == NULL)
5194 {
5195 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005196 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005197 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005198
Jim Ingham7d7931d2013-03-28 00:05:34 +00005199 if (!thread_plan_sp->ValidatePlan(NULL))
5200 {
5201 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005202 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005203 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005204
Greg Claytonc14ee322011-09-22 04:58:26 +00005205 if (exe_ctx.GetProcessPtr() != this)
5206 {
5207 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005208 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005209 }
5210
5211 Thread *thread = exe_ctx.GetThreadPtr();
5212 if (thread == NULL)
5213 {
5214 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005215 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005216 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005217
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005218 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5219 // For that to be true the plan can't be private - since private plans suppress themselves in the
5220 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005221
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005222 bool orig_plan_private = thread_plan_sp->GetPrivate();
5223 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005224
Jim Ingham444586b2011-01-24 06:34:17 +00005225 if (m_private_state.GetValue() != eStateStopped)
5226 {
5227 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005228 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005229 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005230
Jim Ingham66243842011-08-13 00:56:10 +00005231 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005232 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005233 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005234 if (!selected_frame_sp)
5235 {
5236 thread->SetSelectedFrame(0);
5237 selected_frame_sp = thread->GetSelectedFrame();
5238 if (!selected_frame_sp)
5239 {
5240 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005241 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005242 }
5243 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005244
Jim Ingham11b0e052013-02-19 23:22:45 +00005245 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005246
5247 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5248 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005249
Greg Claytonc14ee322011-09-22 04:58:26 +00005250 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005251
Jim Ingham66243842011-08-13 00:56:10 +00005252 uint32_t selected_tid;
5253 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005254 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005255 {
5256 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005257 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005258 }
5259 else
5260 {
5261 selected_tid = LLDB_INVALID_THREAD_ID;
5262 }
5263
Zachary Turner39de3112014-09-09 20:54:56 +00005264 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005265 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005266 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005267
Greg Clayton5160ce52013-03-27 23:08:40 +00005268 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005269 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005270 {
Jim Ingham076b3042012-04-10 01:21:57 +00005271 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5272 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005273 // 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 +00005274 // we are fielding public events here.
5275 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005276 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 +00005277
Jim Ingham372787f2012-04-07 00:00:41 +00005278 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005279
5280 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5281 // returning control here.
5282 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5283 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5284 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5285 // do just what we want.
5286 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5287 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5288 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5289 old_state = m_public_state.GetValue();
5290 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005291
Jim Ingham076b3042012-04-10 01:21:57 +00005292 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005293 StartPrivateStateThread(true);
5294 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005295
Jim Ingham372787f2012-04-07 00:00:41 +00005296 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005297
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005298 if (options.GetDebug())
5299 {
5300 // In this case, we aren't actually going to run, we just want to stop right away.
5301 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5302 // FIXME: To make this prettier we should invent some stop reason for this, but that
5303 // is only cosmetic, and this functionality is only of use to lldb developers who can
5304 // live with not pretty...
5305 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005306 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005307 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005308
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005309 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005310
Sean Callanana46ec452012-07-11 21:31:24 +00005311 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005312
Jim Ingham77787032011-01-20 02:03:18 +00005313 {
Sean Callanana46ec452012-07-11 21:31:24 +00005314 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5315 // restored on exit to the function.
5316 //
5317 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5318 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005319
Sean Callanana46ec452012-07-11 21:31:24 +00005320 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005321
Jim Inghamf48169b2010-11-30 02:22:11 +00005322 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005323 {
5324 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005325 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005326 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005327 thread->GetIndexID(),
5328 thread->GetID(),
5329 s.GetData());
5330 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005331
Sean Callanana46ec452012-07-11 21:31:24 +00005332 bool got_event;
5333 lldb::EventSP event_sp;
5334 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005335
Sean Callanana46ec452012-07-11 21:31:24 +00005336 TimeValue* timeout_ptr = NULL;
5337 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005338
Jim Ingham0161b492013-02-09 01:29:05 +00005339 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 +00005340 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005341 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005342 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005343
Jim Ingham0161b492013-02-09 01:29:05 +00005344 // This is just for accounting:
5345 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005346
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005347 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005348 uint32_t one_thread_timeout_usec;
5349 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005350
5351 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5352 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5353 // first timeout already.
5354
5355 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005356 {
5357 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005358 one_thread_timeout_usec = 0;
5359 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005360 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005361 else
Jim Ingham0161b492013-02-09 01:29:05 +00005362 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005363 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005364
Jim Ingham914f4e72014-03-28 21:58:28 +00005365 // If the overall wait is forever, then we only need to set the one thread timeout:
5366 if (timeout_usec == 0)
5367 {
Ed Maste801335c2014-03-31 19:28:14 +00005368 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005369 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005370 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005371 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005372 }
Jim Ingham0161b492013-02-09 01:29:05 +00005373 else
5374 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005375 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5376 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5377 uint64_t computed_one_thread_timeout;
5378 if (option_one_thread_timeout != 0)
5379 {
5380 if (timeout_usec < option_one_thread_timeout)
5381 {
5382 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005383 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005384 }
5385 computed_one_thread_timeout = option_one_thread_timeout;
5386 }
5387 else
5388 {
5389 computed_one_thread_timeout = timeout_usec / 2;
5390 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5391 computed_one_thread_timeout = default_one_thread_timeout_usec;
5392 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005393 one_thread_timeout_usec = computed_one_thread_timeout;
5394 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5395
Jim Ingham0161b492013-02-09 01:29:05 +00005396 }
Jim Ingham0161b492013-02-09 01:29:05 +00005397 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005398
5399 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005400 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 +00005401 options.GetStopOthers(),
5402 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005403 before_first_timeout,
5404 one_thread_timeout_usec,
5405 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005406
Jim Ingham1460e4b2014-01-10 23:46:59 +00005407 // This isn't going to work if there are unfetched events on the queue.
5408 // Are there cases where we might want to run the remaining events here, and then try to
5409 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005410
Jim Ingham1460e4b2014-01-10 23:46:59 +00005411 Event *other_events = listener.PeekAtNextEvent();
5412 if (other_events != NULL)
5413 {
5414 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005415 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005416 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005417
Jim Ingham1460e4b2014-01-10 23:46:59 +00005418 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5419 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5420 // event coalescing to cause us to lose OUR running event...
5421 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005422
Jim Ingham8559a352012-11-26 23:52:18 +00005423 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5424 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005425
5426#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5427 // It's pretty much impossible to write test cases for things like:
5428 // One thread timeout expires, I go to halt, but the process already stopped
5429 // on the function call stop breakpoint. Turning on this define will make us not
5430 // fetch the first event till after the halt. So if you run a quick function, it will have
5431 // completed, and the completion event will be waiting, when you interrupt for halt.
5432 // The expression evaluation should still succeed.
5433 bool miss_first_event = true;
5434#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005435 TimeValue one_thread_timeout;
5436 TimeValue final_timeout;
5437
Jim Ingham35878c42014-04-08 21:33:21 +00005438
Sean Callanana46ec452012-07-11 21:31:24 +00005439 while (1)
5440 {
5441 // We usually want to resume the process if we get to the top of the loop.
5442 // The only exception is if we get two running events with no intervening
5443 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005444 if (log)
5445 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5446 do_resume,
5447 handle_running_event,
5448 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005449
Jim Ingham184e9812013-01-15 02:47:48 +00005450 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005451 {
5452 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005453
Jim Ingham184e9812013-01-15 02:47:48 +00005454 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005455 {
Jim Ingham0161b492013-02-09 01:29:05 +00005456 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005457 Error resume_error = PrivateResume ();
5458 if (!resume_error.Success())
5459 {
Jim Ingham0161b492013-02-09 01:29:05 +00005460 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5461 num_resumes,
5462 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005463 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005464 break;
5465 }
Sean Callanana46ec452012-07-11 21:31:24 +00005466 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005467
Jim Ingham0161b492013-02-09 01:29:05 +00005468 TimeValue resume_timeout = TimeValue::Now();
5469 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005470
Jim Ingham0161b492013-02-09 01:29:05 +00005471 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005472 if (!got_event)
5473 {
5474 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005475 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5476 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005477
Jim Ingham0161b492013-02-09 01:29:05 +00005478 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005479 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005480 break;
5481 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005482
Sean Callanana46ec452012-07-11 21:31:24 +00005483 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005484
Sean Callanana46ec452012-07-11 21:31:24 +00005485 if (stop_state != eStateRunning)
5486 {
Jim Ingham0161b492013-02-09 01:29:05 +00005487 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005488
Jim Ingham0161b492013-02-09 01:29:05 +00005489 if (stop_state == eStateStopped)
5490 {
5491 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5492 if (log)
5493 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5494 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5495 num_resumes,
5496 StateAsCString(stop_state),
5497 restarted,
5498 do_resume,
5499 handle_running_event);
5500 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005501
Jim Ingham0161b492013-02-09 01:29:05 +00005502 if (restarted)
5503 {
5504 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5505 // event here. But if I do, the best thing is to Halt and then get out of here.
5506 Halt();
5507 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005508
Jim Ingham35e1bda2012-10-16 21:41:58 +00005509 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5510 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005511 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005512 break;
5513 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005514
Sean Callanana46ec452012-07-11 21:31:24 +00005515 if (log)
5516 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5517 // We need to call the function synchronously, so spin waiting for it to return.
5518 // If we get interrupted while executing, we're going to lose our context, and
5519 // won't be able to gather the result at this point.
5520 // We set the timeout AFTER the resume, since the resume takes some time and we
5521 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005522 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005523 else
5524 {
Sean Callanana46ec452012-07-11 21:31:24 +00005525 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005526 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005527 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005528
Jim Ingham0161b492013-02-09 01:29:05 +00005529 if (before_first_timeout)
5530 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005531 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005532 {
5533 one_thread_timeout = TimeValue::Now();
5534 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005535 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005536 }
Jim Ingham0161b492013-02-09 01:29:05 +00005537 else
5538 {
5539 if (timeout_usec == 0)
5540 timeout_ptr = NULL;
5541 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005542 {
5543 final_timeout = TimeValue::Now();
5544 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005545 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005546 }
Jim Ingham0161b492013-02-09 01:29:05 +00005547 }
5548 }
5549 else
5550 {
5551 if (timeout_usec == 0)
5552 timeout_ptr = NULL;
5553 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005554 {
5555 final_timeout = TimeValue::Now();
5556 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005557 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005558 }
Jim Ingham0161b492013-02-09 01:29:05 +00005559 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005560
Jim Ingham0161b492013-02-09 01:29:05 +00005561 do_resume = true;
5562 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005563
Sean Callanana46ec452012-07-11 21:31:24 +00005564 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005565 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005566
Jim Ingham0f16e732011-02-08 05:20:59 +00005567 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005568 {
Sean Callanana46ec452012-07-11 21:31:24 +00005569 if (timeout_ptr)
5570 {
Matt Kopec676a4872013-02-21 23:55:31 +00005571 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005572 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5573 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005574 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005575 else
Sean Callanana46ec452012-07-11 21:31:24 +00005576 {
5577 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5578 }
5579 }
Jim Ingham35878c42014-04-08 21:33:21 +00005580
5581#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5582 // See comment above...
5583 if (miss_first_event)
5584 {
5585 usleep(1000);
5586 miss_first_event = false;
5587 got_event = false;
5588 }
5589 else
5590#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005591 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005592
Sean Callanana46ec452012-07-11 21:31:24 +00005593 if (got_event)
5594 {
5595 if (event_sp.get())
5596 {
5597 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005598 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005599 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005600 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005601 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005602 errors.Printf ("Execution halted by user interrupt.");
5603 if (log)
5604 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005605 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005606 }
5607 else
5608 {
5609 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5610 if (log)
5611 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005612
Jim Inghamcfc09352012-07-27 23:57:19 +00005613 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005614 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005615 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005616 {
Jim Ingham0161b492013-02-09 01:29:05 +00005617 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005618 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5619 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005620 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005621 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005622 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005623 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005624 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005625 }
5626 else
5627 {
Jim Ingham0161b492013-02-09 01:29:05 +00005628 // If we were restarted, we just need to go back up to fetch another event.
5629 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005630 {
5631 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005632 {
5633 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5634 }
5635 keep_going = true;
5636 do_resume = false;
5637 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005638
Jim Inghamcfc09352012-07-27 23:57:19 +00005639 }
5640 else
5641 {
Jim Ingham0161b492013-02-09 01:29:05 +00005642 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5643 StopReason stop_reason = eStopReasonInvalid;
5644 if (stop_info_sp)
5645 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005646
Jim Ingham0161b492013-02-09 01:29:05 +00005647 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5648 // it is OUR plan that is complete?
5649 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005650 {
5651 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005652 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5653 // Now mark this plan as private so it doesn't get reported as the stop reason
5654 // after this point.
5655 if (thread_plan_sp)
5656 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005657 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005658 }
5659 else
5660 {
Jim Ingham0161b492013-02-09 01:29:05 +00005661 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005662 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005663 {
5664 if (log)
5665 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005666 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005667 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005668 {
5669 event_to_broadcast_sp = event_sp;
5670 }
Jim Ingham0161b492013-02-09 01:29:05 +00005671 }
Jim Ingham184e9812013-01-15 02:47:48 +00005672 else
Jim Ingham0161b492013-02-09 01:29:05 +00005673 {
5674 if (log)
5675 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005676 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005677 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005678 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005679 }
Jim Ingham184e9812013-01-15 02:47:48 +00005680 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005681 }
Sean Callanana46ec452012-07-11 21:31:24 +00005682 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005683 }
5684 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005685
Jim Inghamcfc09352012-07-27 23:57:19 +00005686 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005687 // This shouldn't really happen, but sometimes we do get two running events without an
5688 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005689 do_resume = false;
5690 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005691 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005692 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005693
Jim Inghamcfc09352012-07-27 23:57:19 +00005694 default:
5695 if (log)
5696 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005697
Jim Inghamcfc09352012-07-27 23:57:19 +00005698 if (stop_state == eStateExited)
5699 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005700
Sean Callananbf154da2012-08-08 17:35:10 +00005701 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005702 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005703 break;
5704 }
Sean Callanana46ec452012-07-11 21:31:24 +00005705 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005706
Sean Callanana46ec452012-07-11 21:31:24 +00005707 if (keep_going)
5708 continue;
5709 else
5710 break;
5711 }
5712 else
5713 {
5714 if (log)
5715 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005716 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005717 break;
5718 }
5719 }
5720 else
5721 {
5722 // If we didn't get an event that means we've timed out...
5723 // We will interrupt the process here. Depending on what we were asked to do we will
5724 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005725
Sean Callanana46ec452012-07-11 21:31:24 +00005726 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005727 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005728 {
Jim Ingham0161b492013-02-09 01:29:05 +00005729 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005730 {
5731 if (timeout_usec != 0)
5732 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005733 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005734 "running for %" PRIu32 " usec with all threads enabled.",
5735 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005736 }
5737 else
5738 {
5739 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005740 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005741 }
5742 }
Sean Callanana46ec452012-07-11 21:31:24 +00005743 else
5744 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005745 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005746 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005747 }
5748 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005749 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005750 "abandoning execution.",
5751 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005752 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005753
Jim Ingham0161b492013-02-09 01:29:05 +00005754 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5755 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5756 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5757 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5758 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005759
Jim Ingham0161b492013-02-09 01:29:05 +00005760 bool back_to_top = true;
5761 uint32_t try_halt_again = 0;
5762 bool do_halt = true;
5763 const uint32_t num_retries = 5;
5764 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005765 {
Jim Ingham0161b492013-02-09 01:29:05 +00005766 Error halt_error;
5767 if (do_halt)
5768 {
5769 if (log)
5770 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5771 halt_error = Halt();
5772 }
5773 if (halt_error.Success())
5774 {
5775 if (log)
5776 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005777
Jim Ingham0161b492013-02-09 01:29:05 +00005778 real_timeout = TimeValue::Now();
5779 real_timeout.OffsetWithMicroSeconds(500000);
5780
5781 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005782
Jim Ingham0161b492013-02-09 01:29:05 +00005783 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005784 {
Jim Ingham0161b492013-02-09 01:29:05 +00005785 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5786 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005787 {
Jim Ingham0161b492013-02-09 01:29:05 +00005788 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5789 if (stop_state == lldb::eStateStopped
5790 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5791 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005792 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005793
Jim Ingham0161b492013-02-09 01:29:05 +00005794 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005795 {
Jim Ingham0161b492013-02-09 01:29:05 +00005796 // Between the time we initiated the Halt and the time we delivered it, the process could have
5797 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005798
Jim Ingham0161b492013-02-09 01:29:05 +00005799 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5800 {
5801 if (log)
5802 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5803 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005804 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005805 back_to_top = false;
5806 break;
5807 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005808
Jim Ingham0161b492013-02-09 01:29:05 +00005809 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5810 {
5811 if (log)
5812 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5813 "Exiting wait loop.");
5814 try_halt_again++;
5815 do_halt = false;
5816 continue;
5817 }
Sean Callanana46ec452012-07-11 21:31:24 +00005818
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005819 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005820 {
5821 if (log)
5822 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005823 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005824 back_to_top = false;
5825 break;
5826 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005827
Jim Ingham0161b492013-02-09 01:29:05 +00005828 if (before_first_timeout)
5829 {
5830 // Set all the other threads to run, and return to the top of the loop, which will continue;
5831 before_first_timeout = false;
5832 thread_plan_sp->SetStopOthers (false);
5833 if (log)
5834 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005835
Jim Ingham0161b492013-02-09 01:29:05 +00005836 back_to_top = true;
5837 break;
5838 }
5839 else
5840 {
5841 // Running all threads failed, so return Interrupted.
5842 if (log)
5843 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005844 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005845 back_to_top = false;
5846 break;
5847 }
Sean Callanana46ec452012-07-11 21:31:24 +00005848 }
5849 }
5850 else
Jim Ingham0161b492013-02-09 01:29:05 +00005851 { if (log)
5852 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5853 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005854 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005855 back_to_top = false;
5856 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005857 }
5858 }
Jim Ingham0161b492013-02-09 01:29:05 +00005859 else
5860 {
5861 try_halt_again++;
5862 continue;
5863 }
Sean Callanana46ec452012-07-11 21:31:24 +00005864 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005865
Jim Ingham0161b492013-02-09 01:29:05 +00005866 if (!back_to_top || try_halt_again > num_retries)
5867 break;
5868 else
5869 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005870 }
Sean Callanana46ec452012-07-11 21:31:24 +00005871 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005872
Sean Callanana46ec452012-07-11 21:31:24 +00005873 // 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 +00005874 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005875 {
5876 StopPrivateStateThread();
5877 Error error;
5878 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005879 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005880 {
5881 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5882 }
Jason Molenda76513fd2014-10-15 23:39:31 +00005883 if (old_state != eStateInvalid)
5884 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00005885 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005886
Jim Ingham184e9812013-01-15 02:47:48 +00005887 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5888 // could happen:
5889 // 1) The execution successfully completed
5890 // 2) We hit a breakpoint, and ignore_breakpoints was true
5891 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005892 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5893 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005894
Jim Ingham8646d3c2014-05-05 02:47:44 +00005895 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005896 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005897 {
5898 thread_plan_sp->RestoreThreadState();
5899 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005900
Sean Callanana46ec452012-07-11 21:31:24 +00005901 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005902 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005903 {
5904 if (log)
5905 {
5906 StreamString s;
5907 if (event_sp)
5908 event_sp->Dump (&s);
5909 else
5910 {
5911 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5912 }
5913
5914 StreamString ts;
5915
5916 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005917
Sean Callanana46ec452012-07-11 21:31:24 +00005918 do
5919 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005920 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005921 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005922 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005923 break;
5924 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005925 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005926 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005927 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005928 break;
5929 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005930 else
Sean Callanana46ec452012-07-11 21:31:24 +00005931 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005932 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5933
5934 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005935 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005936 event_explanation = "<no event data>";
5937 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005938 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005939
Jim Inghamcfc09352012-07-27 23:57:19 +00005940 Process *process = event_data->GetProcessSP().get();
5941
5942 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005943 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005944 event_explanation = "<no process>";
5945 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005946 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005947
Jim Inghamcfc09352012-07-27 23:57:19 +00005948 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005949
Jim Inghamcfc09352012-07-27 23:57:19 +00005950 uint32_t num_threads = thread_list.GetSize();
5951 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005952
Jim Inghamcfc09352012-07-27 23:57:19 +00005953 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005954
Jim Inghamcfc09352012-07-27 23:57:19 +00005955 for (thread_index = 0;
5956 thread_index < num_threads;
5957 ++thread_index)
5958 {
5959 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005960
Jim Inghamcfc09352012-07-27 23:57:19 +00005961 if (!thread)
5962 {
5963 ts.Printf("<?> ");
5964 continue;
5965 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005966
Daniel Malead01b2952012-11-29 21:49:15 +00005967 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005968 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005969
Jim Inghamcfc09352012-07-27 23:57:19 +00005970 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005971 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005972 else
5973 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005974
Jim Inghamcfc09352012-07-27 23:57:19 +00005975 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5976 if (stop_info_sp)
5977 {
5978 const char *stop_desc = stop_info_sp->GetDescription();
5979 if (stop_desc)
5980 ts.PutCString (stop_desc);
5981 }
5982 ts.Printf(">");
5983 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005984
Jim Inghamcfc09352012-07-27 23:57:19 +00005985 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005986 }
Sean Callanana46ec452012-07-11 21:31:24 +00005987 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005988
Jim Inghamcfc09352012-07-27 23:57:19 +00005989 if (event_explanation)
5990 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005991 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005992 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5993 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005994
Jim Inghame4483cf2013-09-27 01:13:01 +00005995 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005996 {
5997 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005998 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
5999 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006000 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6001 thread_plan_sp->SetPrivate (orig_plan_private);
6002 }
6003 else
6004 {
6005 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006006 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6007 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006008 }
6009 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006010 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006011 {
6012 if (log)
6013 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006014
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006015 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006016 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006017 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006018 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006019 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006020 }
6021 else
6022 {
Sean Callanana46ec452012-07-11 21:31:24 +00006023 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006024 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006025 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006026 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006027 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006028 }
6029 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6030 {
6031 if (log)
6032 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006033 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006034 }
6035 else
6036 {
6037 if (log)
6038 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006039 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006040 {
6041 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006042 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006043 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6044 thread_plan_sp->SetPrivate (orig_plan_private);
6045 }
6046 }
6047 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006048
Sean Callanana46ec452012-07-11 21:31:24 +00006049 // Thread we ran the function in may have gone away because we ran the target
6050 // Check that it's still there, and if it is put it back in the context. Also restore the
6051 // frame in the context if it is still present.
6052 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6053 if (thread)
6054 {
6055 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6056 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006057
Sean Callanana46ec452012-07-11 21:31:24 +00006058 // Also restore the current process'es selected frame & thread, since this function calling may
6059 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006060
Sean Callanana46ec452012-07-11 21:31:24 +00006061 if (selected_tid != LLDB_INVALID_THREAD_ID)
6062 {
6063 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6064 {
6065 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006066 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006067 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006068 if (old_frame_sp)
6069 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006070 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006071 }
6072 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006073
Sean Callanana46ec452012-07-11 21:31:24 +00006074 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006075
Sean Callanana46ec452012-07-11 21:31:24 +00006076 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006077 {
Sean Callanana46ec452012-07-11 21:31:24 +00006078 if (log)
6079 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6080 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006081 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006082
Jim Inghamf48169b2010-11-30 02:22:11 +00006083 return return_value;
6084}
6085
6086const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006087Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006088{
6089 const char *result_name;
6090
6091 switch (result)
6092 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006093 case eExpressionCompleted:
6094 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006095 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006096 case eExpressionDiscarded:
6097 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006098 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006099 case eExpressionInterrupted:
6100 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006101 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006102 case eExpressionHitBreakpoint:
6103 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006104 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006105 case eExpressionSetupError:
6106 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006107 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006108 case eExpressionParseError:
6109 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006110 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006111 case eExpressionResultUnavailable:
6112 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006113 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006114 case eExpressionTimedOut:
6115 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006116 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006117 case eExpressionStoppedForDebug:
6118 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006119 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006120 }
6121 return result_name;
6122}
6123
Greg Clayton7260f622011-04-18 08:33:37 +00006124void
6125Process::GetStatus (Stream &strm)
6126{
6127 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006128 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006129 {
6130 if (state == eStateExited)
6131 {
6132 int exit_status = GetExitStatus();
6133 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006134 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006135 GetID(),
6136 exit_status,
6137 exit_status,
6138 exit_description ? exit_description : "");
6139 }
6140 else
6141 {
6142 if (state == eStateConnected)
6143 strm.Printf ("Connected to remote target.\n");
6144 else
Daniel Malead01b2952012-11-29 21:49:15 +00006145 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006146 }
6147 }
6148 else
6149 {
Daniel Malead01b2952012-11-29 21:49:15 +00006150 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006151 }
6152}
6153
6154size_t
6155Process::GetThreadStatus (Stream &strm,
6156 bool only_threads_with_stop_reason,
6157 uint32_t start_frame,
6158 uint32_t num_frames,
6159 uint32_t num_frames_with_source)
6160{
6161 size_t num_thread_infos_dumped = 0;
6162
Jim Ingham4a65fb12014-03-07 11:20:03 +00006163 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6164 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6165 // ID's, and look them up one by one:
6166
6167 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006168 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006169 //Scope for thread list locker;
6170 {
6171 Mutex::Locker locker (GetThreadList().GetMutex());
6172 ThreadList &curr_thread_list = GetThreadList();
6173 num_threads = curr_thread_list.GetSize();
6174 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006175 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006176 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006177 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006178 }
6179
Greg Clayton7260f622011-04-18 08:33:37 +00006180 for (uint32_t i = 0; i < num_threads; i++)
6181 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006182 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006183 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006184 {
6185 if (only_threads_with_stop_reason)
6186 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006187 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006188 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006189 continue;
6190 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006191 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006192 start_frame,
6193 num_frames,
6194 num_frames_with_source);
6195 ++num_thread_infos_dumped;
6196 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006197 else
6198 {
6199 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6200 if (log)
6201 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6202
6203 }
Greg Clayton7260f622011-04-18 08:33:37 +00006204 }
6205 return num_thread_infos_dumped;
6206}
6207
Greg Claytona9f40ad2012-02-22 04:37:26 +00006208void
6209Process::AddInvalidMemoryRegion (const LoadRange &region)
6210{
6211 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6212}
6213
6214bool
6215Process::RemoveInvalidMemoryRange (const LoadRange &region)
6216{
6217 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6218}
6219
Jim Ingham372787f2012-04-07 00:00:41 +00006220void
6221Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6222{
6223 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6224}
6225
6226bool
6227Process::RunPreResumeActions ()
6228{
6229 bool result = true;
6230 while (!m_pre_resume_actions.empty())
6231 {
6232 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6233 m_pre_resume_actions.pop_back();
6234 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006235 if (result == true)
6236 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006237 }
6238 return result;
6239}
6240
6241void
6242Process::ClearPreResumeActions ()
6243{
6244 m_pre_resume_actions.clear();
6245}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006246
Greg Claytonfa559e52012-05-18 02:38:05 +00006247void
6248Process::Flush ()
6249{
6250 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006251 m_extended_thread_list.Flush();
6252 m_extended_thread_stop_id = 0;
6253 m_queue_list.Clear();
6254 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006255}
Greg Clayton90ba8112012-12-05 00:16:59 +00006256
6257void
6258Process::DidExec ()
6259{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006260 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6261 if (log)
6262 log->Printf ("Process::%s()", __FUNCTION__);
6263
Greg Clayton90ba8112012-12-05 00:16:59 +00006264 Target &target = GetTarget();
6265 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006266 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006267 m_dynamic_checkers_ap.reset();
6268 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006269 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006270 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006271 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006272 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006273 m_image_tokens.clear();
6274 m_allocated_memory_cache.Clear();
6275 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006276 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006277 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006278 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006279 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006280 DoDidExec();
6281 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006282 // Flush the process (threads and all stack frames) after running CompleteAttach()
6283 // in case the dynamic loader loaded things in new locations.
6284 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006285
6286 // After we figure out what was loaded/unloaded in CompleteAttach,
6287 // we need to let the target know so it can do any cleanup it needs to.
6288 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006289}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006290
Jim Ingham1460e4b2014-01-10 23:46:59 +00006291addr_t
6292Process::ResolveIndirectFunction(const Address *address, Error &error)
6293{
6294 if (address == nullptr)
6295 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006296 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006297 return LLDB_INVALID_ADDRESS;
6298 }
6299
6300 addr_t function_addr = LLDB_INVALID_ADDRESS;
6301
6302 addr_t addr = address->GetLoadAddress(&GetTarget());
6303 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6304 if (iter != m_resolved_indirect_addresses.end())
6305 {
6306 function_addr = (*iter).second;
6307 }
6308 else
6309 {
6310 if (!InferiorCall(this, address, function_addr))
6311 {
6312 Symbol *symbol = address->CalculateSymbolContextSymbol();
6313 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6314 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6315 function_addr = LLDB_INVALID_ADDRESS;
6316 }
6317 else
6318 {
6319 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6320 }
6321 }
6322 return function_addr;
6323}
6324
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006325void
6326Process::ModulesDidLoad (ModuleList &module_list)
6327{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006328 SystemRuntime *sys_runtime = GetSystemRuntime();
6329 if (sys_runtime)
6330 {
6331 sys_runtime->ModulesDidLoad (module_list);
6332 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006333
Kuba Breckaafdf8422014-10-10 23:43:03 +00006334 GetJITLoaders().ModulesDidLoad (module_list);
6335
6336 // Give runtimes a chance to be created.
6337 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6338
6339 // Tell runtimes about new modules.
6340 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6341 {
6342 InstrumentationRuntimeSP runtime = pos->second;
6343 runtime->ModulesDidLoad(module_list);
6344 }
6345
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006346}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006347
6348ThreadCollectionSP
6349Process::GetHistoryThreads(lldb::addr_t addr)
6350{
6351 ThreadCollectionSP threads;
6352
6353 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6354
6355 if (! memory_history.get()) {
6356 return threads;
6357 }
6358
6359 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6360
6361 return threads;
6362}
Kuba Brecka63927542014-10-11 01:59:32 +00006363
6364InstrumentationRuntimeSP
6365Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6366{
6367 InstrumentationRuntimeCollection::iterator pos;
6368 pos = m_instrumentation_runtimes.find (type);
6369 if (pos == m_instrumentation_runtimes.end())
6370 {
6371 return InstrumentationRuntimeSP();
6372 }
6373 else
6374 return (*pos).second;
6375}