blob: a1353bf8f02b2dc97167e4e3bba092caae4f3788 [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
Enrico Granatad7a83a92015-02-10 03:06:24 +0000494 case 'G': // Glob args.
495 {
496 bool success;
497 const bool glob_args = Args::StringToBoolean (option_arg, true, &success);
498 if (success)
499 launch_info.SetGlobArguments(glob_args);
500 else
501 error.SetErrorStringWithFormat ("Invalid boolean value for glob-args option: '%s'", option_arg ? option_arg : "<null>");
502 break;
503 }
504
Todd Fiala51637922014-08-19 17:40:43 +0000505 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000506 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000507 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000508 else
Zachary Turner10687b02014-10-20 17:46:43 +0000509 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000510 break;
511
Greg Clayton8b82f082011-04-12 05:54:46 +0000512 case 'v':
513 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
514 break;
515
516 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000517 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000518 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000519 }
520 return error;
521}
522
523OptionDefinition
524ProcessLaunchCommandOptions::g_option_table[] =
525{
Zachary Turnerd37221d2014-07-09 16:31:49 +0000526{ 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 +0000527{ 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 +0000528{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
529{ 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."},
530{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
531{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Enrico Granatad7a83a92015-02-10 03:06:24 +0000532{ LLDB_OPT_SET_1|LLDB_OPT_SET_2|LLDB_OPT_SET_3, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000533
Zachary Turnerd37221d2014-07-09 16:31:49 +0000534{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
535{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
536{ 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 +0000537
Zachary Turnerd37221d2014-07-09 16:31:49 +0000538{ 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 +0000539
Zachary Turnerd37221d2014-07-09 16:31:49 +0000540{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Enrico Granatad7a83a92015-02-10 03:06:24 +0000541{ LLDB_OPT_SET_4, false, "glob-args", 'G', OptionParser::eRequiredArgument, NULL, NULL, 0, eArgTypeBoolean, "Set whether to glob arguments to the process when launching."},
Zachary Turnerd37221d2014-07-09 16:31:49 +0000542{ 0 , false, NULL, 0, 0, NULL, NULL, 0, eArgTypeNone, NULL }
Greg Clayton8b82f082011-04-12 05:54:46 +0000543};
544
545
546
547bool
548ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000549{
550 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
551 return true;
552 const char *match_name = m_match_info.GetName();
553 if (!match_name)
554 return true;
555
556 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
557}
558
559bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000560ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000561{
562 if (!NameMatches (proc_info.GetName()))
563 return false;
564
565 if (m_match_info.ProcessIDIsValid() &&
566 m_match_info.GetProcessID() != proc_info.GetProcessID())
567 return false;
568
569 if (m_match_info.ParentProcessIDIsValid() &&
570 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
571 return false;
572
Greg Clayton8b82f082011-04-12 05:54:46 +0000573 if (m_match_info.UserIDIsValid () &&
574 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000575 return false;
576
Greg Clayton8b82f082011-04-12 05:54:46 +0000577 if (m_match_info.GroupIDIsValid () &&
578 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000579 return false;
580
581 if (m_match_info.EffectiveUserIDIsValid () &&
582 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
583 return false;
584
585 if (m_match_info.EffectiveGroupIDIsValid () &&
586 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
587 return false;
588
589 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000590 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000591 return false;
592 return true;
593}
594
595bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000596ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000597{
598 if (m_name_match_type != eNameMatchIgnore)
599 return false;
600
601 if (m_match_info.ProcessIDIsValid())
602 return false;
603
604 if (m_match_info.ParentProcessIDIsValid())
605 return false;
606
Greg Clayton8b82f082011-04-12 05:54:46 +0000607 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000608 return false;
609
Greg Clayton8b82f082011-04-12 05:54:46 +0000610 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000611 return false;
612
613 if (m_match_info.EffectiveUserIDIsValid ())
614 return false;
615
616 if (m_match_info.EffectiveGroupIDIsValid ())
617 return false;
618
619 if (m_match_info.GetArchitecture().IsValid())
620 return false;
621
622 if (m_match_all_users)
623 return false;
624
625 return true;
626
627}
628
629void
Greg Clayton8b82f082011-04-12 05:54:46 +0000630ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000631{
632 m_match_info.Clear();
633 m_name_match_type = eNameMatchIgnore;
634 m_match_all_users = false;
635}
Greg Clayton58be07b2011-01-07 06:08:19 +0000636
Greg Claytonc3776bf2012-02-09 06:16:32 +0000637ProcessSP
638Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639{
Greg Clayton949e8222013-01-16 17:29:04 +0000640 static uint32_t g_process_unique_id = 0;
641
Greg Claytonc3776bf2012-02-09 06:16:32 +0000642 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643 ProcessCreateInstance create_callback = NULL;
644 if (plugin_name)
645 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000646 ConstString const_plugin_name(plugin_name);
647 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000648 if (create_callback)
649 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000650 process_sp = create_callback(target, listener, crash_file_path);
651 if (process_sp)
652 {
Greg Clayton949e8222013-01-16 17:29:04 +0000653 if (process_sp->CanDebug(target, true))
654 {
655 process_sp->m_process_unique_id = ++g_process_unique_id;
656 }
657 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000658 process_sp.reset();
659 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000660 }
661 }
662 else
663 {
Greg Claytonc982c762010-07-09 20:39:50 +0000664 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000666 process_sp = create_callback(target, listener, crash_file_path);
667 if (process_sp)
668 {
Greg Clayton949e8222013-01-16 17:29:04 +0000669 if (process_sp->CanDebug(target, false))
670 {
671 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000672 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000673 }
674 else
675 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000676 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 }
678 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000679 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680}
681
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000682ConstString &
683Process::GetStaticBroadcasterClass ()
684{
685 static ConstString class_name ("lldb.process");
686 return class_name;
687}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000688
689//----------------------------------------------------------------------
690// Process constructor
691//----------------------------------------------------------------------
692Process::Process(Target &target, Listener &listener) :
Todd Fiala4ceced32014-08-29 17:35:57 +0000693 Process(target, listener, Host::GetUnixSignals ())
694{
695 // This constructor just delegates to the full Process constructor,
696 // defaulting to using the Host's UnixSignals.
697}
698
699Process::Process(Target &target, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000700 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000701 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000702 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000703 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 m_public_state (eStateUnloaded),
705 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000706 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
707 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 m_private_state_listener ("lldb.process.internal_state_listener"),
709 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000710 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000711 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000713 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000714 m_exit_status (-1),
715 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000716 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000717 m_thread_mutex (Mutex::eMutexTypeRecursive),
718 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000719 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000720 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000721 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000722 m_queue_list (this),
723 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000725 m_image_tokens (),
726 m_listener (listener),
727 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000728 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000729 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000730 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000731 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000732 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000733 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrone0be4252015-02-06 18:32:57 +0000734 m_stdio_disable(true),
Greg Clayton58be07b2011-01-07 06:08:19 +0000735 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000736 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000737 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
738 m_profile_data (),
Todd Fialaa3b89e22014-08-12 14:33:19 +0000739 m_iohandler_sync (false),
Greg Claytond495c532011-05-17 03:37:42 +0000740 m_memory_cache (*this),
741 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000742 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000743 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000744 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000745 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000746 m_currently_handling_event(false),
Greg Claytona97c4d22014-12-09 23:31:02 +0000747 m_stop_info_override_callback (NULL),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000748 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000749 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +0000750 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +0000751 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000752 m_destroy_in_process (false),
753 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000755 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000756
Greg Clayton5160ce52013-03-27 23:08:40 +0000757 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000759 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000760
Todd Fiala4ceced32014-08-29 17:35:57 +0000761 if (!m_unix_signals_sp)
762 m_unix_signals_sp.reset (new UnixSignals ());
763
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000764 SetEventName (eBroadcastBitStateChanged, "state-changed");
765 SetEventName (eBroadcastBitInterrupt, "interrupt");
766 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
767 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000768 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000769
Greg Clayton35a4cc52012-10-29 20:52:08 +0000770 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
771 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
772 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
773
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 listener.StartListeningForEvents (this,
775 eBroadcastBitStateChanged |
776 eBroadcastBitInterrupt |
777 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000778 eBroadcastBitSTDERR |
779 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780
781 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000782 eBroadcastBitStateChanged |
783 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784
785 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
786 eBroadcastInternalStateControlStop |
787 eBroadcastInternalStateControlPause |
788 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000789 // We need something valid here, even if just the default UnixSignalsSP.
790 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791}
792
793//----------------------------------------------------------------------
794// Destructor
795//----------------------------------------------------------------------
796Process::~Process()
797{
Greg Clayton5160ce52013-03-27 23:08:40 +0000798 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000800 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000802
803 // ThreadList::Clear() will try to acquire this process's mutex, so
804 // explicitly clear the thread list here to ensure that the mutex
805 // is not destroyed before the thread list.
806 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807}
808
Greg Clayton67cc0632012-08-22 17:17:09 +0000809const ProcessPropertiesSP &
810Process::GetGlobalProperties()
811{
812 static ProcessPropertiesSP g_settings_sp;
813 if (!g_settings_sp)
Greg Clayton332e8b12015-01-13 21:13:08 +0000814 g_settings_sp.reset (new ProcessProperties (NULL));
Greg Clayton67cc0632012-08-22 17:17:09 +0000815 return g_settings_sp;
816}
817
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818void
819Process::Finalize()
820{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000821 switch (GetPrivateState())
822 {
823 case eStateConnected:
824 case eStateAttaching:
825 case eStateLaunching:
826 case eStateStopped:
827 case eStateRunning:
828 case eStateStepping:
829 case eStateCrashed:
830 case eStateSuspended:
831 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +0000832 {
833 // FIXME: This will have to be a process setting:
834 bool keep_stopped = false;
835 Detach(keep_stopped);
836 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000837 else
838 Destroy();
839 break;
840
841 case eStateInvalid:
842 case eStateUnloaded:
843 case eStateDetached:
844 case eStateExited:
845 break;
846 }
847
Greg Clayton1ed54f52011-10-01 00:45:15 +0000848 // Clear our broadcaster before we proceed with destroying
849 Broadcaster::Clear();
850
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851 // Do any cleanup needed prior to being destructed... Subclasses
852 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000853
854 // We need to destroy the loader before the derived Process class gets destroyed
855 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000856 m_dynamic_checkers_ap.reset();
857 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000858 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000859 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000860 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000861 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000862 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000863 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000864 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000865 m_queue_list.Clear();
866 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000867 std::vector<Notifications> empty_notifications;
868 m_notifications.swap(empty_notifications);
869 m_image_tokens.clear();
870 m_memory_cache.Clear();
871 m_allocated_memory_cache.Clear();
872 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000873 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000874 m_next_event_action_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +0000875 m_stop_info_override_callback = NULL;
Greg Clayton35a4cc52012-10-29 20:52:08 +0000876//#ifdef LLDB_CONFIGURATION_DEBUG
877// StreamFile s(stdout, false);
878// EventSP event_sp;
879// while (m_private_state_listener.GetNextEvent(event_sp))
880// {
881// event_sp->Dump (&s);
882// s.EOL();
883// }
884//#endif
885 // We have to be very careful here as the m_private_state_listener might
886 // contain events that have ProcessSP values in them which can keep this
887 // process around forever. These events need to be cleared out.
888 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000889 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
890 m_public_run_lock.SetStopped();
891 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
892 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000893 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894}
895
896void
897Process::RegisterNotificationCallbacks (const Notifications& callbacks)
898{
899 m_notifications.push_back(callbacks);
900 if (callbacks.initialize != NULL)
901 callbacks.initialize (callbacks.baton, this);
902}
903
904bool
905Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
906{
907 std::vector<Notifications>::iterator pos, end = m_notifications.end();
908 for (pos = m_notifications.begin(); pos != end; ++pos)
909 {
910 if (pos->baton == callbacks.baton &&
911 pos->initialize == callbacks.initialize &&
912 pos->process_state_changed == callbacks.process_state_changed)
913 {
914 m_notifications.erase(pos);
915 return true;
916 }
917 }
918 return false;
919}
920
921void
922Process::SynchronouslyNotifyStateChanged (StateType state)
923{
924 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
925 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
926 {
927 if (notification_pos->process_state_changed)
928 notification_pos->process_state_changed (notification_pos->baton, this, state);
929 }
930}
931
932// FIXME: We need to do some work on events before the general Listener sees them.
933// For instance if we are continuing from a breakpoint, we need to ensure that we do
934// the little "insert real insn, step & stop" trick. But we can't do that when the
935// event is delivered by the broadcaster - since that is done on the thread that is
936// waiting for new events, so if we needed more than one event for our handling, we would
937// stall. So instead we do it when we fetch the event off of the queue.
938//
939
940StateType
941Process::GetNextEvent (EventSP &event_sp)
942{
943 StateType state = eStateInvalid;
944
945 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
946 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
947
948 return state;
949}
950
Todd Fialaa3b89e22014-08-12 14:33:19 +0000951bool
952Process::SyncIOHandler (uint64_t timeout_msec)
953{
954 bool timed_out = false;
955
956 // don't sync (potentially context switch) in case where there is no process IO
957 if (m_process_input_reader)
958 {
959 TimeValue timeout = TimeValue::Now();
960 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
961
962 m_iohandler_sync.WaitForValueEqualTo(true, &timeout, &timed_out);
963
964 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
965 if(log)
966 {
967 if(timed_out)
968 log->Printf ("Process::%s pid %" PRIu64 " (timeout=%" PRIu64 "ms): FAIL", __FUNCTION__, GetID (), timeout_msec);
969 else
970 log->Printf ("Process::%s pid %" PRIu64 ": SUCCESS", __FUNCTION__, GetID ());
971 }
972
Shawn Best1ded74a2014-10-08 01:50:37 +0000973 // reset sync one-shot so it will be ready for next launch
Todd Fialaa3b89e22014-08-12 14:33:19 +0000974 m_iohandler_sync.SetValue(false, eBroadcastNever);
975 }
976
977 return !timed_out;
978}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979
980StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000981Process::WaitForProcessToStop (const TimeValue *timeout,
982 EventSP *event_sp_ptr,
983 bool wait_always,
984 Listener *hijack_listener,
985 Stream *stream)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000986{
Jim Ingham4b536182011-08-09 02:12:22 +0000987 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
988 // We have to actually check each event, and in the case of a stopped event check the restarted flag
989 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +0000990 if (event_sp_ptr)
991 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +0000992 StateType state = GetState();
993 // If we are exited or detached, we won't ever get back to any
994 // other valid state...
995 if (state == eStateDetached || state == eStateExited)
996 return state;
997
Daniel Malea9e9919f2013-10-09 16:56:28 +0000998 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
999 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001000 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
1001 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001002
1003 if (!wait_always &&
1004 StateIsStoppedState(state, true) &&
1005 StateIsStoppedState(GetPrivateState(), true)) {
1006 if (log)
1007 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1008 __FUNCTION__);
1009 return state;
1010 }
1011
Jim Ingham4b536182011-08-09 02:12:22 +00001012 while (state != eStateInvalid)
1013 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001014 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001015 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001016 if (event_sp_ptr && event_sp)
1017 *event_sp_ptr = event_sp;
1018
Greg Claytondc6224e2014-10-21 01:00:42 +00001019 bool pop_process_io_handler = hijack_listener != NULL;
1020 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1021
Jim Ingham4b536182011-08-09 02:12:22 +00001022 switch (state)
1023 {
1024 case eStateCrashed:
1025 case eStateDetached:
1026 case eStateExited:
1027 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001028 // We need to toggle the run lock as this won't get done in
1029 // SetPublicState() if the process is hijacked.
1030 if (hijack_listener)
1031 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001032 return state;
1033 case eStateStopped:
1034 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1035 continue;
1036 else
Greg Clayton44d93782014-01-27 23:43:24 +00001037 {
1038 // We need to toggle the run lock as this won't get done in
1039 // SetPublicState() if the process is hijacked.
1040 if (hijack_listener)
1041 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001042 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001043 }
Jim Ingham4b536182011-08-09 02:12:22 +00001044 default:
1045 continue;
1046 }
1047 }
1048 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049}
1050
Greg Claytondc6224e2014-10-21 01:00:42 +00001051bool
1052Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1053 Stream *stream,
1054 bool &pop_process_io_handler)
1055{
1056 const bool handle_pop = pop_process_io_handler == true;
1057
1058 pop_process_io_handler = false;
1059 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1060
1061 if (!process_sp)
1062 return false;
1063
1064 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1065 if (event_state == eStateInvalid)
1066 return false;
1067
1068 switch (event_state)
1069 {
1070 case eStateInvalid:
1071 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001072 case eStateAttaching:
1073 case eStateLaunching:
1074 case eStateStepping:
1075 case eStateDetached:
1076 {
1077 if (stream)
1078 stream->Printf ("Process %" PRIu64 " %s\n",
1079 process_sp->GetID(),
1080 StateAsCString (event_state));
1081
1082 if (event_state == eStateDetached)
1083 pop_process_io_handler = true;
1084 }
1085 break;
1086
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001087 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001088 case eStateRunning:
1089 // Don't be chatty when we run...
1090 break;
1091
1092 case eStateExited:
1093 if (stream)
1094 process_sp->GetStatus(*stream);
1095 pop_process_io_handler = true;
1096 break;
1097
1098 case eStateStopped:
1099 case eStateCrashed:
1100 case eStateSuspended:
1101 // Make sure the program hasn't been auto-restarted:
1102 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1103 {
1104 if (stream)
1105 {
1106 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1107 if (num_reasons > 0)
1108 {
1109 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1110 if (num_reasons == 1)
1111 {
1112 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1113 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1114 process_sp->GetID(),
1115 reason ? reason : "<UNKNOWN REASON>");
1116 }
1117 else
1118 {
1119 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1120 process_sp->GetID());
1121
1122
1123 for (size_t i = 0; i < num_reasons; i++)
1124 {
1125 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1126 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1127 }
1128 }
1129 }
1130 }
1131 }
1132 else
1133 {
1134 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1135 {
1136 ThreadList &thread_list = process_sp->GetThreadList();
1137 Mutex::Locker locker (thread_list.GetMutex());
1138
1139 ThreadSP curr_thread (thread_list.GetSelectedThread());
1140 ThreadSP thread;
1141 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1142 if (curr_thread)
1143 curr_thread_stop_reason = curr_thread->GetStopReason();
1144 if (!curr_thread ||
1145 !curr_thread->IsValid() ||
1146 curr_thread_stop_reason == eStopReasonInvalid ||
1147 curr_thread_stop_reason == eStopReasonNone)
1148 {
1149 // Prefer a thread that has just completed its plan over another thread as current thread.
1150 ThreadSP plan_thread;
1151 ThreadSP other_thread;
1152 const size_t num_threads = thread_list.GetSize();
1153 size_t i;
1154 for (i = 0; i < num_threads; ++i)
1155 {
1156 thread = thread_list.GetThreadAtIndex(i);
1157 StopReason thread_stop_reason = thread->GetStopReason();
1158 switch (thread_stop_reason)
1159 {
1160 case eStopReasonInvalid:
1161 case eStopReasonNone:
1162 break;
1163
1164 case eStopReasonTrace:
1165 case eStopReasonBreakpoint:
1166 case eStopReasonWatchpoint:
1167 case eStopReasonSignal:
1168 case eStopReasonException:
1169 case eStopReasonExec:
1170 case eStopReasonThreadExiting:
1171 case eStopReasonInstrumentation:
1172 if (!other_thread)
1173 other_thread = thread;
1174 break;
1175 case eStopReasonPlanComplete:
1176 if (!plan_thread)
1177 plan_thread = thread;
1178 break;
1179 }
1180 }
1181 if (plan_thread)
1182 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1183 else if (other_thread)
1184 thread_list.SetSelectedThreadByID (other_thread->GetID());
1185 else
1186 {
1187 if (curr_thread && curr_thread->IsValid())
1188 thread = curr_thread;
1189 else
1190 thread = thread_list.GetThreadAtIndex(0);
1191
1192 if (thread)
1193 thread_list.SetSelectedThreadByID (thread->GetID());
1194 }
1195 }
1196 }
1197 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1198 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1199 // have a hard time restarting the process.
1200 if (stream)
1201 {
1202 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1203 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1204 {
1205 const bool only_threads_with_stop_reason = true;
1206 const uint32_t start_frame = 0;
1207 const uint32_t num_frames = 1;
1208 const uint32_t num_frames_with_source = 1;
1209 process_sp->GetStatus(*stream);
1210 process_sp->GetThreadStatus (*stream,
1211 only_threads_with_stop_reason,
1212 start_frame,
1213 num_frames,
1214 num_frames_with_source);
1215 }
1216 else
1217 {
1218 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1219 if (target_idx != UINT32_MAX)
1220 stream->Printf ("Target %d: (", target_idx);
1221 else
1222 stream->Printf ("Target <unknown index>: (");
1223 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1224 stream->Printf (") stopped.\n");
1225 }
1226 }
1227
1228 // Pop the process IO handler
1229 pop_process_io_handler = true;
1230 }
1231 break;
1232 }
1233
1234 if (handle_pop && pop_process_io_handler)
1235 process_sp->PopProcessIOHandler();
1236
1237 return true;
1238}
1239
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001240
1241StateType
1242Process::WaitForState
1243(
1244 const TimeValue *timeout,
Greg Clayton44d93782014-01-27 23:43:24 +00001245 const StateType *match_states,
1246 const uint32_t num_match_states
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001247)
1248{
1249 EventSP event_sp;
1250 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001251 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001252 while (state != eStateInvalid)
1253 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001254 // If we are exited or detached, we won't ever get back to any
1255 // other valid state...
1256 if (state == eStateDetached || state == eStateExited)
1257 return state;
1258
Greg Clayton44d93782014-01-27 23:43:24 +00001259 state = WaitForStateChangedEvents (timeout, event_sp, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260
1261 for (i=0; i<num_match_states; ++i)
1262 {
1263 if (match_states[i] == state)
1264 return state;
1265 }
1266 }
1267 return state;
1268}
1269
Jim Ingham30f9b212010-10-11 23:53:14 +00001270bool
1271Process::HijackProcessEvents (Listener *listener)
1272{
1273 if (listener != NULL)
1274 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001275 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001276 }
1277 else
1278 return false;
1279}
1280
1281void
1282Process::RestoreProcessEvents ()
1283{
1284 RestoreBroadcaster();
1285}
1286
Jim Ingham0f16e732011-02-08 05:20:59 +00001287bool
1288Process::HijackPrivateProcessEvents (Listener *listener)
1289{
1290 if (listener != NULL)
1291 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001292 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001293 }
1294 else
1295 return false;
1296}
1297
1298void
1299Process::RestorePrivateProcessEvents ()
1300{
1301 m_private_state_broadcaster.RestoreBroadcaster();
1302}
1303
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001305Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001306{
Greg Clayton5160ce52013-03-27 23:08:40 +00001307 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308
1309 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001310 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1311 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312
Greg Clayton44d93782014-01-27 23:43:24 +00001313 Listener *listener = hijack_listener;
1314 if (listener == NULL)
1315 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001316
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001317 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001318 if (listener->WaitForEventForBroadcasterWithType (timeout,
1319 this,
1320 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1321 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001322 {
1323 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1324 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1325 else if (log)
1326 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1327 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328
1329 if (log)
1330 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001331 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332 StateAsCString(state));
1333 return state;
1334}
1335
1336Event *
1337Process::PeekAtStateChangedEvents ()
1338{
Greg Clayton5160ce52013-03-27 23:08:40 +00001339 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001340
1341 if (log)
1342 log->Printf ("Process::%s...", __FUNCTION__);
1343
1344 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001345 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1346 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001347 if (log)
1348 {
1349 if (event_ptr)
1350 {
1351 log->Printf ("Process::%s (event_ptr) => %s",
1352 __FUNCTION__,
1353 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1354 }
1355 else
1356 {
1357 log->Printf ("Process::%s no events found",
1358 __FUNCTION__);
1359 }
1360 }
1361 return event_ptr;
1362}
1363
1364StateType
1365Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1366{
Greg Clayton5160ce52013-03-27 23:08:40 +00001367 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001368
1369 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001370 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1371 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372
1373 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001374 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1375 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001376 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001377 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001378 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1379 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380
1381 // This is a bit of a hack, but when we wait here we could very well return
1382 // to the command-line, and that could disable the log, which would render the
1383 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001384 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001385 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1386 __FUNCTION__, static_cast<const void *>(timeout),
1387 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388 return state;
1389}
1390
1391bool
1392Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1393{
Greg Clayton5160ce52013-03-27 23:08:40 +00001394 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395
1396 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001397 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1398 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001399
1400 if (control_only)
1401 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1402 else
1403 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1404}
1405
1406bool
1407Process::IsRunning () const
1408{
1409 return StateIsRunningState (m_public_state.GetValue());
1410}
1411
1412int
1413Process::GetExitStatus ()
1414{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001415 Mutex::Locker locker (m_exit_status_mutex);
1416
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001417 if (m_public_state.GetValue() == eStateExited)
1418 return m_exit_status;
1419 return -1;
1420}
1421
Greg Clayton85851dd2010-12-04 00:10:17 +00001422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423const char *
1424Process::GetExitDescription ()
1425{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001426 Mutex::Locker locker (m_exit_status_mutex);
1427
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001428 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1429 return m_exit_string.c_str();
1430 return NULL;
1431}
1432
Greg Clayton6779606a2011-01-22 23:43:18 +00001433bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434Process::SetExitStatus (int status, const char *cstr)
1435{
Greg Clayton5160ce52013-03-27 23:08:40 +00001436 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001437 if (log)
1438 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1439 status, status,
1440 cstr ? "\"" : "",
1441 cstr ? cstr : "NULL",
1442 cstr ? "\"" : "");
1443
Greg Clayton6779606a2011-01-22 23:43:18 +00001444 // We were already in the exited state
1445 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001446 {
Greg Clayton385d6032011-01-26 23:47:29 +00001447 if (log)
1448 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001449 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001450 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001451
Todd Fiala7b0917a2014-09-15 20:07:33 +00001452 // use a mutex to protect the status and string during updating
1453 {
1454 Mutex::Locker locker (m_exit_status_mutex);
1455
1456 m_exit_status = status;
1457 if (cstr)
1458 m_exit_string = cstr;
1459 else
1460 m_exit_string.clear();
1461 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001462
Greg Clayton6779606a2011-01-22 23:43:18 +00001463 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001464
Greg Clayton6779606a2011-01-22 23:43:18 +00001465 SetPrivateState (eStateExited);
1466 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467}
1468
1469// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001470// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471// found in the global target list (we want to be completely sure that the
1472// lldb_private::Process doesn't go away before we can deliver the signal.
1473bool
Greg Claytone4e45922011-11-16 05:37:56 +00001474Process::SetProcessExitStatus (void *callback_baton,
1475 lldb::pid_t pid,
1476 bool exited,
1477 int signo, // Zero for no signal
1478 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001479)
1480{
Greg Clayton5160ce52013-03-27 23:08:40 +00001481 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001482 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001483 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001484 callback_baton,
1485 pid,
1486 exited,
1487 signo,
1488 exit_status);
1489
1490 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001491 {
Greg Clayton66111032010-06-23 01:19:29 +00001492 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493 if (target_sp)
1494 {
1495 ProcessSP process_sp (target_sp->GetProcessSP());
1496 if (process_sp)
1497 {
1498 const char *signal_cstr = NULL;
1499 if (signo)
1500 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1501
1502 process_sp->SetExitStatus (exit_status, signal_cstr);
1503 }
1504 }
1505 return true;
1506 }
1507 return false;
1508}
1509
1510
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001511void
1512Process::UpdateThreadListIfNeeded ()
1513{
1514 const uint32_t stop_id = GetStopID();
1515 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1516 {
Greg Clayton2637f822011-11-17 01:23:07 +00001517 const StateType state = GetPrivateState();
1518 if (StateIsStoppedState (state, true))
1519 {
1520 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001521 // m_thread_list does have its own mutex, but we need to
1522 // hold onto the mutex between the call to UpdateThreadList(...)
1523 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001524 ThreadList &old_thread_list = m_thread_list;
1525 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001526 ThreadList new_thread_list(this);
1527 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001528 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001529 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001530 {
Jim Ingham09437922013-03-01 20:04:25 +00001531 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1532 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1533 // shutting us down, causing a deadlock.
1534 if (!m_destroy_in_process)
1535 {
1536 OperatingSystem *os = GetOperatingSystem ();
1537 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001538 {
1539 // Clear any old backing threads where memory threads might have been
1540 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001541 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001542 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001543 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001544
1545 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001546 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1547 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1548 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 +00001549 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001550 else
1551 {
1552 // No OS plug-in, the new thread list is the same as the real thread list
1553 new_thread_list = real_thread_list;
1554 }
Jim Ingham09437922013-03-01 20:04:25 +00001555 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001556
1557 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001558 m_thread_list.Update (new_thread_list);
1559 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001560
Jason Molenda4ff13262013-11-20 00:31:38 +00001561 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1562 {
1563 // Clear any extended threads that we may have accumulated previously
1564 m_extended_thread_list.Clear();
1565 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001566
1567 m_queue_list.Clear();
1568 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001569 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001570 }
Greg Clayton2637f822011-11-17 01:23:07 +00001571 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001572 }
1573}
1574
Jason Molenda5e8dce42013-12-13 00:29:16 +00001575void
1576Process::UpdateQueueListIfNeeded ()
1577{
1578 if (m_system_runtime_ap.get())
1579 {
1580 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1581 {
1582 const StateType state = GetPrivateState();
1583 if (StateIsStoppedState (state, true))
1584 {
1585 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1586 m_queue_list_stop_id = GetLastNaturalStopID();
1587 }
1588 }
1589 }
1590}
1591
Greg Claytona4d87472013-01-18 23:41:08 +00001592ThreadSP
1593Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1594{
1595 OperatingSystem *os = GetOperatingSystem ();
1596 if (os)
1597 return os->CreateThread(tid, context);
1598 return ThreadSP();
1599}
1600
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001601uint32_t
1602Process::GetNextThreadIndexID (uint64_t thread_id)
1603{
1604 return AssignIndexIDToThread(thread_id);
1605}
1606
1607bool
1608Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1609{
1610 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1611 if (iterator == m_thread_id_to_index_id_map.end())
1612 {
1613 return false;
1614 }
1615 else
1616 {
1617 return true;
1618 }
1619}
1620
1621uint32_t
1622Process::AssignIndexIDToThread(uint64_t thread_id)
1623{
1624 uint32_t result = 0;
1625 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1626 if (iterator == m_thread_id_to_index_id_map.end())
1627 {
1628 result = ++m_thread_index_id;
1629 m_thread_id_to_index_id_map[thread_id] = result;
1630 }
1631 else
1632 {
1633 result = iterator->second;
1634 }
1635
1636 return result;
1637}
1638
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001639StateType
1640Process::GetState()
1641{
1642 // If any other threads access this we will need a mutex for it
1643 return m_public_state.GetValue ();
1644}
1645
Greg Claytondc6224e2014-10-21 01:00:42 +00001646bool
1647Process::StateChangedIsExternallyHijacked()
1648{
1649 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1650 {
1651 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1652 return true;
1653 }
1654 return false;
1655}
1656
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001657void
Jim Ingham221d51c2013-05-08 00:35:16 +00001658Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001659{
Greg Clayton5160ce52013-03-27 23:08:40 +00001660 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001662 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001663 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001665
1666 // On the transition from Run to Stopped, we unlock the writer end of the
1667 // run lock. The lock gets locked in Resume, which is the public API
1668 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001669 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001670 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001671 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001672 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001673 if (log)
1674 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001675 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001676 }
1677 else
1678 {
1679 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1680 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001681 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001682 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001683 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001684 {
1685 if (log)
1686 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001687 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001688 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001689 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001690 }
1691 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001692}
1693
Jim Ingham3b8285d2012-04-19 01:40:33 +00001694Error
1695Process::Resume ()
1696{
Greg Clayton5160ce52013-03-27 23:08:40 +00001697 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001698 if (log)
1699 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001700 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001701 {
1702 Error error("Resume request failed - process still running.");
1703 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001704 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001705 return error;
1706 }
1707 return PrivateResume();
1708}
1709
Greg Claytondc6224e2014-10-21 01:00:42 +00001710Error
1711Process::ResumeSynchronous (Stream *stream)
1712{
1713 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1714 if (log)
1715 log->Printf("Process::ResumeSynchronous -- locking run lock");
1716 if (!m_public_run_lock.TrySetRunning())
1717 {
1718 Error error("Resume request failed - process still running.");
1719 if (log)
1720 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1721 return error;
1722 }
1723
1724 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1725 HijackProcessEvents(listener_sp.get());
1726
1727 Error error = PrivateResume();
1728
1729 StateType state = WaitForProcessToStop (NULL, NULL, true, listener_sp.get(), stream);
1730
1731 // Undo the hijacking of process events...
1732 RestoreProcessEvents();
1733
1734 if (error.Success() && !StateIsStoppedState(state, false))
1735 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1736
1737 return error;
1738}
1739
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001740StateType
1741Process::GetPrivateState ()
1742{
1743 return m_private_state.GetValue();
1744}
1745
1746void
1747Process::SetPrivateState (StateType new_state)
1748{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001749 if (m_finalize_called)
1750 return;
1751
Greg Clayton5160ce52013-03-27 23:08:40 +00001752 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001753 bool state_changed = false;
1754
1755 if (log)
1756 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1757
Andrew Kaylor29d65742013-05-10 17:19:04 +00001758 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759 Mutex::Locker locker(m_private_state.GetMutex());
1760
1761 const StateType old_state = m_private_state.GetValueNoLock ();
1762 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001763
Greg Claytonaa49c832013-05-03 22:25:56 +00001764 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1765 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1766 if (old_state_is_stopped != new_state_is_stopped)
1767 {
1768 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001769 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001770 else
Ed Maste64fad602013-07-29 20:58:06 +00001771 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001772 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001773
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001774 if (state_changed)
1775 {
1776 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001777 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001778 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001779 // Note, this currently assumes that all threads in the list
1780 // stop when the process stops. In the future we will want to
1781 // support a debugging model where some threads continue to run
1782 // while others are stopped. When that happens we will either need
1783 // a way for the thread list to identify which threads are stopping
1784 // or create a special thread list containing only threads which
1785 // actually stopped.
1786 //
1787 // The process plugin is responsible for managing the actual
1788 // behavior of the threads and should have stopped any threads
1789 // that are going to stop before we get here.
1790 m_thread_list.DidStop();
1791
Jim Ingham4b536182011-08-09 02:12:22 +00001792 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001793 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001795 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001796 }
1797 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001798 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1799 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1800 else
1801 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001802 }
1803 else
1804 {
1805 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001806 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001807 }
1808}
1809
Jim Ingham0faa43f2011-11-08 03:00:11 +00001810void
1811Process::SetRunningUserExpression (bool on)
1812{
1813 m_mod_id.SetRunningUserExpression (on);
1814}
1815
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816addr_t
1817Process::GetImageInfoAddress()
1818{
1819 return LLDB_INVALID_ADDRESS;
1820}
1821
Greg Clayton8f343b02010-11-04 01:54:29 +00001822//----------------------------------------------------------------------
1823// LoadImage
1824//
1825// This function provides a default implementation that works for most
1826// unix variants. Any Process subclasses that need to do shared library
1827// loading differently should override LoadImage and UnloadImage and
1828// do what is needed.
1829//----------------------------------------------------------------------
1830uint32_t
1831Process::LoadImage (const FileSpec &image_spec, Error &error)
1832{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001833 char path[PATH_MAX];
1834 image_spec.GetPath(path, sizeof(path));
1835
Greg Clayton8f343b02010-11-04 01:54:29 +00001836 DynamicLoader *loader = GetDynamicLoader();
1837 if (loader)
1838 {
1839 error = loader->CanLoadImage();
1840 if (error.Fail())
1841 return LLDB_INVALID_IMAGE_TOKEN;
1842 }
1843
1844 if (error.Success())
1845 {
1846 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001847
1848 if (thread_sp)
1849 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001850 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001851
1852 if (frame_sp)
1853 {
1854 ExecutionContext exe_ctx;
1855 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001856 EvaluateExpressionOptions expr_options;
1857 expr_options.SetUnwindOnError(true);
1858 expr_options.SetIgnoreBreakpoints(true);
1859 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Jim Ingham4ac04432014-07-19 01:09:16 +00001860 expr_options.SetResultIsInternal(true);
1861
Greg Clayton8f343b02010-11-04 01:54:29 +00001862 StreamString expr;
Jim Ingham6971b862014-07-19 00:37:06 +00001863 expr.Printf(R"(
1864 struct __lldb_dlopen_result { void *image_ptr; const char *error_str; } the_result;
1865 the_result.image_ptr = dlopen ("%s", 2);
1866 if (the_result.image_ptr == (void *) 0x0)
1867 {
1868 the_result.error_str = dlerror();
1869 }
1870 else
1871 {
1872 the_result.error_str = (const char *) 0x0;
1873 }
1874 the_result;
1875 )",
1876 path);
1877 const char *prefix = R"(
1878 extern "C" void* dlopen (const char *path, int mode);
1879 extern "C" const char *dlerror (void);
1880 )";
Jim Inghamf48169b2010-11-30 02:22:11 +00001881 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001882 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001883 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001884 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001885 expr.GetData(),
1886 prefix,
1887 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001888 expr_error);
1889 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001890 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001891 error = result_valobj_sp->GetError();
1892 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001893 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001894 Scalar scalar;
Jim Ingham6971b862014-07-19 00:37:06 +00001895 ValueObjectSP image_ptr_sp = result_valobj_sp->GetChildAtIndex(0, true);
1896 if (image_ptr_sp && image_ptr_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001897 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001898 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1899 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1900 {
1901 uint32_t image_token = m_image_tokens.size();
1902 m_image_tokens.push_back (image_ptr);
1903 return image_token;
1904 }
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001905 else if (image_ptr == 0)
1906 {
Jim Ingham6971b862014-07-19 00:37:06 +00001907 ValueObjectSP error_str_sp = result_valobj_sp->GetChildAtIndex(1, true);
1908 if (error_str_sp)
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001909 {
Jim Ingham6971b862014-07-19 00:37:06 +00001910 if (error_str_sp->IsCStringContainer(true))
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001911 {
Enrico Granata2206b482014-10-30 18:27:31 +00001912 DataBufferSP buffer_sp(new DataBufferHeap(10240,0));
1913 size_t num_chars = error_str_sp->ReadPointedString (buffer_sp, error, 10240);
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001914 if (error.Success() && num_chars > 0)
1915 {
1916 error.Clear();
Enrico Granata2206b482014-10-30 18:27:31 +00001917 error.SetErrorStringWithFormat("dlopen error: %s", buffer_sp->GetBytes());
1918 }
1919 else
1920 {
1921 error.Clear();
1922 error.SetErrorStringWithFormat("dlopen failed for unknown reasons.");
Jim Ingham3ac7cf32014-07-17 18:55:25 +00001923 }
1924 }
1925 }
1926 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001927 }
1928 }
1929 }
Jim Ingham6c9ed912014-04-03 01:26:14 +00001930 else
1931 error = expr_error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001932 }
1933 }
1934 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001935 if (!error.AsCString())
1936 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001937 return LLDB_INVALID_IMAGE_TOKEN;
1938}
1939
1940//----------------------------------------------------------------------
1941// UnloadImage
1942//
1943// This function provides a default implementation that works for most
1944// unix variants. Any Process subclasses that need to do shared library
1945// loading differently should override LoadImage and UnloadImage and
1946// do what is needed.
1947//----------------------------------------------------------------------
1948Error
1949Process::UnloadImage (uint32_t image_token)
1950{
1951 Error error;
1952 if (image_token < m_image_tokens.size())
1953 {
1954 const addr_t image_addr = m_image_tokens[image_token];
1955 if (image_addr == LLDB_INVALID_ADDRESS)
1956 {
1957 error.SetErrorString("image already unloaded");
1958 }
1959 else
1960 {
1961 DynamicLoader *loader = GetDynamicLoader();
1962 if (loader)
1963 error = loader->CanLoadImage();
1964
1965 if (error.Success())
1966 {
1967 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001968
1969 if (thread_sp)
1970 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001971 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001972
1973 if (frame_sp)
1974 {
1975 ExecutionContext exe_ctx;
1976 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001977 EvaluateExpressionOptions expr_options;
1978 expr_options.SetUnwindOnError(true);
1979 expr_options.SetIgnoreBreakpoints(true);
1980 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001981 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001982 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001983 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001984 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001985 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001986 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001987 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001988 expr.GetData(),
1989 prefix,
1990 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001991 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001992 if (result_valobj_sp->GetError().Success())
1993 {
1994 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001995 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001996 {
1997 if (scalar.UInt(1))
1998 {
1999 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
2000 }
2001 else
2002 {
2003 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
2004 }
2005 }
2006 }
2007 else
2008 {
2009 error = result_valobj_sp->GetError();
2010 }
2011 }
2012 }
2013 }
2014 }
2015 }
2016 else
2017 {
2018 error.SetErrorString("invalid image token");
2019 }
2020 return error;
2021}
2022
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002023const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024Process::GetABI()
2025{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002026 if (!m_abi_sp)
2027 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2028 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029}
2030
Jim Ingham22777012010-09-23 02:01:19 +00002031LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002032Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002033{
2034 LanguageRuntimeCollection::iterator pos;
2035 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002036 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002037 {
Jim Inghamab175242012-03-10 00:22:19 +00002038 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002039
Jim Inghamab175242012-03-10 00:22:19 +00002040 m_language_runtimes[language] = runtime_sp;
2041 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002042 }
2043 else
2044 return (*pos).second.get();
2045}
2046
2047CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002048Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002049{
Jim Inghamab175242012-03-10 00:22:19 +00002050 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002051 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2052 return static_cast<CPPLanguageRuntime *> (runtime);
2053 return NULL;
2054}
2055
2056ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002057Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002058{
Jim Inghamab175242012-03-10 00:22:19 +00002059 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002060 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2061 return static_cast<ObjCLanguageRuntime *> (runtime);
2062 return NULL;
2063}
2064
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002065bool
2066Process::IsPossibleDynamicValue (ValueObject& in_value)
2067{
2068 if (in_value.IsDynamic())
2069 return false;
2070 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2071
2072 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2073 {
2074 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2075 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2076 }
2077
2078 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2079 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2080 return true;
2081
2082 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2083 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2084}
2085
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002086BreakpointSiteList &
2087Process::GetBreakpointSiteList()
2088{
2089 return m_breakpoint_site_list;
2090}
2091
2092const BreakpointSiteList &
2093Process::GetBreakpointSiteList() const
2094{
2095 return m_breakpoint_site_list;
2096}
2097
2098
2099void
2100Process::DisableAllBreakpointSites ()
2101{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002102 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2103// bp_site->SetEnabled(true);
2104 DisableBreakpointSite(bp_site);
2105 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002106}
2107
2108Error
2109Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2110{
2111 Error error (DisableBreakpointSiteByID (break_id));
2112
2113 if (error.Success())
2114 m_breakpoint_site_list.Remove(break_id);
2115
2116 return error;
2117}
2118
2119Error
2120Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2121{
2122 Error error;
2123 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2124 if (bp_site_sp)
2125 {
2126 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002127 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128 }
2129 else
2130 {
Daniel Malead01b2952012-11-29 21:49:15 +00002131 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002132 }
2133
2134 return error;
2135}
2136
2137Error
2138Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2139{
2140 Error error;
2141 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2142 if (bp_site_sp)
2143 {
2144 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002145 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146 }
2147 else
2148 {
Daniel Malead01b2952012-11-29 21:49:15 +00002149 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002150 }
2151 return error;
2152}
2153
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002154lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002155Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002157 addr_t load_addr = LLDB_INVALID_ADDRESS;
2158
2159 bool show_error = true;
2160 switch (GetState())
2161 {
2162 case eStateInvalid:
2163 case eStateUnloaded:
2164 case eStateConnected:
2165 case eStateAttaching:
2166 case eStateLaunching:
2167 case eStateDetached:
2168 case eStateExited:
2169 show_error = false;
2170 break;
2171
2172 case eStateStopped:
2173 case eStateRunning:
2174 case eStateStepping:
2175 case eStateCrashed:
2176 case eStateSuspended:
2177 show_error = IsAlive();
2178 break;
2179 }
2180
2181 // Reset the IsIndirect flag here, in case the location changes from
2182 // pointing to a indirect symbol to a regular symbol.
2183 owner->SetIsIndirect (false);
2184
2185 if (owner->ShouldResolveIndirectFunctions())
2186 {
2187 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2188 if (symbol && symbol->IsIndirect())
2189 {
2190 Error error;
2191 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2192 if (!error.Success() && show_error)
2193 {
Greg Clayton44d93782014-01-27 23:43:24 +00002194 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2195 symbol->GetAddress().GetLoadAddress(&m_target),
2196 owner->GetBreakpoint().GetID(),
2197 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002198 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002199 return LLDB_INVALID_BREAK_ID;
2200 }
2201 Address resolved_address(load_addr);
2202 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2203 owner->SetIsIndirect(true);
2204 }
2205 else
2206 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2207 }
2208 else
2209 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2210
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211 if (load_addr != LLDB_INVALID_ADDRESS)
2212 {
2213 BreakpointSiteSP bp_site_sp;
2214
2215 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2216 // create a new breakpoint site and add it.
2217
2218 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2219
2220 if (bp_site_sp)
2221 {
2222 bp_site_sp->AddOwner (owner);
2223 owner->SetBreakpointSite (bp_site_sp);
2224 return bp_site_sp->GetID();
2225 }
2226 else
2227 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002228 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002229 if (bp_site_sp)
2230 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002231 Error error = EnableBreakpointSite (bp_site_sp.get());
2232 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233 {
2234 owner->SetBreakpointSite (bp_site_sp);
2235 return m_breakpoint_site_list.Add (bp_site_sp);
2236 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002237 else
2238 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002239 if (show_error)
2240 {
2241 // Report error for setting breakpoint...
Greg Clayton44d93782014-01-27 23:43:24 +00002242 m_target.GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2243 load_addr,
2244 owner->GetBreakpoint().GetID(),
2245 owner->GetID(),
Sylvestre Ledruf6102892014-08-11 18:06:28 +00002246 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002247 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002248 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 }
2250 }
2251 }
2252 // We failed to enable the breakpoint
2253 return LLDB_INVALID_BREAK_ID;
2254
2255}
2256
2257void
2258Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2259{
2260 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2261 if (num_owners == 0)
2262 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002263 // Don't try to disable the site if we don't have a live process anymore.
2264 if (IsAlive())
2265 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2267 }
2268}
2269
2270
2271size_t
2272Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2273{
2274 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002275 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276
Jim Ingham20c77192011-06-29 19:42:28 +00002277 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002279 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2280 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002282 addr_t intersect_addr;
2283 size_t intersect_size;
2284 size_t opcode_offset;
2285 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002286 {
2287 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2288 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002289 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002290 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002291 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002294 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002295 }
2296 return bytes_removed;
2297}
2298
2299
Greg Claytonded470d2011-03-19 01:12:21 +00002300
2301size_t
2302Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2303{
2304 PlatformSP platform_sp (m_target.GetPlatform());
2305 if (platform_sp)
2306 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2307 return 0;
2308}
2309
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310Error
2311Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2312{
2313 Error error;
2314 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002315 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002316 const addr_t bp_addr = bp_site->GetLoadAddress();
2317 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002318 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002319 if (bp_site->IsEnabled())
2320 {
2321 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002322 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 +00002323 return error;
2324 }
2325
2326 if (bp_addr == LLDB_INVALID_ADDRESS)
2327 {
2328 error.SetErrorString("BreakpointSite contains an invalid load address.");
2329 return error;
2330 }
2331 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2332 // trap for the breakpoint site
2333 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2334
2335 if (bp_opcode_size == 0)
2336 {
Daniel Malead01b2952012-11-29 21:49:15 +00002337 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 }
2339 else
2340 {
2341 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2342
2343 if (bp_opcode_bytes == NULL)
2344 {
2345 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2346 return error;
2347 }
2348
2349 // Save the original opcode by reading it
2350 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2351 {
2352 // Write a software breakpoint in place of the original opcode
2353 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2354 {
2355 uint8_t verify_bp_opcode_bytes[64];
2356 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2357 {
2358 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2359 {
2360 bp_site->SetEnabled(true);
2361 bp_site->SetType (BreakpointSite::eSoftware);
2362 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002363 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002364 bp_site->GetID(),
2365 (uint64_t)bp_addr);
2366 }
2367 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002368 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002369 }
2370 else
2371 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2372 }
2373 else
2374 error.SetErrorString("Unable to write breakpoint trap to memory.");
2375 }
2376 else
2377 error.SetErrorString("Unable to read memory at breakpoint address.");
2378 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002379 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002380 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 bp_site->GetID(),
2382 (uint64_t)bp_addr,
2383 error.AsCString());
2384 return error;
2385}
2386
2387Error
2388Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2389{
2390 Error error;
2391 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002392 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393 addr_t bp_addr = bp_site->GetLoadAddress();
2394 lldb::user_id_t breakID = bp_site->GetID();
2395 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002396 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002397
2398 if (bp_site->IsHardware())
2399 {
2400 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2401 }
2402 else if (bp_site->IsEnabled())
2403 {
2404 const size_t break_op_size = bp_site->GetByteSize();
2405 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2406 if (break_op_size > 0)
2407 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002408 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002409 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002410 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 bool break_op_found = false;
2412
2413 // Read the breakpoint opcode
2414 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2415 {
2416 bool verify = false;
2417 // Make sure we have the a breakpoint opcode exists at this address
2418 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2419 {
2420 break_op_found = true;
2421 // We found a valid breakpoint opcode at this address, now restore
2422 // the saved opcode.
2423 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2424 {
2425 verify = true;
2426 }
2427 else
2428 error.SetErrorString("Memory write failed when restoring original opcode.");
2429 }
2430 else
2431 {
2432 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2433 // Set verify to true and so we can check if the original opcode has already been restored
2434 verify = true;
2435 }
2436
2437 if (verify)
2438 {
Greg Claytonc982c762010-07-09 20:39:50 +00002439 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002440 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002441 // Verify that our original opcode made it back to the inferior
2442 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2443 {
2444 // compare the memory we just read with the original opcode
2445 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2446 {
2447 // SUCCESS
2448 bp_site->SetEnabled(false);
2449 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002450 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 +00002451 return error;
2452 }
2453 else
2454 {
2455 if (break_op_found)
2456 error.SetErrorString("Failed to restore original opcode.");
2457 }
2458 }
2459 else
2460 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2461 }
2462 }
2463 else
2464 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2465 }
2466 }
2467 else
2468 {
2469 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002470 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 +00002471 return error;
2472 }
2473
2474 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002475 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476 bp_site->GetID(),
2477 (uint64_t)bp_addr,
2478 error.AsCString());
2479 return error;
2480
2481}
2482
Greg Clayton58be07b2011-01-07 06:08:19 +00002483// Uncomment to verify memory caching works after making changes to caching code
2484//#define VERIFY_MEMORY_READS
2485
Sean Callanan64c0cf22012-06-07 22:26:42 +00002486size_t
2487Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2488{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002489 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002490 if (!GetDisableMemoryCache())
2491 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002492#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002493 // Memory caching is enabled, with debug verification
2494
2495 if (buf && size)
2496 {
2497 // Uncomment the line below to make sure memory caching is working.
2498 // I ran this through the test suite and got no assertions, so I am
2499 // pretty confident this is working well. If any changes are made to
2500 // memory caching, uncomment the line below and test your changes!
2501
2502 // Verify all memory reads by using the cache first, then redundantly
2503 // reading the same memory from the inferior and comparing to make sure
2504 // everything is exactly the same.
2505 std::string verify_buf (size, '\0');
2506 assert (verify_buf.size() == size);
2507 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2508 Error verify_error;
2509 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2510 assert (cache_bytes_read == verify_bytes_read);
2511 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2512 assert (verify_error.Success() == error.Success());
2513 return cache_bytes_read;
2514 }
2515 return 0;
2516#else // !defined(VERIFY_MEMORY_READS)
2517 // Memory caching is enabled, without debug verification
2518
2519 return m_memory_cache.Read (addr, buf, size, error);
2520#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002521 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002522 else
2523 {
2524 // Memory caching is disabled
2525
2526 return ReadMemoryFromInferior (addr, buf, size, error);
2527 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002528}
Greg Clayton58be07b2011-01-07 06:08:19 +00002529
Greg Clayton4c82d422012-05-18 23:20:01 +00002530size_t
2531Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2532{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002533 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002534 out_str.clear();
2535 addr_t curr_addr = addr;
2536 while (1)
2537 {
2538 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2539 if (length == 0)
2540 break;
2541 out_str.append(buf, length);
2542 // If we got "length - 1" bytes, we didn't get the whole C string, we
2543 // need to read some more characters
2544 if (length == sizeof(buf) - 1)
2545 curr_addr += length;
2546 else
2547 break;
2548 }
2549 return out_str.size();
2550}
2551
Greg Clayton58be07b2011-01-07 06:08:19 +00002552
2553size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002554Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2555 size_t type_width)
2556{
2557 size_t total_bytes_read = 0;
2558 if (dst && max_bytes && type_width && max_bytes >= type_width)
2559 {
2560 // Ensure a null terminator independent of the number of bytes that is read.
2561 memset (dst, 0, max_bytes);
2562 size_t bytes_left = max_bytes - type_width;
2563
2564 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2565 assert(sizeof(terminator) >= type_width &&
2566 "Attempting to validate a string with more than 4 bytes per character!");
2567
2568 addr_t curr_addr = addr;
2569 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2570 char *curr_dst = dst;
2571
2572 error.Clear();
2573 while (bytes_left > 0 && error.Success())
2574 {
2575 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2576 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2577 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2578
2579 if (bytes_read == 0)
2580 break;
2581
2582 // Search for a null terminator of correct size and alignment in bytes_read
2583 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2584 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2585 if (::strncmp(&dst[i], terminator, type_width) == 0)
2586 {
2587 error.Clear();
2588 return i;
2589 }
2590
2591 total_bytes_read += bytes_read;
2592 curr_dst += bytes_read;
2593 curr_addr += bytes_read;
2594 bytes_left -= bytes_read;
2595 }
2596 }
2597 else
2598 {
2599 if (max_bytes)
2600 error.SetErrorString("invalid arguments");
2601 }
2602 return total_bytes_read;
2603}
2604
2605// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2606// null terminators.
2607size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002608Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002609{
2610 size_t total_cstr_len = 0;
2611 if (dst && dst_max_len)
2612 {
Greg Claytone91b7952011-12-15 03:14:23 +00002613 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002614 // NULL out everything just to be safe
2615 memset (dst, 0, dst_max_len);
2616 Error error;
2617 addr_t curr_addr = addr;
2618 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2619 size_t bytes_left = dst_max_len - 1;
2620 char *curr_dst = dst;
2621
2622 while (bytes_left > 0)
2623 {
2624 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2625 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2626 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2627
2628 if (bytes_read == 0)
2629 {
Greg Claytone91b7952011-12-15 03:14:23 +00002630 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002631 dst[total_cstr_len] = '\0';
2632 break;
2633 }
2634 const size_t len = strlen(curr_dst);
2635
2636 total_cstr_len += len;
2637
2638 if (len < bytes_to_read)
2639 break;
2640
2641 curr_dst += bytes_read;
2642 curr_addr += bytes_read;
2643 bytes_left -= bytes_read;
2644 }
2645 }
Greg Claytone91b7952011-12-15 03:14:23 +00002646 else
2647 {
2648 if (dst == NULL)
2649 result_error.SetErrorString("invalid arguments");
2650 else
2651 result_error.Clear();
2652 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002653 return total_cstr_len;
2654}
2655
2656size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002657Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2658{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002659 if (buf == NULL || size == 0)
2660 return 0;
2661
2662 size_t bytes_read = 0;
2663 uint8_t *bytes = (uint8_t *)buf;
2664
2665 while (bytes_read < size)
2666 {
2667 const size_t curr_size = size - bytes_read;
2668 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2669 bytes + bytes_read,
2670 curr_size,
2671 error);
2672 bytes_read += curr_bytes_read;
2673 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2674 break;
2675 }
2676
2677 // Replace any software breakpoint opcodes that fall into this range back
2678 // into "buf" before we return
2679 if (bytes_read > 0)
2680 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2681 return bytes_read;
2682}
2683
Greg Clayton58a4c462010-12-16 20:01:20 +00002684uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002685Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002686{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002687 Scalar scalar;
2688 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2689 return scalar.ULongLong(fail_value);
2690 return fail_value;
2691}
2692
2693addr_t
2694Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2695{
2696 Scalar scalar;
2697 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2698 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2699 return LLDB_INVALID_ADDRESS;
2700}
2701
2702
2703bool
2704Process::WritePointerToMemory (lldb::addr_t vm_addr,
2705 lldb::addr_t ptr_value,
2706 Error &error)
2707{
2708 Scalar scalar;
2709 const uint32_t addr_byte_size = GetAddressByteSize();
2710 if (addr_byte_size <= 4)
2711 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002712 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002713 scalar = ptr_value;
2714 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002715}
2716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717size_t
2718Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2719{
2720 size_t bytes_written = 0;
2721 const uint8_t *bytes = (const uint8_t *)buf;
2722
2723 while (bytes_written < size)
2724 {
2725 const size_t curr_size = size - bytes_written;
2726 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2727 bytes + bytes_written,
2728 curr_size,
2729 error);
2730 bytes_written += curr_bytes_written;
2731 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2732 break;
2733 }
2734 return bytes_written;
2735}
2736
2737size_t
2738Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2739{
Greg Clayton58be07b2011-01-07 06:08:19 +00002740#if defined (ENABLE_MEMORY_CACHING)
2741 m_memory_cache.Flush (addr, size);
2742#endif
2743
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744 if (buf == NULL || size == 0)
2745 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002746
Jim Ingham4b536182011-08-09 02:12:22 +00002747 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002748
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749 // We need to write any data that would go where any current software traps
2750 // (enabled software breakpoints) any software traps (breakpoints) that we
2751 // may have placed in our tasks memory.
2752
Greg Claytond8cf1a12013-06-12 00:46:38 +00002753 BreakpointSiteList bp_sites_in_range;
2754
2755 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002757 // No breakpoint sites overlap
2758 if (bp_sites_in_range.IsEmpty())
2759 return WriteMemoryPrivate (addr, buf, size, error);
2760 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002761 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002762 const uint8_t *ubuf = (const uint8_t *)buf;
2763 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002764
Greg Claytond8cf1a12013-06-12 00:46:38 +00002765 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2766
2767 if (error.Success())
2768 {
2769 addr_t intersect_addr;
2770 size_t intersect_size;
2771 size_t opcode_offset;
2772 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2773 assert(intersects);
2774 assert(addr <= intersect_addr && intersect_addr < addr + size);
2775 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2776 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2777
2778 // Check for bytes before this breakpoint
2779 const addr_t curr_addr = addr + bytes_written;
2780 if (intersect_addr > curr_addr)
2781 {
2782 // There are some bytes before this breakpoint that we need to
2783 // just write to memory
2784 size_t curr_size = intersect_addr - curr_addr;
2785 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2786 ubuf + bytes_written,
2787 curr_size,
2788 error);
2789 bytes_written += curr_bytes_written;
2790 if (curr_bytes_written != curr_size)
2791 {
2792 // We weren't able to write all of the requested bytes, we
2793 // are done looping and will return the number of bytes that
2794 // we have written so far.
2795 if (error.Success())
2796 error.SetErrorToGenericError();
2797 }
2798 }
2799 // Now write any bytes that would cover up any software breakpoints
2800 // directly into the breakpoint opcode buffer
2801 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2802 bytes_written += intersect_size;
2803 }
2804 });
2805
2806 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002807 WriteMemoryPrivate (addr + bytes_written,
2808 ubuf + bytes_written,
2809 size - bytes_written,
2810 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002811 }
2812 }
2813 else
2814 {
2815 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816 }
2817
2818 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002819 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002820}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002821
2822size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002823Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002824{
2825 if (byte_size == UINT32_MAX)
2826 byte_size = scalar.GetByteSize();
2827 if (byte_size > 0)
2828 {
2829 uint8_t buf[32];
2830 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2831 if (mem_size > 0)
2832 return WriteMemory(addr, buf, mem_size, error);
2833 else
2834 error.SetErrorString ("failed to get scalar as memory data");
2835 }
2836 else
2837 {
2838 error.SetErrorString ("invalid scalar value");
2839 }
2840 return 0;
2841}
2842
2843size_t
2844Process::ReadScalarIntegerFromMemory (addr_t addr,
2845 uint32_t byte_size,
2846 bool is_signed,
2847 Scalar &scalar,
2848 Error &error)
2849{
Greg Clayton7060f892013-05-01 23:41:30 +00002850 uint64_t uval = 0;
2851 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002852 {
Greg Clayton7060f892013-05-01 23:41:30 +00002853 error.SetErrorString ("byte size is zero");
2854 }
2855 else if (byte_size & (byte_size - 1))
2856 {
2857 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2858 }
2859 else if (byte_size <= sizeof(uval))
2860 {
2861 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002862 if (bytes_read == byte_size)
2863 {
2864 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002865 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002866 if (byte_size <= 4)
2867 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002868 else
Greg Clayton7060f892013-05-01 23:41:30 +00002869 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002870 if (is_signed)
2871 scalar.SignExtend(byte_size * 8);
2872 return bytes_read;
2873 }
2874 }
2875 else
2876 {
2877 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2878 }
2879 return 0;
2880}
2881
Greg Claytond495c532011-05-17 03:37:42 +00002882#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883addr_t
2884Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2885{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002886 if (GetPrivateState() != eStateStopped)
2887 return LLDB_INVALID_ADDRESS;
2888
Greg Claytond495c532011-05-17 03:37:42 +00002889#if defined (USE_ALLOCATE_MEMORY_CACHE)
2890 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2891#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002892 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002893 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002894 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002895 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 +00002896 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002897 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002898 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002899 m_mod_id.GetStopID(),
2900 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002901 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002902#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903}
2904
Sean Callanan90539452011-09-20 23:01:51 +00002905bool
2906Process::CanJIT ()
2907{
Sean Callanana7b443a2012-02-14 22:50:38 +00002908 if (m_can_jit == eCanJITDontKnow)
2909 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002910 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002911 Error err;
2912
2913 uint64_t allocated_memory = AllocateMemory(8,
2914 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2915 err);
2916
2917 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002918 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002919 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002920 if (log)
2921 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2922 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002923 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002924 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002925 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002926 if (log)
2927 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2928 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002929
2930 DeallocateMemory (allocated_memory);
2931 }
2932
Sean Callanan90539452011-09-20 23:01:51 +00002933 return m_can_jit == eCanJITYes;
2934}
2935
2936void
2937Process::SetCanJIT (bool can_jit)
2938{
2939 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2940}
2941
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942Error
2943Process::DeallocateMemory (addr_t ptr)
2944{
Greg Claytond495c532011-05-17 03:37:42 +00002945 Error error;
2946#if defined (USE_ALLOCATE_MEMORY_CACHE)
2947 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2948 {
Daniel Malead01b2952012-11-29 21:49:15 +00002949 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002950 }
2951#else
2952 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002953
Greg Clayton5160ce52013-03-27 23:08:40 +00002954 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002955 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002956 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 +00002957 ptr,
2958 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002959 m_mod_id.GetStopID(),
2960 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002961#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002962 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963}
2964
Han Ming Ongc811d382012-11-17 00:33:14 +00002965
Greg Claytonc9660542012-02-05 02:38:54 +00002966ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002967Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002968 lldb::addr_t header_addr,
2969 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002970{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002971 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002972 if (module_sp)
2973 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002974 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002975 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002976 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002977 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002978 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002979 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002980}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002981
2982Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002983Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002984{
2985 Error error;
2986 error.SetErrorString("watchpoints are not supported");
2987 return error;
2988}
2989
2990Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002991Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992{
2993 Error error;
2994 error.SetErrorString("watchpoints are not supported");
2995 return error;
2996}
2997
2998StateType
2999Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
3000{
3001 StateType state;
3002 // Now wait for the process to launch and return control to us, and then
3003 // call DidLaunch:
3004 while (1)
3005 {
Greg Clayton6779606a2011-01-22 23:43:18 +00003006 event_sp.reset();
3007 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
3008
Greg Clayton2637f822011-11-17 01:23:07 +00003009 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003010 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00003011
3012 // If state is invalid, then we timed out
3013 if (state == eStateInvalid)
3014 break;
3015
3016 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 HandlePrivateEvent (event_sp);
3018 }
3019 return state;
3020}
3021
Greg Clayton332e8b12015-01-13 21:13:08 +00003022void
3023Process::LoadOperatingSystemPlugin(bool flush)
3024{
3025 if (flush)
3026 m_thread_list.Clear();
3027 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
3028 if (flush)
3029 Flush();
3030}
3031
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003033Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034{
3035 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003037 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003038 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003039 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003040 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003041 m_process_input_reader.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003042 m_stop_info_override_callback = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043
Greg Claytonaa149cb2011-08-11 02:48:45 +00003044 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045 if (exe_module)
3046 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003047 char local_exec_file_path[PATH_MAX];
3048 char platform_exec_file_path[PATH_MAX];
3049 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3050 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051 if (exe_module->GetFileSpec().Exists())
3052 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003053 // Install anything that might need to be installed prior to launching.
3054 // For host systems, this will do nothing, but if we are connected to a
3055 // remote platform it will install any needed binaries
3056 error = GetTarget().Install(&launch_info);
3057 if (error.Fail())
3058 return error;
3059
Greg Clayton71337622011-02-24 22:24:29 +00003060 if (PrivateStateThreadIsValid ())
3061 PausePrivateStateThread ();
3062
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003063 error = WillLaunch (exe_module);
3064 if (error.Success())
3065 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003066 const bool restarted = false;
3067 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003068 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069
Ed Maste64fad602013-07-29 20:58:06 +00003070 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003071 {
3072 // Now launch using these arguments.
3073 error = DoLaunch (exe_module, launch_info);
3074 }
3075 else
3076 {
3077 // This shouldn't happen
3078 error.SetErrorString("failed to acquire process run lock");
3079 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080
3081 if (error.Fail())
3082 {
3083 if (GetID() != LLDB_INVALID_PROCESS_ID)
3084 {
3085 SetID (LLDB_INVALID_PROCESS_ID);
3086 const char *error_string = error.AsCString();
3087 if (error_string == NULL)
3088 error_string = "launch failed";
3089 SetExitStatus (-1, error_string);
3090 }
3091 }
3092 else
3093 {
3094 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003095 TimeValue timeout_time;
3096 timeout_time = TimeValue::Now();
3097 timeout_time.OffsetWithSeconds(10);
3098 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003099
Greg Clayton1a38ea72011-06-22 01:42:17 +00003100 if (state == eStateInvalid || event_sp.get() == NULL)
3101 {
3102 // We were able to launch the process, but we failed to
3103 // catch the initial stop.
3104 SetExitStatus (0, "failed to catch stop after launch");
3105 Destroy();
3106 }
3107 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003108 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003109
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110 DidLaunch ();
3111
Greg Claytonc859e2d2012-02-13 23:10:39 +00003112 DynamicLoader *dyld = GetDynamicLoader ();
3113 if (dyld)
3114 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003115
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003116 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003117
Jason Molendaeef51062013-11-05 03:57:19 +00003118 SystemRuntime *system_runtime = GetSystemRuntime ();
3119 if (system_runtime)
3120 system_runtime->DidLaunch();
3121
Greg Clayton332e8b12015-01-13 21:13:08 +00003122 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003123
3124 // Note, the stop event was consumed above, but not handled. This was done
3125 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3126 // Directly set the state. This is done to prevent a stop message with a bunch
3127 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3128 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003129
3130 if (PrivateStateThreadIsValid ())
3131 ResumePrivateStateThread ();
3132 else
3133 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003134
3135 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003136
3137 // Target was stopped at entry as was intended. Need to notify the listeners
3138 // about it.
3139 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry) == true)
3140 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 }
3142 else if (state == eStateExited)
3143 {
3144 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3145 // not likely to work, and return an invalid pid.
3146 HandlePrivateEvent (event_sp);
3147 }
3148 }
3149 }
3150 }
3151 else
3152 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003153 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003154 }
3155 }
3156 return error;
3157}
3158
Greg Claytonc3776bf2012-02-09 06:16:32 +00003159
3160Error
3161Process::LoadCore ()
3162{
3163 Error error = DoLoadCore();
3164 if (error.Success())
3165 {
3166 if (PrivateStateThreadIsValid ())
3167 ResumePrivateStateThread ();
3168 else
3169 StartPrivateStateThread ();
3170
Greg Claytonc859e2d2012-02-13 23:10:39 +00003171 DynamicLoader *dyld = GetDynamicLoader ();
3172 if (dyld)
3173 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003174
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003175 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003176
Jason Molendaeef51062013-11-05 03:57:19 +00003177 SystemRuntime *system_runtime = GetSystemRuntime ();
3178 if (system_runtime)
3179 system_runtime->DidAttach();
3180
Greg Claytonc859e2d2012-02-13 23:10:39 +00003181 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003182 // We successfully loaded a core file, now pretend we stopped so we can
3183 // show all of the threads in the core file and explore the crashed
3184 // state.
3185 SetPrivateState (eStateStopped);
3186
3187 }
3188 return error;
3189}
3190
Greg Claytonc859e2d2012-02-13 23:10:39 +00003191DynamicLoader *
3192Process::GetDynamicLoader ()
3193{
3194 if (m_dyld_ap.get() == NULL)
3195 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3196 return m_dyld_ap.get();
3197}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003198
Todd Fialaaf245d12014-06-30 21:05:18 +00003199const lldb::DataBufferSP
3200Process::GetAuxvData()
3201{
3202 return DataBufferSP ();
3203}
3204
Andrew MacPherson17220c12014-03-05 10:12:43 +00003205JITLoaderList &
3206Process::GetJITLoaders ()
3207{
3208 if (!m_jit_loaders_ap)
3209 {
3210 m_jit_loaders_ap.reset(new JITLoaderList());
3211 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3212 }
3213 return *m_jit_loaders_ap;
3214}
3215
Jason Molendaeef51062013-11-05 03:57:19 +00003216SystemRuntime *
3217Process::GetSystemRuntime ()
3218{
3219 if (m_system_runtime_ap.get() == NULL)
3220 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3221 return m_system_runtime_ap.get();
3222}
3223
Todd Fiala76e0fc92014-08-27 22:58:26 +00003224Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3225 NextEventAction (process),
3226 m_exec_count (exec_count)
3227{
3228 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3229 if (log)
3230 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3231}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003232
Jim Inghambb3a2832011-01-29 01:49:25 +00003233Process::NextEventAction::EventActionResult
3234Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003236 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3237
Jim Inghambb3a2832011-01-29 01:49:25 +00003238 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003239 if (log)
3240 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3241
3242 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003243 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003244 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003245 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003246 return eEventActionRetry;
3247
3248 case eStateStopped:
3249 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003250 {
3251 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003252 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003253 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003254 // We don't want these events to be reported, so go set the ShouldReportStop here:
3255 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3256
Greg Claytonc9ed4782011-11-12 02:10:56 +00003257 if (m_exec_count > 0)
3258 {
3259 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003260
3261 if (log)
3262 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
3263
Jim Ingham221d51c2013-05-08 00:35:16 +00003264 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003265 return eEventActionRetry;
3266 }
3267 else
3268 {
Todd Fiala76e0fc92014-08-27 22:58:26 +00003269 if (log)
3270 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
3271
Greg Claytonc9ed4782011-11-12 02:10:56 +00003272 m_process->CompleteAttach ();
3273 return eEventActionSuccess;
3274 }
3275 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003276 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003277
Greg Clayton513c26c2011-01-29 07:10:55 +00003278 default:
3279 case eStateExited:
3280 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003281 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003282 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003283
3284 m_exit_string.assign ("No valid Process");
3285 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003286}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287
Jim Inghambb3a2832011-01-29 01:49:25 +00003288Process::NextEventAction::EventActionResult
3289Process::AttachCompletionHandler::HandleBeingInterrupted()
3290{
3291 return eEventActionSuccess;
3292}
3293
3294const char *
3295Process::AttachCompletionHandler::GetExitString ()
3296{
3297 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298}
3299
Greg Clayton8012cad2014-11-17 19:39:20 +00003300Listener &
3301ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3302{
3303 if (m_listener_sp)
3304 return *m_listener_sp;
3305 else
3306 return debugger.GetListener();
3307}
3308
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003310Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003311{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003313 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003314 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003315 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003316 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003317 m_os_ap.reset();
Greg Claytona97c4d22014-12-09 23:31:02 +00003318 m_stop_info_override_callback = NULL;
Jim Ingham5aee1622010-08-09 23:31:02 +00003319
Greg Clayton144f3a92011-11-15 03:53:30 +00003320 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003321 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003322 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003323 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003324 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003325
Greg Clayton144f3a92011-11-15 03:53:30 +00003326 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003327 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003328 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3329
3330 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003332 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3333 if (error.Success())
3334 {
Ed Maste64fad602013-07-29 20:58:06 +00003335 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003336 {
3337 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003338 const bool restarted = false;
3339 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003340 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003341 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003342 }
3343 else
3344 {
3345 // This shouldn't happen
3346 error.SetErrorString("failed to acquire process run lock");
3347 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003348
Greg Clayton144f3a92011-11-15 03:53:30 +00003349 if (error.Fail())
3350 {
3351 if (GetID() != LLDB_INVALID_PROCESS_ID)
3352 {
3353 SetID (LLDB_INVALID_PROCESS_ID);
3354 if (error.AsCString() == NULL)
3355 error.SetErrorString("attach failed");
3356
3357 SetExitStatus(-1, error.AsCString());
3358 }
3359 }
3360 else
3361 {
3362 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3363 StartPrivateStateThread();
3364 }
3365 return error;
3366 }
Greg Claytone996fd32011-03-08 22:40:15 +00003367 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003368 else
Greg Claytone996fd32011-03-08 22:40:15 +00003369 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003370 ProcessInstanceInfoList process_infos;
3371 PlatformSP platform_sp (m_target.GetPlatform ());
3372
3373 if (platform_sp)
3374 {
3375 ProcessInstanceInfoMatch match_info;
3376 match_info.GetProcessInfo() = attach_info;
3377 match_info.SetNameMatchType (eNameMatchEquals);
3378 platform_sp->FindProcesses (match_info, process_infos);
3379 const uint32_t num_matches = process_infos.GetSize();
3380 if (num_matches == 1)
3381 {
3382 attach_pid = process_infos.GetProcessIDAtIndex(0);
3383 // Fall through and attach using the above process ID
3384 }
3385 else
3386 {
3387 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3388 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003389 {
3390 StreamString s;
3391 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3392 for (size_t i = 0; i < num_matches; i++)
3393 {
3394 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3395 }
3396 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3397 process_name,
3398 s.GetData());
3399 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003400 else
3401 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3402 }
3403 }
3404 else
3405 {
3406 error.SetErrorString ("invalid platform, can't find processes by name");
3407 return error;
3408 }
Greg Claytone996fd32011-03-08 22:40:15 +00003409 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 }
3411 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003412 {
3413 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003414 }
3415 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003416
3417 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003418 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003419 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003420 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003421 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003422
Ed Maste64fad602013-07-29 20:58:06 +00003423 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003424 {
3425 // Now attach using these arguments.
3426 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003427 const bool restarted = false;
3428 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003429 error = DoAttachToProcessWithID (attach_pid, attach_info);
3430 }
3431 else
3432 {
3433 // This shouldn't happen
3434 error.SetErrorString("failed to acquire process run lock");
3435 }
3436
Greg Clayton144f3a92011-11-15 03:53:30 +00003437 if (error.Success())
3438 {
3439
3440 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3441 StartPrivateStateThread();
3442 }
3443 else
Greg Claytone996fd32011-03-08 22:40:15 +00003444 {
3445 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003446 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003447
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003448 const char *error_string = error.AsCString();
3449 if (error_string == NULL)
3450 error_string = "attach failed";
3451
3452 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454 }
3455 }
3456 return error;
3457}
3458
Greg Clayton93d3c8332011-02-16 04:46:07 +00003459void
3460Process::CompleteAttach ()
3461{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003462 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3463 if (log)
3464 log->Printf ("Process::%s()", __FUNCTION__);
3465
Greg Clayton93d3c8332011-02-16 04:46:07 +00003466 // Let the process subclass figure out at much as it can about the process
3467 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003468 ArchSpec process_arch;
3469 DidAttach(process_arch);
3470
3471 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003472 {
Jim Inghambb006ce2014-08-02 00:33:35 +00003473 m_target.SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003474 if (log)
3475 {
3476 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3477 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3478 __FUNCTION__,
3479 triple_str ? triple_str : "<null>");
3480 }
3481 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003482
Jim Ingham4299fdb2011-09-15 01:10:17 +00003483 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3484 // the same as the one we've already set, switch architectures.
3485 PlatformSP platform_sp (m_target.GetPlatform ());
3486 assert (platform_sp.get());
3487 if (platform_sp)
3488 {
Greg Clayton70512312012-05-08 01:45:38 +00003489 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003490 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003491 {
3492 ArchSpec platform_arch;
3493 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3494 if (platform_sp)
3495 {
3496 m_target.SetPlatform (platform_sp);
3497 m_target.SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003498 if (log)
3499 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 +00003500 }
3501 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003502 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003503 {
3504 ProcessInstanceInfo process_info;
3505 platform_sp->GetProcessInfo (GetID(), process_info);
3506 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003507 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003508 {
Greg Clayton70512312012-05-08 01:45:38 +00003509 m_target.SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003510 if (log)
3511 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 ());
3512 }
Greg Clayton70512312012-05-08 01:45:38 +00003513 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003514 }
3515
3516 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003517 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003518 DynamicLoader *dyld = GetDynamicLoader ();
3519 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003520 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003521 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003522 if (log)
3523 {
3524 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3525 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3526 __FUNCTION__,
3527 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3528 dyld->GetPluginName().AsCString ("<unnamed>"));
3529 }
3530 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003531
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003532 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003533
Jason Molendaeef51062013-11-05 03:57:19 +00003534 SystemRuntime *system_runtime = GetSystemRuntime ();
3535 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003536 {
Jason Molendaeef51062013-11-05 03:57:19 +00003537 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003538 if (log)
3539 {
3540 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3541 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3542 __FUNCTION__,
3543 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3544 system_runtime->GetPluginName().AsCString("<unnamed>"));
3545 }
3546 }
Jason Molendaeef51062013-11-05 03:57:19 +00003547
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003548 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003549 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003550 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003551 Mutex::Locker modules_locker(target_modules.GetMutex());
3552 size_t num_modules = target_modules.GetSize();
3553 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003554
Andy Gibbsa297a972013-06-19 19:04:53 +00003555 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003556 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003557 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003558 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003559 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003560 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003561 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003562 break;
3563 }
3564 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003565 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003566 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003567 m_target.SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003568 if (log)
3569 {
3570 ModuleSP exe_module_sp = m_target.GetExecutableModule ();
3571 log->Printf ("Process::%s after looping through modules, target executable is %s",
3572 __FUNCTION__,
3573 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3574 }
3575 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003576
3577 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003578}
3579
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003580Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003581Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003582{
Greg Claytonb766a732011-02-04 01:58:07 +00003583 m_abi_sp.reset();
3584 m_process_input_reader.reset();
3585
3586 // Find the process and its architecture. Make sure it matches the architecture
3587 // of the current Target, and if not adjust it.
3588
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003589 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003590 if (error.Success())
3591 {
Greg Clayton71337622011-02-24 22:24:29 +00003592 if (GetID() != LLDB_INVALID_PROCESS_ID)
3593 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003594 EventSP event_sp;
3595 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3596
3597 if (state == eStateStopped || state == eStateCrashed)
3598 {
3599 // If we attached and actually have a process on the other end, then
3600 // this ended up being the equivalent of an attach.
3601 CompleteAttach ();
3602
3603 // This delays passing the stopped event to listeners till
3604 // CompleteAttach gets a chance to complete...
3605 HandlePrivateEvent (event_sp);
3606
3607 }
Greg Clayton71337622011-02-24 22:24:29 +00003608 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003609
3610 if (PrivateStateThreadIsValid ())
3611 ResumePrivateStateThread ();
3612 else
3613 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003614 }
3615 return error;
3616}
3617
3618
3619Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003620Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003621{
Greg Clayton5160ce52013-03-27 23:08:40 +00003622 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003623 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003624 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003625 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003626 StateAsCString(m_public_state.GetValue()),
3627 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003628
3629 Error error (WillResume());
3630 // Tell the process it is about to resume before the thread list
3631 if (error.Success())
3632 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003633 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003634 // can let all of our threads know that they are about to be
3635 // resumed. Threads will each be called with
3636 // Thread::WillResume(StateType) where StateType contains the state
3637 // that they are supposed to have when the process is resumed
3638 // (suspended/running/stepping). Threads should also check
3639 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003640 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003641 if (m_thread_list.WillResume())
3642 {
Jim Ingham372787f2012-04-07 00:00:41 +00003643 // Last thing, do the PreResumeActions.
3644 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645 {
Jim Ingham0161b492013-02-09 01:29:05 +00003646 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003647 }
3648 else
3649 {
3650 m_mod_id.BumpResumeID();
3651 error = DoResume();
3652 if (error.Success())
3653 {
3654 DidResume();
3655 m_thread_list.DidResume();
3656 if (log)
3657 log->Printf ("Process thinks the process has resumed.");
3658 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003659 }
3660 }
3661 else
3662 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003663 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3664 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003665 // and let the world handle them.
3666 if (log)
3667 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3668
3669 SetPrivateState(eStateRunning);
3670 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003671 }
3672 }
Jim Ingham444586b2011-01-24 06:34:17 +00003673 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003674 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675 return error;
3676}
3677
3678Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003679Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003680{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003681 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3682 // in case it was already set and some thread plan logic calls halt on its
3683 // own.
3684 m_clear_thread_plans_on_stop |= clear_thread_plans;
3685
Jim Inghamaacc3182012-06-06 00:29:30 +00003686 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3687 // we could just straightaway get another event. It just narrows the window...
3688 m_currently_handling_event.WaitForValueEqualTo(false);
3689
3690
Jim Inghambb3a2832011-01-29 01:49:25 +00003691 // Pause our private state thread so we can ensure no one else eats
3692 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003693 Listener halt_listener ("lldb.process.halt_listener");
3694 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003695
Jim Inghambb3a2832011-01-29 01:49:25 +00003696 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003697 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003698
Greg Clayton06357c92014-07-30 17:38:47 +00003699 bool restored_process_events = false;
Greg Clayton513c26c2011-01-29 07:10:55 +00003700 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003701 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003702
Greg Clayton513c26c2011-01-29 07:10:55 +00003703 bool caused_stop = false;
3704
3705 // Ask the process subclass to actually halt our process
3706 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003707 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003708 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003709 if (m_public_state.GetValue() == eStateAttaching)
3710 {
Greg Clayton06357c92014-07-30 17:38:47 +00003711 // Don't hijack and eat the eStateExited as the code that was doing
3712 // the attach will be waiting for this event...
3713 RestorePrivateProcessEvents();
3714 restored_process_events = true;
Greg Clayton513c26c2011-01-29 07:10:55 +00003715 SetExitStatus(SIGKILL, "Cancelled async attach.");
3716 Destroy ();
3717 }
3718 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003719 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003720 // If "caused_stop" is true, then DoHalt stopped the process. If
3721 // "caused_stop" is false, the process was already stopped.
3722 // If the DoHalt caused the process to stop, then we want to catch
3723 // this event and set the interrupted bool to true before we pass
3724 // this along so clients know that the process was interrupted by
3725 // a halt command.
3726 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003727 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003728 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003729 TimeValue timeout_time;
3730 timeout_time = TimeValue::Now();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003731 timeout_time.OffsetWithSeconds(10);
Jim Ingham0f16e732011-02-08 05:20:59 +00003732 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3733 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003734
Jim Ingham0f16e732011-02-08 05:20:59 +00003735 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003736 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003737 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003738 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003739 }
3740 else
3741 {
Greg Clayton2637f822011-11-17 01:23:07 +00003742 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003743 {
3744 // We caused the process to interrupt itself, so mark this
3745 // as such in the stop event so clients can tell an interrupted
3746 // process from a natural stop
3747 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3748 }
3749 else
3750 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003751 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003752 if (log)
3753 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3754 error.SetErrorString ("Did not get stopped event after halt.");
3755 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003756 }
3757 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003758 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003759 }
3760 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003762 // Resume our private state thread before we post the event (if any)
Greg Clayton06357c92014-07-30 17:38:47 +00003763 if (!restored_process_events)
3764 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003765
3766 // Post any event we might have consumed. If all goes well, we will have
3767 // stopped the process, intercepted the event and set the interrupted
3768 // bool in the event. Post it to the private event queue and that will end up
3769 // correctly setting the state.
3770 if (event_sp)
3771 m_private_state_broadcaster.BroadcastEvent(event_sp);
3772
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773 return error;
3774}
3775
3776Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003777Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3778{
3779 Error error;
3780 if (m_public_state.GetValue() == eStateRunning)
3781 {
3782 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3783 if (log)
3784 log->Printf("Process::Destroy() About to halt.");
3785 error = Halt();
3786 if (error.Success())
3787 {
3788 // Consume the halt event.
3789 TimeValue timeout (TimeValue::Now());
3790 timeout.OffsetWithSeconds(1);
3791 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3792
3793 // If the process exited while we were waiting for it to stop, put the exited event into
3794 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3795 // they don't have a process anymore...
3796
3797 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3798 {
3799 if (log)
3800 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3801 return error;
3802 }
3803 else
3804 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3805
3806 if (state != eStateStopped)
3807 {
3808 if (log)
3809 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3810 // If we really couldn't stop the process then we should just error out here, but if the
3811 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3812 StateType private_state = m_private_state.GetValue();
3813 if (private_state != eStateStopped)
3814 {
3815 return error;
3816 }
3817 }
3818 }
3819 else
3820 {
3821 if (log)
3822 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3823 }
3824 }
3825 return error;
3826}
3827
3828Error
Jim Inghamacff8952013-05-02 00:27:30 +00003829Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003830{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003831 EventSP exit_event_sp;
3832 Error error;
3833 m_destroy_in_process = true;
3834
3835 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003836
3837 if (error.Success())
3838 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003839 if (DetachRequiresHalt())
3840 {
3841 error = HaltForDestroyOrDetach (exit_event_sp);
3842 if (!error.Success())
3843 {
3844 m_destroy_in_process = false;
3845 return error;
3846 }
3847 else if (exit_event_sp)
3848 {
3849 // We shouldn't need to do anything else here. There's no process left to detach from...
3850 StopPrivateStateThread();
3851 m_destroy_in_process = false;
3852 return error;
3853 }
3854 }
3855
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003856 m_thread_list.DiscardThreadPlans();
3857 DisableAllBreakpointSites();
3858
Jim Inghamacff8952013-05-02 00:27:30 +00003859 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003860 if (error.Success())
3861 {
3862 DidDetach();
3863 StopPrivateStateThread();
3864 }
Jim Inghamacff8952013-05-02 00:27:30 +00003865 else
3866 {
3867 return error;
3868 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003869 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003870 m_destroy_in_process = false;
3871
3872 // If we exited when we were waiting for a process to stop, then
3873 // forward the event here so we don't lose the event
3874 if (exit_event_sp)
3875 {
3876 // Directly broadcast our exited event because we shut down our
3877 // private state thread above
3878 BroadcastEvent(exit_event_sp);
3879 }
3880
3881 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3882 // the last events through the event system, in which case we might strand the write lock. Unlock
3883 // it here so when we do to tear down the process we don't get an error destroying the lock.
3884
Ed Maste64fad602013-07-29 20:58:06 +00003885 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003886 return error;
3887}
3888
3889Error
3890Process::Destroy ()
3891{
Jim Ingham09437922013-03-01 20:04:25 +00003892
3893 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3894 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3895 // failed and the process stays around for some reason it won't be in a confused state.
3896
3897 m_destroy_in_process = true;
3898
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003899 Error error (WillDestroy());
3900 if (error.Success())
3901 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003902 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003903 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003904 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003905 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003906 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003907
Jim Inghamaacc3182012-06-06 00:29:30 +00003908 if (m_public_state.GetValue() != eStateRunning)
3909 {
3910 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3911 // kill it, we don't want it hitting a breakpoint...
3912 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3913 // we're not going to have much luck doing this now.
3914 m_thread_list.DiscardThreadPlans();
3915 DisableAllBreakpointSites();
3916 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003917
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003918 error = DoDestroy();
3919 if (error.Success())
3920 {
3921 DidDestroy();
3922 StopPrivateStateThread();
3923 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003924 m_stdio_communication.StopReadThread();
3925 m_stdio_communication.Disconnect();
Vince Harrone0be4252015-02-06 18:32:57 +00003926 m_stdio_disable = true;
Greg Claytonb4874f12014-02-28 18:22:24 +00003927
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003928 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003929 {
3930 m_process_input_reader->SetIsDone(true);
3931 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003932 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003933 }
3934
Greg Clayton85fb1b92012-09-11 02:33:37 +00003935 // If we exited when we were waiting for a process to stop, then
3936 // forward the event here so we don't lose the event
3937 if (exit_event_sp)
3938 {
3939 // Directly broadcast our exited event because we shut down our
3940 // private state thread above
3941 BroadcastEvent(exit_event_sp);
3942 }
3943
Jim Inghamb1e2e842012-04-12 18:49:31 +00003944 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3945 // the last events through the event system, in which case we might strand the write lock. Unlock
3946 // 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 +00003947 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003948 }
Jim Ingham09437922013-03-01 20:04:25 +00003949
3950 m_destroy_in_process = false;
3951
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003952 return error;
3953}
3954
3955Error
3956Process::Signal (int signal)
3957{
3958 Error error (WillSignal());
3959 if (error.Success())
3960 {
3961 error = DoSignal(signal);
3962 if (error.Success())
3963 DidSignal();
3964 }
3965 return error;
3966}
3967
Greg Clayton514487e2011-02-15 21:59:32 +00003968lldb::ByteOrder
3969Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003970{
Greg Clayton514487e2011-02-15 21:59:32 +00003971 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003972}
3973
3974uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003975Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003976{
Greg Clayton514487e2011-02-15 21:59:32 +00003977 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978}
3979
Greg Clayton514487e2011-02-15 21:59:32 +00003980
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003981bool
3982Process::ShouldBroadcastEvent (Event *event_ptr)
3983{
3984 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3985 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003986 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003987
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988 switch (state)
3989 {
Greg Claytonb766a732011-02-04 01:58:07 +00003990 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003991 case eStateAttaching:
3992 case eStateLaunching:
3993 case eStateDetached:
3994 case eStateExited:
3995 case eStateUnloaded:
3996 // These events indicate changes in the state of the debugging session, always report them.
3997 return_value = true;
3998 break;
3999 case eStateInvalid:
4000 // We stopped for no apparent reason, don't report it.
4001 return_value = false;
4002 break;
4003 case eStateRunning:
4004 case eStateStepping:
4005 // If we've started the target running, we handle the cases where we
4006 // are already running and where there is a transition from stopped to
4007 // running differently.
4008 // running -> running: Automatically suppress extra running events
4009 // stopped -> running: Report except when there is one or more no votes
4010 // and no yes votes.
4011 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00004012 if (m_force_next_event_delivery)
4013 return_value = true;
4014 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004015 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00004016 switch (m_last_broadcast_state)
4017 {
4018 case eStateRunning:
4019 case eStateStepping:
4020 // We always suppress multiple runnings with no PUBLIC stop in between.
4021 return_value = false;
4022 break;
4023 default:
4024 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004025 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00004026 // events. If I run the lldb/test/thread/a.out file and
4027 // break at main.cpp:58, run and hit the breakpoints on
4028 // multiple threads, then somehow during the stepping over
4029 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004030
Jim Ingham1460e4b2014-01-10 23:46:59 +00004031 // This is a transition from stop to run.
4032 switch (m_thread_list.ShouldReportRun (event_ptr))
4033 {
4034 case eVoteYes:
4035 case eVoteNoOpinion:
4036 return_value = true;
4037 break;
4038 case eVoteNo:
4039 return_value = false;
4040 break;
4041 }
4042 break;
4043 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004044 }
4045 break;
4046 case eStateStopped:
4047 case eStateCrashed:
4048 case eStateSuspended:
4049 {
4050 // We've stopped. First see if we're going to restart the target.
4051 // If we are going to stop, then we always broadcast the event.
4052 // 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 +00004053 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00004054
Jim Inghamcb4ca112012-05-16 01:32:14 +00004055 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004056 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004057 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00004058 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004059 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004060 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00004061 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00004062 // Even though we know we are going to stop, we should let the threads have a look at the stop,
4063 // so they can properly set their state.
4064 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00004065 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004066 }
4067 else
4068 {
Jim Ingham221d51c2013-05-08 00:35:16 +00004069 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
4070 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004071
Jim Ingham0161b492013-02-09 01:29:05 +00004072 // It makes no sense to ask "ShouldStop" if we've already been restarted...
4073 // Asking the thread list is also not likely to go well, since we are running again.
4074 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004075
Jim Ingham0161b492013-02-09 01:29:05 +00004076 if (!was_restarted)
4077 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004078
Jim Ingham221d51c2013-05-08 00:35:16 +00004079 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004080 {
Jim Ingham0161b492013-02-09 01:29:05 +00004081 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
4082 if (log)
4083 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004084 should_resume, StateAsCString(state),
4085 was_restarted, stop_vote);
4086
Jim Ingham0161b492013-02-09 01:29:05 +00004087 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004088 {
4089 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00004090 return_value = true;
4091 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004093 case eVoteNo:
4094 return_value = false;
4095 break;
4096 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004097
Jim Inghamcb95f342012-09-05 21:13:56 +00004098 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00004099 {
4100 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004101 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
4102 static_cast<void*>(event_ptr),
4103 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00004104 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00004105 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00004106 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004107
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004108 }
4109 else
4110 {
4111 return_value = true;
4112 SynchronouslyNotifyStateChanged (state);
4113 }
4114 }
4115 }
Jim Ingham0161b492013-02-09 01:29:05 +00004116 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004118
Jim Ingham1460e4b2014-01-10 23:46:59 +00004119 // Forcing the next event delivery is a one shot deal. So reset it here.
4120 m_force_next_event_delivery = false;
4121
Jim Ingham0161b492013-02-09 01:29:05 +00004122 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4123 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4124 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4125 // because the PublicState reflects the last event pulled off the queue, and there may be several
4126 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4127 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004128
Jim Ingham0161b492013-02-09 01:29:05 +00004129 if (return_value)
4130 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004131
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004132 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004133 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004134 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004135 StateAsCString(m_last_broadcast_state),
4136 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004137 return return_value;
4138}
4139
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004140
4141bool
Jim Ingham372787f2012-04-07 00:00:41 +00004142Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004143{
Greg Clayton5160ce52013-03-27 23:08:40 +00004144 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145
Greg Clayton8b82f082011-04-12 05:54:46 +00004146 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004148 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4149
Jim Ingham372787f2012-04-07 00:00:41 +00004150 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004151 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004152
4153 // Create a thread that watches our internal state and controls which
4154 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004155 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004156
Zachary Turner39de3112014-09-09 20:54:56 +00004157 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004158 {
Zachary Turner39de3112014-09-09 20:54:56 +00004159 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4160 if (already_running)
4161 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4162 else
4163 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004164 }
Jim Ingham372787f2012-04-07 00:00:41 +00004165 else
Todd Fiala17096d72014-07-16 19:03:16 +00004166 {
4167 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004168 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004169 else
Zachary Turner39de3112014-09-09 20:54:56 +00004170 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004171 }
4172
Jim Ingham076b3042012-04-10 01:21:57 +00004173 // Create the private state thread, and start it running.
Zachary Turner39de3112014-09-09 20:54:56 +00004174 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, this, NULL);
Zachary Turneracee96a2014-09-23 18:32:09 +00004175 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004176 {
4177 ResumePrivateStateThread();
4178 return true;
4179 }
4180 else
4181 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004182}
4183
4184void
4185Process::PausePrivateStateThread ()
4186{
4187 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4188}
4189
4190void
4191Process::ResumePrivateStateThread ()
4192{
4193 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4194}
4195
4196void
4197Process::StopPrivateStateThread ()
4198{
Greg Clayton8b82f082011-04-12 05:54:46 +00004199 if (PrivateStateThreadIsValid ())
4200 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004201 else
4202 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004203 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004204 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004205 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004206 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004207}
4208
4209void
4210Process::ControlPrivateStateThread (uint32_t signal)
4211{
Greg Clayton5160ce52013-03-27 23:08:40 +00004212 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213
4214 assert (signal == eBroadcastInternalStateControlStop ||
4215 signal == eBroadcastInternalStateControlPause ||
4216 signal == eBroadcastInternalStateControlResume);
4217
4218 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004219 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004220
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004221 // Signal the private state thread. First we should copy this is case the
4222 // thread starts exiting since the private state thread will NULL this out
4223 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004224 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004225 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004226 {
4227 TimeValue timeout_time;
4228 bool timed_out;
4229
4230 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4231
4232 timeout_time = TimeValue::Now();
4233 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004234 if (log)
4235 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004236 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4237 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4238
4239 if (signal == eBroadcastInternalStateControlStop)
4240 {
4241 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004242 {
Zachary Turner39de3112014-09-09 20:54:56 +00004243 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004244 if (log)
4245 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4246 }
4247 else
4248 {
4249 if (log)
4250 log->Printf ("The control event killed the private state thread without having to cancel.");
4251 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004252
4253 thread_result_t result = NULL;
Zachary Turner39de3112014-09-09 20:54:56 +00004254 private_state_thread.Join(&result);
4255 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004256 }
4257 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004258 else
4259 {
4260 if (log)
4261 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4262 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004263}
4264
4265void
Jim Inghamcfc09352012-07-27 23:57:19 +00004266Process::SendAsyncInterrupt ()
4267{
4268 if (PrivateStateThreadIsValid())
4269 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4270 else
4271 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4272}
4273
4274void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004275Process::HandlePrivateEvent (EventSP &event_sp)
4276{
Greg Clayton5160ce52013-03-27 23:08:40 +00004277 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004278 m_resume_requested = false;
4279
Jim Inghamaacc3182012-06-06 00:29:30 +00004280 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004281
Greg Clayton414f5d32011-01-25 02:58:48 +00004282 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004283
4284 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004285 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004286 {
Jim Ingham754ab982011-01-29 04:05:41 +00004287 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004288 if (log)
4289 log->Printf ("Ran next event action, result was %d.", action_result);
4290
Jim Inghambb3a2832011-01-29 01:49:25 +00004291 switch (action_result)
4292 {
4293 case NextEventAction::eEventActionSuccess:
4294 SetNextEventAction(NULL);
4295 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004296
Jim Inghambb3a2832011-01-29 01:49:25 +00004297 case NextEventAction::eEventActionRetry:
4298 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004299
Jim Inghambb3a2832011-01-29 01:49:25 +00004300 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004301 // Handle Exiting Here. If we already got an exited event,
4302 // we should just propagate it. Otherwise, swallow this event,
4303 // and set our state to exit so the next event will kill us.
4304 if (new_state != eStateExited)
4305 {
4306 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004307 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004308 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004309 SetNextEventAction(NULL);
4310 return;
4311 }
4312 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004313 break;
4314 }
4315 }
4316
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004317 // See if we should broadcast this state to external clients?
4318 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004319
4320 if (should_broadcast)
4321 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004322 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004323 if (log)
4324 {
Daniel Malead01b2952012-11-29 21:49:15 +00004325 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004326 __FUNCTION__,
4327 GetID(),
4328 StateAsCString(new_state),
4329 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004330 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004331 }
Jim Ingham9575d842011-03-11 03:53:59 +00004332 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004333 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004334 {
4335 // Only push the input handler if we aren't fowarding events,
4336 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004337 // Or don't push it if we are launching since it will come up stopped.
4338 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching)
Greg Clayton44d93782014-01-27 23:43:24 +00004339 PushProcessIOHandler ();
Todd Fialaa3b89e22014-08-12 14:33:19 +00004340 m_iohandler_sync.SetValue(true, eBroadcastAlways);
Greg Clayton44d93782014-01-27 23:43:24 +00004341 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004342 else if (StateIsStoppedState(new_state, false))
4343 {
Todd Fialaa3b89e22014-08-12 14:33:19 +00004344 m_iohandler_sync.SetValue(false, eBroadcastNever);
Greg Claytonb4874f12014-02-28 18:22:24 +00004345 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4346 {
4347 // If the lldb_private::Debugger is handling the events, we don't
4348 // want to pop the process IOHandler here, we want to do it when
4349 // we receive the stopped event so we can carefully control when
4350 // the process IOHandler is popped because when we stop we want to
4351 // display some text stating how and why we stopped, then maybe some
4352 // process/thread/frame info, and then we want the "(lldb) " prompt
4353 // to show up. If we pop the process IOHandler here, then we will
4354 // cause the command interpreter to become the top IOHandler after
4355 // the process pops off and it will update its prompt right away...
4356 // See the Debugger.cpp file where it calls the function as
4357 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4358 // Otherwise we end up getting overlapping "(lldb) " prompts and
4359 // garbled output.
4360 //
4361 // If we aren't handling the events in the debugger (which is indicated
4362 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4363 // are hijacked, then we always pop the process IO handler manually.
4364 // Hijacking happens when the internal process state thread is running
4365 // thread plans, or when commands want to run in synchronous mode
4366 // and they call "process->WaitForProcessToStop()". An example of something
4367 // that will hijack the events is a simple expression:
4368 //
4369 // (lldb) expr (int)puts("hello")
4370 //
4371 // This will cause the internal process state thread to resume and halt
4372 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4373 // events) and we do need the IO handler to be pushed and popped
4374 // correctly.
4375
4376 if (is_hijacked || m_target.GetDebugger().IsHandlingEvents() == false)
4377 PopProcessIOHandler ();
4378 }
4379 }
Jim Ingham9575d842011-03-11 03:53:59 +00004380
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004381 BroadcastEvent (event_sp);
4382 }
4383 else
4384 {
4385 if (log)
4386 {
Daniel Malead01b2952012-11-29 21:49:15 +00004387 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004388 __FUNCTION__,
4389 GetID(),
4390 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004391 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004392 }
4393 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004394 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004395}
4396
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004397thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004398Process::PrivateStateThread (void *arg)
4399{
4400 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004401 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004402 return result;
4403}
4404
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004405thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004406Process::RunPrivateStateThread ()
4407{
Jim Ingham076b3042012-04-10 01:21:57 +00004408 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004409 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004410
Greg Clayton5160ce52013-03-27 23:08:40 +00004411 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004412 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004413 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4414 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004415
4416 bool exit_now = false;
4417 while (!exit_now)
4418 {
4419 EventSP event_sp;
4420 WaitForEventsPrivate (NULL, event_sp, control_only);
4421 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4422 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004423 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004424 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4425 __FUNCTION__, static_cast<void*>(this), GetID(),
4426 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004427
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004428 switch (event_sp->GetType())
4429 {
4430 case eBroadcastInternalStateControlStop:
4431 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004432 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004433
4434 case eBroadcastInternalStateControlPause:
4435 control_only = true;
4436 break;
4437
4438 case eBroadcastInternalStateControlResume:
4439 control_only = false;
4440 break;
4441 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004442
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004443 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004444 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004445 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004446 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4447 {
4448 if (m_public_state.GetValue() == eStateAttaching)
4449 {
4450 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004451 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4452 __FUNCTION__, static_cast<void*>(this),
4453 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004454 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4455 }
4456 else
4457 {
4458 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004459 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4460 __FUNCTION__, static_cast<void*>(this),
4461 GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004462 Halt();
4463 }
4464 continue;
4465 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004466
4467 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4468
4469 if (internal_state != eStateInvalid)
4470 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004471 if (m_clear_thread_plans_on_stop &&
4472 StateIsStoppedState(internal_state, true))
4473 {
4474 m_clear_thread_plans_on_stop = false;
4475 m_thread_list.DiscardThreadPlans();
4476 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004477 HandlePrivateEvent (event_sp);
4478 }
4479
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004480 if (internal_state == eStateInvalid ||
4481 internal_state == eStateExited ||
4482 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004483 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004484 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004485 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4486 __FUNCTION__, static_cast<void*>(this), GetID(),
4487 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004488
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004489 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004490 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004491 }
4492
Caroline Tice20ad3c42010-10-29 21:48:37 +00004493 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004494 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004495 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4496 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004497
Ed Maste64fad602013-07-29 20:58:06 +00004498 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004499 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004500 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004501 return NULL;
4502}
4503
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004504//------------------------------------------------------------------
4505// Process Event Data
4506//------------------------------------------------------------------
4507
4508Process::ProcessEventData::ProcessEventData () :
4509 EventData (),
4510 m_process_sp (),
4511 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004512 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004513 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004514 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004515{
4516}
4517
4518Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4519 EventData (),
4520 m_process_sp (process_sp),
4521 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004522 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004523 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004524 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004525{
4526}
4527
4528Process::ProcessEventData::~ProcessEventData()
4529{
4530}
4531
4532const ConstString &
4533Process::ProcessEventData::GetFlavorString ()
4534{
4535 static ConstString g_flavor ("Process::ProcessEventData");
4536 return g_flavor;
4537}
4538
4539const ConstString &
4540Process::ProcessEventData::GetFlavor () const
4541{
4542 return ProcessEventData::GetFlavorString ();
4543}
4544
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004545void
4546Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4547{
4548 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004549 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4550 // the public event queue, then other times when we're pretending that this is where we stopped at the
4551 // end of expression evaluation. m_update_state is used to distinguish these
4552 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004553 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004554 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004555 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004556
Jim Ingham221d51c2013-05-08 00:35:16 +00004557 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004558
4559 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4560 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4561 // end up restarting the process.
4562 if (m_interrupted)
4563 return;
4564
4565 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004566 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004567 {
4568 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004569 uint32_t num_threads = curr_thread_list.GetSize();
4570 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004571
Jim Ingham4b536182011-08-09 02:12:22 +00004572 // The actions might change one of the thread's stop_info's opinions about whether we should
4573 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004574
4575 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4576 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4577 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4578 // 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
4579 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004580 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004581 for (idx = 0; idx < num_threads; ++idx)
4582 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4583
Jim Inghamc7078c22012-12-13 22:24:15 +00004584 // Use this to track whether we should continue from here. We will only continue the target running if
4585 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4586 // then it doesn't matter what the other threads say...
4587
4588 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004589
Jim Ingham0ad7e052013-04-25 02:04:59 +00004590 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4591 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4592 // thing to do is, and it's better to let the user decide than continue behind their backs.
4593
4594 bool does_anybody_have_an_opinion = false;
4595
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004596 for (idx = 0; idx < num_threads; ++idx)
4597 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004598 curr_thread_list = m_process_sp->GetThreadList();
4599 if (curr_thread_list.GetSize() != num_threads)
4600 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004601 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004602 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004603 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 +00004604 break;
4605 }
4606
4607 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4608
4609 if (thread_sp->GetIndexID() != thread_index_array[idx])
4610 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004611 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004612 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004613 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004614 idx,
4615 thread_index_array[idx],
4616 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004617 break;
4618 }
4619
Jim Inghamb15bfc72010-10-20 00:39:53 +00004620 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004621 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004622 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004623 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004624 bool this_thread_wants_to_stop;
4625 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004626 {
Jim Ingham0161b492013-02-09 01:29:05 +00004627 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4628 }
4629 else
4630 {
4631 stop_info_sp->PerformAction(event_ptr);
4632 // The stop action might restart the target. If it does, then we want to mark that in the
4633 // event so that whoever is receiving it will know to wait for the running event and reflect
4634 // that state appropriately.
4635 // We also need to stop processing actions, since they aren't expecting the target to be running.
4636
4637 // FIXME: we might have run.
4638 if (stop_info_sp->HasTargetRunSinceMe())
4639 {
4640 SetRestarted (true);
4641 break;
4642 }
4643
4644 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004645 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004646
Jim Inghamc7078c22012-12-13 22:24:15 +00004647 if (still_should_stop == false)
4648 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004649 }
4650 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004651
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004652
Jim Inghama8ca6e22013-05-03 23:04:37 +00004653 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004654 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004655 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004656 {
4657 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004658 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004659 // Use the public resume method here, since this is just
4660 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004661 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004662 }
4663 else
4664 {
4665 // If we didn't restart, run the Stop Hooks here:
4666 // They might also restart the target, so watch for that.
4667 m_process_sp->GetTarget().RunStopHooks();
4668 if (m_process_sp->GetPrivateState() == eStateRunning)
4669 SetRestarted(true);
4670 }
Jim Ingham9575d842011-03-11 03:53:59 +00004671 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004672 }
4673}
4674
4675void
4676Process::ProcessEventData::Dump (Stream *s) const
4677{
4678 if (m_process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004679 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4680 static_cast<void*>(m_process_sp.get()), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004681
Greg Clayton8b82f082011-04-12 05:54:46 +00004682 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004683}
4684
4685const Process::ProcessEventData *
4686Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4687{
4688 if (event_ptr)
4689 {
4690 const EventData *event_data = event_ptr->GetData();
4691 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4692 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4693 }
4694 return NULL;
4695}
4696
4697ProcessSP
4698Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4699{
4700 ProcessSP process_sp;
4701 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4702 if (data)
4703 process_sp = data->GetProcessSP();
4704 return process_sp;
4705}
4706
4707StateType
4708Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4709{
4710 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4711 if (data == NULL)
4712 return eStateInvalid;
4713 else
4714 return data->GetState();
4715}
4716
4717bool
4718Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4719{
4720 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4721 if (data == NULL)
4722 return false;
4723 else
4724 return data->GetRestarted();
4725}
4726
4727void
4728Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4729{
4730 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4731 if (data != NULL)
4732 data->SetRestarted(new_value);
4733}
4734
Jim Ingham0161b492013-02-09 01:29:05 +00004735size_t
4736Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4737{
4738 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4739 if (data != NULL)
4740 return data->GetNumRestartedReasons();
4741 else
4742 return 0;
4743}
4744
4745const char *
4746Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4747{
4748 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4749 if (data != NULL)
4750 return data->GetRestartedReasonAtIndex(idx);
4751 else
4752 return NULL;
4753}
4754
4755void
4756Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4757{
4758 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4759 if (data != NULL)
4760 data->AddRestartedReason(reason);
4761}
4762
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004763bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004764Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4765{
4766 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4767 if (data == NULL)
4768 return false;
4769 else
4770 return data->GetInterrupted ();
4771}
4772
4773void
4774Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4775{
4776 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4777 if (data != NULL)
4778 data->SetInterrupted(new_value);
4779}
4780
4781bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004782Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4783{
4784 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4785 if (data)
4786 {
4787 data->SetUpdateStateOnRemoval();
4788 return true;
4789 }
4790 return false;
4791}
4792
Greg Claytond9e416c2012-02-18 05:35:26 +00004793lldb::TargetSP
4794Process::CalculateTarget ()
4795{
4796 return m_target.shared_from_this();
4797}
4798
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004799void
Greg Clayton0603aa92010-10-04 01:05:56 +00004800Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004801{
Greg Claytonc14ee322011-09-22 04:58:26 +00004802 exe_ctx.SetTargetPtr (&m_target);
4803 exe_ctx.SetProcessPtr (this);
4804 exe_ctx.SetThreadPtr(NULL);
4805 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004806}
4807
Greg Claytone996fd32011-03-08 22:40:15 +00004808//uint32_t
4809//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4810//{
4811// return 0;
4812//}
4813//
4814//ArchSpec
4815//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4816//{
4817// return Host::GetArchSpecForExistingProcess (pid);
4818//}
4819//
4820//ArchSpec
4821//Process::GetArchSpecForExistingProcess (const char *process_name)
4822//{
4823// return Host::GetArchSpecForExistingProcess (process_name);
4824//}
4825//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004826void
4827Process::AppendSTDOUT (const char * s, size_t len)
4828{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004829 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004830 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004831 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004832}
4833
4834void
Greg Clayton93e86192011-11-13 04:45:22 +00004835Process::AppendSTDERR (const char * s, size_t len)
4836{
4837 Mutex::Locker locker (m_stdio_communication_mutex);
4838 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004839 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004840}
4841
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004842void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004843Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004844{
4845 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004846 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004847 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4848}
4849
4850size_t
4851Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4852{
4853 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004854 if (m_profile_data.empty())
4855 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004856
4857 std::string &one_profile_data = m_profile_data.front();
4858 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004859 if (bytes_available > 0)
4860 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004861 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004862 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004863 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4864 static_cast<void*>(buf),
4865 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004866 if (bytes_available > buf_size)
4867 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004868 memcpy(buf, one_profile_data.c_str(), buf_size);
4869 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004870 bytes_available = buf_size;
4871 }
4872 else
4873 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004874 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004875 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004876 }
4877 }
4878 return bytes_available;
4879}
4880
4881
Greg Clayton93e86192011-11-13 04:45:22 +00004882//------------------------------------------------------------------
4883// Process STDIO
4884//------------------------------------------------------------------
4885
4886size_t
4887Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4888{
4889 Mutex::Locker locker(m_stdio_communication_mutex);
4890 size_t bytes_available = m_stdout_data.size();
4891 if (bytes_available > 0)
4892 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004893 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004894 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004895 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4896 static_cast<void*>(buf),
4897 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004898 if (bytes_available > buf_size)
4899 {
4900 memcpy(buf, m_stdout_data.c_str(), buf_size);
4901 m_stdout_data.erase(0, buf_size);
4902 bytes_available = buf_size;
4903 }
4904 else
4905 {
4906 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4907 m_stdout_data.clear();
4908 }
4909 }
4910 return bytes_available;
4911}
4912
4913
4914size_t
4915Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4916{
4917 Mutex::Locker locker(m_stdio_communication_mutex);
4918 size_t bytes_available = m_stderr_data.size();
4919 if (bytes_available > 0)
4920 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004921 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004922 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004923 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4924 static_cast<void*>(buf),
4925 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004926 if (bytes_available > buf_size)
4927 {
4928 memcpy(buf, m_stderr_data.c_str(), buf_size);
4929 m_stderr_data.erase(0, buf_size);
4930 bytes_available = buf_size;
4931 }
4932 else
4933 {
4934 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4935 m_stderr_data.clear();
4936 }
4937 }
4938 return bytes_available;
4939}
4940
4941void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004942Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4943{
4944 Process *process = (Process *) baton;
4945 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4946}
4947
Greg Clayton44d93782014-01-27 23:43:24 +00004948class IOHandlerProcessSTDIO :
4949 public IOHandler
4950{
4951public:
4952 IOHandlerProcessSTDIO (Process *process,
4953 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00004954 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00004955 m_process (process),
4956 m_read_file (),
4957 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004958 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004959 {
4960 m_read_file.SetDescriptor(GetInputFD(), false);
4961 }
4962
4963 virtual
4964 ~IOHandlerProcessSTDIO ()
4965 {
4966
4967 }
4968
4969 bool
4970 OpenPipes ()
4971 {
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00004972 if (m_pipe.CanRead() && m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00004973 return true;
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00004974 Error result = m_pipe.CreateNew(false);
4975 return result.Success();
Greg Clayton44d93782014-01-27 23:43:24 +00004976 }
4977
4978 void
4979 ClosePipes()
4980 {
Greg Clayton100eb932014-07-02 21:10:39 +00004981 m_pipe.Close();
Greg Clayton44d93782014-01-27 23:43:24 +00004982 }
4983
4984 // Each IOHandler gets to run until it is done. It should read data
4985 // from the "in" and place output into "out" and "err and return
4986 // when done.
4987 virtual void
4988 Run ()
4989 {
4990 if (m_read_file.IsValid() && m_write_file.IsValid())
4991 {
4992 SetIsDone(false);
4993 if (OpenPipes())
4994 {
4995 const int read_fd = m_read_file.GetDescriptor();
Greg Clayton100eb932014-07-02 21:10:39 +00004996 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton44d93782014-01-27 23:43:24 +00004997 TerminalState terminal_state;
4998 terminal_state.Save (read_fd, false);
4999 Terminal terminal(read_fd);
5000 terminal.SetCanonical(false);
5001 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00005002// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00005003#ifndef _WIN32
Greg Clayton44d93782014-01-27 23:43:24 +00005004 while (!GetIsDone())
5005 {
5006 fd_set read_fdset;
5007 FD_ZERO (&read_fdset);
5008 FD_SET (read_fd, &read_fdset);
5009 FD_SET (pipe_read_fd, &read_fdset);
5010 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
5011 int num_set_fds = select (nfds, &read_fdset, NULL, NULL, NULL);
5012 if (num_set_fds < 0)
5013 {
5014 const int select_errno = errno;
5015
5016 if (select_errno != EINTR)
5017 SetIsDone(true);
5018 }
5019 else if (num_set_fds > 0)
5020 {
5021 char ch = 0;
5022 size_t n;
5023 if (FD_ISSET (read_fd, &read_fdset))
5024 {
5025 n = 1;
5026 if (m_read_file.Read(&ch, n).Success() && n == 1)
5027 {
5028 if (m_write_file.Write(&ch, n).Fail() || n != 1)
5029 SetIsDone(true);
5030 }
5031 else
5032 SetIsDone(true);
5033 }
5034 if (FD_ISSET (pipe_read_fd, &read_fdset))
5035 {
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005036 size_t bytes_read;
Greg Clayton44d93782014-01-27 23:43:24 +00005037 // Consume the interrupt byte
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005038 Error error = m_pipe.Read(&ch, 1, bytes_read);
5039 if (error.Success())
Greg Clayton19e11352014-02-26 22:47:33 +00005040 {
Greg Clayton100eb932014-07-02 21:10:39 +00005041 switch (ch)
5042 {
5043 case 'q':
5044 SetIsDone(true);
5045 break;
5046 case 'i':
5047 if (StateIsRunningState(m_process->GetState()))
5048 m_process->Halt();
5049 break;
5050 }
Greg Clayton19e11352014-02-26 22:47:33 +00005051 }
Greg Clayton44d93782014-01-27 23:43:24 +00005052 }
5053 }
5054 }
Deepak Panickal914b8d92014-01-31 18:48:46 +00005055#endif
Greg Clayton44d93782014-01-27 23:43:24 +00005056 terminal_state.Restore();
5057
5058 }
5059 else
5060 SetIsDone(true);
5061 }
5062 else
5063 SetIsDone(true);
5064 }
5065
5066 // Hide any characters that have been displayed so far so async
5067 // output can be displayed. Refresh() will be called after the
5068 // output has been displayed.
5069 virtual void
5070 Hide ()
5071 {
5072
5073 }
5074 // Called when the async output has been received in order to update
5075 // the input reader (refresh the prompt and redisplay any current
5076 // line(s) that are being edited
5077 virtual void
5078 Refresh ()
5079 {
5080
5081 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005082
Greg Clayton44d93782014-01-27 23:43:24 +00005083 virtual void
Greg Claytone68f5d62014-02-24 22:50:57 +00005084 Cancel ()
Greg Clayton44d93782014-01-27 23:43:24 +00005085 {
Greg Clayton19e11352014-02-26 22:47:33 +00005086 char ch = 'q'; // Send 'q' for quit
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005087 size_t bytes_written = 0;
5088 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00005089 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005090
Greg Claytonf0066ad2014-05-02 00:45:31 +00005091 virtual bool
Greg Claytone68f5d62014-02-24 22:50:57 +00005092 Interrupt ()
5093 {
Greg Clayton19e11352014-02-26 22:47:33 +00005094 // Do only things that are safe to do in an interrupt context (like in
5095 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5096 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5097 // that was written to the pipe and then call m_process->Halt() from a
5098 // much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005099 if (m_active)
5100 {
5101 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005102 size_t bytes_written = 0;
5103 Error result = m_pipe.Write(&ch, 1, bytes_written);
5104 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005105 }
5106 else
5107 {
5108 // This IOHandler might be pushed on the stack, but not being run currently
5109 // so do the right thing if we aren't actively watching for STDIN by sending
5110 // the interrupt to the process. Otherwise the write to the pipe above would
5111 // do nothing. This can happen when the command interpreter is running and
5112 // gets a "expression ...". It will be on the IOHandler thread and sending
5113 // the input is complete to the delegate which will cause the expression to
5114 // run, which will push the process IO handler, but not run it.
5115
5116 if (StateIsRunningState(m_process->GetState()))
5117 {
5118 m_process->SendAsyncInterrupt();
5119 return true;
5120 }
5121 }
5122 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005123 }
Greg Clayton44d93782014-01-27 23:43:24 +00005124
5125 virtual void
5126 GotEOF()
5127 {
5128
5129 }
5130
5131protected:
5132 Process *m_process;
5133 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5134 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005135 Pipe m_pipe;
Greg Clayton44d93782014-01-27 23:43:24 +00005136};
5137
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005138void
Greg Clayton44d93782014-01-27 23:43:24 +00005139Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005140{
5141 // First set up the Read Thread for reading/handling process I/O
5142
Greg Clayton44d93782014-01-27 23:43:24 +00005143 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005144
5145 if (conn_ap.get())
5146 {
5147 m_stdio_communication.SetConnection (conn_ap.release());
5148 if (m_stdio_communication.IsConnected())
5149 {
5150 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5151 m_stdio_communication.StartReadThread();
5152
5153 // Now read thread is set up, set up input reader.
5154
5155 if (!m_process_input_reader.get())
Greg Clayton44d93782014-01-27 23:43:24 +00005156 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005157 }
5158 }
5159}
5160
Greg Claytonb4874f12014-02-28 18:22:24 +00005161bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005162Process::ProcessIOHandlerIsActive ()
5163{
5164 IOHandlerSP io_handler_sp (m_process_input_reader);
5165 if (io_handler_sp)
5166 return m_target.GetDebugger().IsTopIOHandler (io_handler_sp);
5167 return false;
5168}
5169bool
Greg Clayton44d93782014-01-27 23:43:24 +00005170Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005171{
Greg Clayton44d93782014-01-27 23:43:24 +00005172 IOHandlerSP io_handler_sp (m_process_input_reader);
5173 if (io_handler_sp)
5174 {
5175 io_handler_sp->SetIsDone(false);
5176 m_target.GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005177 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005178 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005179 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005180}
5181
Greg Claytonb4874f12014-02-28 18:22:24 +00005182bool
Greg Clayton44d93782014-01-27 23:43:24 +00005183Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005184{
Greg Clayton44d93782014-01-27 23:43:24 +00005185 IOHandlerSP io_handler_sp (m_process_input_reader);
5186 if (io_handler_sp)
Greg Claytonb4874f12014-02-28 18:22:24 +00005187 return m_target.GetDebugger().PopIOHandler (io_handler_sp);
5188 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005189}
5190
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005191// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005192void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005193Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005194{
Greg Clayton6920b522012-08-22 18:39:03 +00005195 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005196}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005197
Greg Clayton99d0faf2010-11-18 23:32:35 +00005198void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005199Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005200{
Greg Clayton6920b522012-08-22 18:39:03 +00005201 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005202}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005203
Jim Ingham1624a2d2014-05-05 02:26:40 +00005204ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005205Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005206 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005207 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005208 Stream &errors)
5209{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005210 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005211
Jim Ingham77787032011-01-20 02:03:18 +00005212 if (thread_plan_sp.get() == NULL)
5213 {
5214 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005215 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005216 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005217
Jim Ingham7d7931d2013-03-28 00:05:34 +00005218 if (!thread_plan_sp->ValidatePlan(NULL))
5219 {
5220 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005221 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005222 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005223
Greg Claytonc14ee322011-09-22 04:58:26 +00005224 if (exe_ctx.GetProcessPtr() != this)
5225 {
5226 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005227 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005228 }
5229
5230 Thread *thread = exe_ctx.GetThreadPtr();
5231 if (thread == NULL)
5232 {
5233 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005234 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005235 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005236
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005237 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5238 // For that to be true the plan can't be private - since private plans suppress themselves in the
5239 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005240
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005241 bool orig_plan_private = thread_plan_sp->GetPrivate();
5242 thread_plan_sp->SetPrivate(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005243
Jim Ingham444586b2011-01-24 06:34:17 +00005244 if (m_private_state.GetValue() != eStateStopped)
5245 {
5246 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005247 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005248 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005249
Jim Ingham66243842011-08-13 00:56:10 +00005250 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005251 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005252 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005253 if (!selected_frame_sp)
5254 {
5255 thread->SetSelectedFrame(0);
5256 selected_frame_sp = thread->GetSelectedFrame();
5257 if (!selected_frame_sp)
5258 {
5259 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005260 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005261 }
5262 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005263
Jim Ingham11b0e052013-02-19 23:22:45 +00005264 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005265
5266 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5267 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005268
Greg Claytonc14ee322011-09-22 04:58:26 +00005269 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005270
Jim Ingham66243842011-08-13 00:56:10 +00005271 uint32_t selected_tid;
5272 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005273 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005274 {
5275 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005276 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005277 }
5278 else
5279 {
5280 selected_tid = LLDB_INVALID_THREAD_ID;
5281 }
5282
Zachary Turner39de3112014-09-09 20:54:56 +00005283 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005284 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005285 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005286
Greg Clayton5160ce52013-03-27 23:08:40 +00005287 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005288 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005289 {
Jim Ingham076b3042012-04-10 01:21:57 +00005290 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5291 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005292 // 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 +00005293 // we are fielding public events here.
5294 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005295 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 +00005296
Jim Ingham372787f2012-04-07 00:00:41 +00005297 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005298
5299 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5300 // returning control here.
5301 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5302 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5303 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5304 // do just what we want.
5305 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5306 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5307 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5308 old_state = m_public_state.GetValue();
5309 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005310
Jim Ingham076b3042012-04-10 01:21:57 +00005311 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005312 StartPrivateStateThread(true);
5313 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005314
Jim Ingham372787f2012-04-07 00:00:41 +00005315 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005316
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005317 if (options.GetDebug())
5318 {
5319 // In this case, we aren't actually going to run, we just want to stop right away.
5320 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5321 // FIXME: To make this prettier we should invent some stop reason for this, but that
5322 // is only cosmetic, and this functionality is only of use to lldb developers who can
5323 // live with not pretty...
5324 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005325 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005326 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005327
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005328 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005329
Sean Callanana46ec452012-07-11 21:31:24 +00005330 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005331
Jim Ingham77787032011-01-20 02:03:18 +00005332 {
Sean Callanana46ec452012-07-11 21:31:24 +00005333 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5334 // restored on exit to the function.
5335 //
5336 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5337 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005338
Sean Callanana46ec452012-07-11 21:31:24 +00005339 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005340
Jim Inghamf48169b2010-11-30 02:22:11 +00005341 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005342 {
5343 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005344 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005345 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005346 thread->GetIndexID(),
5347 thread->GetID(),
5348 s.GetData());
5349 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005350
Sean Callanana46ec452012-07-11 21:31:24 +00005351 bool got_event;
5352 lldb::EventSP event_sp;
5353 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005354
Sean Callanana46ec452012-07-11 21:31:24 +00005355 TimeValue* timeout_ptr = NULL;
5356 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005357
Jim Ingham0161b492013-02-09 01:29:05 +00005358 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 +00005359 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005360 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005361 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005362
Jim Ingham0161b492013-02-09 01:29:05 +00005363 // This is just for accounting:
5364 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005365
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005366 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005367 uint32_t one_thread_timeout_usec;
5368 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005369
5370 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5371 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5372 // first timeout already.
5373
5374 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005375 {
5376 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005377 one_thread_timeout_usec = 0;
5378 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005379 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005380 else
Jim Ingham0161b492013-02-09 01:29:05 +00005381 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005382 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005383
Jim Ingham914f4e72014-03-28 21:58:28 +00005384 // If the overall wait is forever, then we only need to set the one thread timeout:
5385 if (timeout_usec == 0)
5386 {
Ed Maste801335c2014-03-31 19:28:14 +00005387 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005388 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005389 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005390 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005391 }
Jim Ingham0161b492013-02-09 01:29:05 +00005392 else
5393 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005394 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5395 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5396 uint64_t computed_one_thread_timeout;
5397 if (option_one_thread_timeout != 0)
5398 {
5399 if (timeout_usec < option_one_thread_timeout)
5400 {
5401 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005402 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005403 }
5404 computed_one_thread_timeout = option_one_thread_timeout;
5405 }
5406 else
5407 {
5408 computed_one_thread_timeout = timeout_usec / 2;
5409 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5410 computed_one_thread_timeout = default_one_thread_timeout_usec;
5411 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005412 one_thread_timeout_usec = computed_one_thread_timeout;
5413 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
5414
Jim Ingham0161b492013-02-09 01:29:05 +00005415 }
Jim Ingham0161b492013-02-09 01:29:05 +00005416 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005417
5418 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005419 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 +00005420 options.GetStopOthers(),
5421 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005422 before_first_timeout,
5423 one_thread_timeout_usec,
5424 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005425
Jim Ingham1460e4b2014-01-10 23:46:59 +00005426 // This isn't going to work if there are unfetched events on the queue.
5427 // Are there cases where we might want to run the remaining events here, and then try to
5428 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005429
Jim Ingham1460e4b2014-01-10 23:46:59 +00005430 Event *other_events = listener.PeekAtNextEvent();
5431 if (other_events != NULL)
5432 {
5433 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005434 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005435 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005436
Jim Ingham1460e4b2014-01-10 23:46:59 +00005437 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5438 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5439 // event coalescing to cause us to lose OUR running event...
5440 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005441
Jim Ingham8559a352012-11-26 23:52:18 +00005442 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5443 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005444
5445#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5446 // It's pretty much impossible to write test cases for things like:
5447 // One thread timeout expires, I go to halt, but the process already stopped
5448 // on the function call stop breakpoint. Turning on this define will make us not
5449 // fetch the first event till after the halt. So if you run a quick function, it will have
5450 // completed, and the completion event will be waiting, when you interrupt for halt.
5451 // The expression evaluation should still succeed.
5452 bool miss_first_event = true;
5453#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005454 TimeValue one_thread_timeout;
5455 TimeValue final_timeout;
5456
Jim Ingham35878c42014-04-08 21:33:21 +00005457
Sean Callanana46ec452012-07-11 21:31:24 +00005458 while (1)
5459 {
5460 // We usually want to resume the process if we get to the top of the loop.
5461 // The only exception is if we get two running events with no intervening
5462 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005463 if (log)
5464 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5465 do_resume,
5466 handle_running_event,
5467 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005468
Jim Ingham184e9812013-01-15 02:47:48 +00005469 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005470 {
5471 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005472
Jim Ingham184e9812013-01-15 02:47:48 +00005473 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005474 {
Jim Ingham0161b492013-02-09 01:29:05 +00005475 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005476 Error resume_error = PrivateResume ();
5477 if (!resume_error.Success())
5478 {
Jim Ingham0161b492013-02-09 01:29:05 +00005479 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5480 num_resumes,
5481 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005482 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005483 break;
5484 }
Sean Callanana46ec452012-07-11 21:31:24 +00005485 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005486
Jim Ingham0161b492013-02-09 01:29:05 +00005487 TimeValue resume_timeout = TimeValue::Now();
5488 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005489
Jim Ingham0161b492013-02-09 01:29:05 +00005490 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005491 if (!got_event)
5492 {
5493 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005494 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5495 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005496
Jim Ingham0161b492013-02-09 01:29:05 +00005497 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005498 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005499 break;
5500 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005501
Sean Callanana46ec452012-07-11 21:31:24 +00005502 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005503
Sean Callanana46ec452012-07-11 21:31:24 +00005504 if (stop_state != eStateRunning)
5505 {
Jim Ingham0161b492013-02-09 01:29:05 +00005506 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005507
Jim Ingham0161b492013-02-09 01:29:05 +00005508 if (stop_state == eStateStopped)
5509 {
5510 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5511 if (log)
5512 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5513 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5514 num_resumes,
5515 StateAsCString(stop_state),
5516 restarted,
5517 do_resume,
5518 handle_running_event);
5519 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005520
Jim Ingham0161b492013-02-09 01:29:05 +00005521 if (restarted)
5522 {
5523 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5524 // event here. But if I do, the best thing is to Halt and then get out of here.
5525 Halt();
5526 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005527
Jim Ingham35e1bda2012-10-16 21:41:58 +00005528 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5529 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005530 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005531 break;
5532 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005533
Sean Callanana46ec452012-07-11 21:31:24 +00005534 if (log)
5535 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5536 // We need to call the function synchronously, so spin waiting for it to return.
5537 // If we get interrupted while executing, we're going to lose our context, and
5538 // won't be able to gather the result at this point.
5539 // We set the timeout AFTER the resume, since the resume takes some time and we
5540 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005541 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005542 else
5543 {
Sean Callanana46ec452012-07-11 21:31:24 +00005544 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005545 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005546 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005547
Jim Ingham0161b492013-02-09 01:29:05 +00005548 if (before_first_timeout)
5549 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005550 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005551 {
5552 one_thread_timeout = TimeValue::Now();
5553 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005554 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005555 }
Jim Ingham0161b492013-02-09 01:29:05 +00005556 else
5557 {
5558 if (timeout_usec == 0)
5559 timeout_ptr = NULL;
5560 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005561 {
5562 final_timeout = TimeValue::Now();
5563 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005564 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005565 }
Jim Ingham0161b492013-02-09 01:29:05 +00005566 }
5567 }
5568 else
5569 {
5570 if (timeout_usec == 0)
5571 timeout_ptr = NULL;
5572 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005573 {
5574 final_timeout = TimeValue::Now();
5575 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005576 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005577 }
Jim Ingham0161b492013-02-09 01:29:05 +00005578 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005579
Jim Ingham0161b492013-02-09 01:29:05 +00005580 do_resume = true;
5581 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005582
Sean Callanana46ec452012-07-11 21:31:24 +00005583 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005584 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005585
Jim Ingham0f16e732011-02-08 05:20:59 +00005586 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005587 {
Sean Callanana46ec452012-07-11 21:31:24 +00005588 if (timeout_ptr)
5589 {
Matt Kopec676a4872013-02-21 23:55:31 +00005590 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005591 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5592 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005593 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005594 else
Sean Callanana46ec452012-07-11 21:31:24 +00005595 {
5596 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5597 }
5598 }
Jim Ingham35878c42014-04-08 21:33:21 +00005599
5600#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5601 // See comment above...
5602 if (miss_first_event)
5603 {
5604 usleep(1000);
5605 miss_first_event = false;
5606 got_event = false;
5607 }
5608 else
5609#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005610 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005611
Sean Callanana46ec452012-07-11 21:31:24 +00005612 if (got_event)
5613 {
5614 if (event_sp.get())
5615 {
5616 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005617 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005618 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005619 Halt();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005620 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005621 errors.Printf ("Execution halted by user interrupt.");
5622 if (log)
5623 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005624 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005625 }
5626 else
5627 {
5628 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5629 if (log)
5630 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005631
Jim Inghamcfc09352012-07-27 23:57:19 +00005632 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005633 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005634 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005635 {
Jim Ingham0161b492013-02-09 01:29:05 +00005636 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005637 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5638 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005639 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005640 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005641 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005642 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005643 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005644 }
5645 else
5646 {
Jim Ingham0161b492013-02-09 01:29:05 +00005647 // If we were restarted, we just need to go back up to fetch another event.
5648 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005649 {
5650 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005651 {
5652 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5653 }
5654 keep_going = true;
5655 do_resume = false;
5656 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005657
Jim Inghamcfc09352012-07-27 23:57:19 +00005658 }
5659 else
5660 {
Jim Ingham0161b492013-02-09 01:29:05 +00005661 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5662 StopReason stop_reason = eStopReasonInvalid;
5663 if (stop_info_sp)
5664 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005665
Jim Ingham0161b492013-02-09 01:29:05 +00005666 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5667 // it is OUR plan that is complete?
5668 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005669 {
5670 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005671 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5672 // Now mark this plan as private so it doesn't get reported as the stop reason
5673 // after this point.
5674 if (thread_plan_sp)
5675 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005676 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005677 }
5678 else
5679 {
Jim Ingham0161b492013-02-09 01:29:05 +00005680 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005681 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005682 {
5683 if (log)
5684 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005685 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005686 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005687 {
5688 event_to_broadcast_sp = event_sp;
5689 }
Jim Ingham0161b492013-02-09 01:29:05 +00005690 }
Jim Ingham184e9812013-01-15 02:47:48 +00005691 else
Jim Ingham0161b492013-02-09 01:29:05 +00005692 {
5693 if (log)
5694 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005695 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005696 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005697 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005698 }
Jim Ingham184e9812013-01-15 02:47:48 +00005699 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005700 }
Sean Callanana46ec452012-07-11 21:31:24 +00005701 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005702 }
5703 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005704
Jim Inghamcfc09352012-07-27 23:57:19 +00005705 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005706 // This shouldn't really happen, but sometimes we do get two running events without an
5707 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005708 do_resume = false;
5709 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005710 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005711 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005712
Jim Inghamcfc09352012-07-27 23:57:19 +00005713 default:
5714 if (log)
5715 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005716
Jim Inghamcfc09352012-07-27 23:57:19 +00005717 if (stop_state == eStateExited)
5718 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005719
Sean Callananbf154da2012-08-08 17:35:10 +00005720 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005721 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005722 break;
5723 }
Sean Callanana46ec452012-07-11 21:31:24 +00005724 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005725
Sean Callanana46ec452012-07-11 21:31:24 +00005726 if (keep_going)
5727 continue;
5728 else
5729 break;
5730 }
5731 else
5732 {
5733 if (log)
5734 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005735 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005736 break;
5737 }
5738 }
5739 else
5740 {
5741 // If we didn't get an event that means we've timed out...
5742 // We will interrupt the process here. Depending on what we were asked to do we will
5743 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005744
Sean Callanana46ec452012-07-11 21:31:24 +00005745 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005746 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005747 {
Jim Ingham0161b492013-02-09 01:29:05 +00005748 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005749 {
5750 if (timeout_usec != 0)
5751 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005752 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005753 "running for %" PRIu32 " usec with all threads enabled.",
5754 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005755 }
5756 else
5757 {
5758 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005759 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005760 }
5761 }
Sean Callanana46ec452012-07-11 21:31:24 +00005762 else
5763 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005764 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005765 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005766 }
5767 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005768 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005769 "abandoning execution.",
5770 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005771 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005772
Jim Ingham0161b492013-02-09 01:29:05 +00005773 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5774 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5775 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5776 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5777 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005778
Jim Ingham0161b492013-02-09 01:29:05 +00005779 bool back_to_top = true;
5780 uint32_t try_halt_again = 0;
5781 bool do_halt = true;
5782 const uint32_t num_retries = 5;
5783 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005784 {
Jim Ingham0161b492013-02-09 01:29:05 +00005785 Error halt_error;
5786 if (do_halt)
5787 {
5788 if (log)
5789 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5790 halt_error = Halt();
5791 }
5792 if (halt_error.Success())
5793 {
5794 if (log)
5795 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005796
Jim Ingham0161b492013-02-09 01:29:05 +00005797 real_timeout = TimeValue::Now();
5798 real_timeout.OffsetWithMicroSeconds(500000);
5799
5800 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005801
Jim Ingham0161b492013-02-09 01:29:05 +00005802 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005803 {
Jim Ingham0161b492013-02-09 01:29:05 +00005804 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5805 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005806 {
Jim Ingham0161b492013-02-09 01:29:05 +00005807 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5808 if (stop_state == lldb::eStateStopped
5809 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5810 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005811 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005812
Jim Ingham0161b492013-02-09 01:29:05 +00005813 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005814 {
Jim Ingham0161b492013-02-09 01:29:05 +00005815 // Between the time we initiated the Halt and the time we delivered it, the process could have
5816 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005817
Jim Ingham0161b492013-02-09 01:29:05 +00005818 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5819 {
5820 if (log)
5821 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5822 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005823 return_value = eExpressionCompleted;
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 (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5829 {
5830 if (log)
5831 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5832 "Exiting wait loop.");
5833 try_halt_again++;
5834 do_halt = false;
5835 continue;
5836 }
Sean Callanana46ec452012-07-11 21:31:24 +00005837
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005838 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005839 {
5840 if (log)
5841 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005842 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005843 back_to_top = false;
5844 break;
5845 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005846
Jim Ingham0161b492013-02-09 01:29:05 +00005847 if (before_first_timeout)
5848 {
5849 // Set all the other threads to run, and return to the top of the loop, which will continue;
5850 before_first_timeout = false;
5851 thread_plan_sp->SetStopOthers (false);
5852 if (log)
5853 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005854
Jim Ingham0161b492013-02-09 01:29:05 +00005855 back_to_top = true;
5856 break;
5857 }
5858 else
5859 {
5860 // Running all threads failed, so return Interrupted.
5861 if (log)
5862 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005863 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005864 back_to_top = false;
5865 break;
5866 }
Sean Callanana46ec452012-07-11 21:31:24 +00005867 }
5868 }
5869 else
Jim Ingham0161b492013-02-09 01:29:05 +00005870 { if (log)
5871 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5872 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005873 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005874 back_to_top = false;
5875 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005876 }
5877 }
Jim Ingham0161b492013-02-09 01:29:05 +00005878 else
5879 {
5880 try_halt_again++;
5881 continue;
5882 }
Sean Callanana46ec452012-07-11 21:31:24 +00005883 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005884
Jim Ingham0161b492013-02-09 01:29:05 +00005885 if (!back_to_top || try_halt_again > num_retries)
5886 break;
5887 else
5888 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005889 }
Sean Callanana46ec452012-07-11 21:31:24 +00005890 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005891
Sean Callanana46ec452012-07-11 21:31:24 +00005892 // 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 +00005893 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005894 {
5895 StopPrivateStateThread();
5896 Error error;
5897 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005898 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005899 {
5900 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5901 }
Jason Molenda76513fd2014-10-15 23:39:31 +00005902 if (old_state != eStateInvalid)
5903 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00005904 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005905
Jim Ingham184e9812013-01-15 02:47:48 +00005906 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5907 // could happen:
5908 // 1) The execution successfully completed
5909 // 2) We hit a breakpoint, and ignore_breakpoints was true
5910 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005911 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5912 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005913
Jim Ingham8646d3c2014-05-05 02:47:44 +00005914 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005915 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005916 {
5917 thread_plan_sp->RestoreThreadState();
5918 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005919
Sean Callanana46ec452012-07-11 21:31:24 +00005920 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005921 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005922 {
5923 if (log)
5924 {
5925 StreamString s;
5926 if (event_sp)
5927 event_sp->Dump (&s);
5928 else
5929 {
5930 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5931 }
5932
5933 StreamString ts;
5934
5935 const char *event_explanation = NULL;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005936
Sean Callanana46ec452012-07-11 21:31:24 +00005937 do
5938 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005939 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005940 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005941 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005942 break;
5943 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005944 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005945 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005946 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005947 break;
5948 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005949 else
Sean Callanana46ec452012-07-11 21:31:24 +00005950 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005951 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5952
5953 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005954 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005955 event_explanation = "<no event data>";
5956 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005957 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005958
Jim Inghamcfc09352012-07-27 23:57:19 +00005959 Process *process = event_data->GetProcessSP().get();
5960
5961 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005962 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005963 event_explanation = "<no process>";
5964 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005965 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005966
Jim Inghamcfc09352012-07-27 23:57:19 +00005967 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005968
Jim Inghamcfc09352012-07-27 23:57:19 +00005969 uint32_t num_threads = thread_list.GetSize();
5970 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005971
Jim Inghamcfc09352012-07-27 23:57:19 +00005972 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005973
Jim Inghamcfc09352012-07-27 23:57:19 +00005974 for (thread_index = 0;
5975 thread_index < num_threads;
5976 ++thread_index)
5977 {
5978 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005979
Jim Inghamcfc09352012-07-27 23:57:19 +00005980 if (!thread)
5981 {
5982 ts.Printf("<?> ");
5983 continue;
5984 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005985
Daniel Malead01b2952012-11-29 21:49:15 +00005986 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005987 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005988
Jim Inghamcfc09352012-07-27 23:57:19 +00005989 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005990 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005991 else
5992 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005993
Jim Inghamcfc09352012-07-27 23:57:19 +00005994 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5995 if (stop_info_sp)
5996 {
5997 const char *stop_desc = stop_info_sp->GetDescription();
5998 if (stop_desc)
5999 ts.PutCString (stop_desc);
6000 }
6001 ts.Printf(">");
6002 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006003
Jim Inghamcfc09352012-07-27 23:57:19 +00006004 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006005 }
Sean Callanana46ec452012-07-11 21:31:24 +00006006 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006007
Jim Inghamcfc09352012-07-27 23:57:19 +00006008 if (event_explanation)
6009 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006010 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006011 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6012 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006013
Jim Inghame4483cf2013-09-27 01:13:01 +00006014 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006015 {
6016 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006017 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6018 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006019 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6020 thread_plan_sp->SetPrivate (orig_plan_private);
6021 }
6022 else
6023 {
6024 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006025 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6026 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006027 }
6028 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006029 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006030 {
6031 if (log)
6032 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006033
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006034 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006035 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006036 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00006037 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00006038 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006039 }
6040 else
6041 {
Sean Callanana46ec452012-07-11 21:31:24 +00006042 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006043 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006044 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006045 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006046 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006047 }
6048 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6049 {
6050 if (log)
6051 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006052 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006053 }
6054 else
6055 {
6056 if (log)
6057 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006058 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006059 {
6060 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006061 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006062 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
6063 thread_plan_sp->SetPrivate (orig_plan_private);
6064 }
6065 }
6066 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006067
Sean Callanana46ec452012-07-11 21:31:24 +00006068 // Thread we ran the function in may have gone away because we ran the target
6069 // Check that it's still there, and if it is put it back in the context. Also restore the
6070 // frame in the context if it is still present.
6071 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6072 if (thread)
6073 {
6074 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6075 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006076
Sean Callanana46ec452012-07-11 21:31:24 +00006077 // Also restore the current process'es selected frame & thread, since this function calling may
6078 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006079
Sean Callanana46ec452012-07-11 21:31:24 +00006080 if (selected_tid != LLDB_INVALID_THREAD_ID)
6081 {
6082 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6083 {
6084 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006085 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006086 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006087 if (old_frame_sp)
6088 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006089 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006090 }
6091 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006092
Sean Callanana46ec452012-07-11 21:31:24 +00006093 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006094
Sean Callanana46ec452012-07-11 21:31:24 +00006095 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006096 {
Sean Callanana46ec452012-07-11 21:31:24 +00006097 if (log)
6098 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6099 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006100 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006101
Jim Inghamf48169b2010-11-30 02:22:11 +00006102 return return_value;
6103}
6104
6105const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006106Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006107{
6108 const char *result_name;
6109
6110 switch (result)
6111 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006112 case eExpressionCompleted:
6113 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006114 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006115 case eExpressionDiscarded:
6116 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006117 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006118 case eExpressionInterrupted:
6119 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006120 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006121 case eExpressionHitBreakpoint:
6122 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006123 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006124 case eExpressionSetupError:
6125 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006126 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006127 case eExpressionParseError:
6128 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006129 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006130 case eExpressionResultUnavailable:
6131 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006132 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006133 case eExpressionTimedOut:
6134 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006135 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006136 case eExpressionStoppedForDebug:
6137 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006138 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006139 }
6140 return result_name;
6141}
6142
Greg Clayton7260f622011-04-18 08:33:37 +00006143void
6144Process::GetStatus (Stream &strm)
6145{
6146 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006147 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006148 {
6149 if (state == eStateExited)
6150 {
6151 int exit_status = GetExitStatus();
6152 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006153 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006154 GetID(),
6155 exit_status,
6156 exit_status,
6157 exit_description ? exit_description : "");
6158 }
6159 else
6160 {
6161 if (state == eStateConnected)
6162 strm.Printf ("Connected to remote target.\n");
6163 else
Daniel Malead01b2952012-11-29 21:49:15 +00006164 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006165 }
6166 }
6167 else
6168 {
Daniel Malead01b2952012-11-29 21:49:15 +00006169 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006170 }
6171}
6172
6173size_t
6174Process::GetThreadStatus (Stream &strm,
6175 bool only_threads_with_stop_reason,
6176 uint32_t start_frame,
6177 uint32_t num_frames,
6178 uint32_t num_frames_with_source)
6179{
6180 size_t num_thread_infos_dumped = 0;
6181
Jim Ingham4a65fb12014-03-07 11:20:03 +00006182 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6183 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6184 // ID's, and look them up one by one:
6185
6186 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006187 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006188 //Scope for thread list locker;
6189 {
6190 Mutex::Locker locker (GetThreadList().GetMutex());
6191 ThreadList &curr_thread_list = GetThreadList();
6192 num_threads = curr_thread_list.GetSize();
6193 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006194 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006195 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006196 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006197 }
6198
Greg Clayton7260f622011-04-18 08:33:37 +00006199 for (uint32_t i = 0; i < num_threads; i++)
6200 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006201 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006202 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006203 {
6204 if (only_threads_with_stop_reason)
6205 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006206 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Jim Ingham5d88a062012-10-16 00:09:33 +00006207 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006208 continue;
6209 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006210 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006211 start_frame,
6212 num_frames,
6213 num_frames_with_source);
6214 ++num_thread_infos_dumped;
6215 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006216 else
6217 {
6218 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6219 if (log)
6220 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
6221
6222 }
Greg Clayton7260f622011-04-18 08:33:37 +00006223 }
6224 return num_thread_infos_dumped;
6225}
6226
Greg Claytona9f40ad2012-02-22 04:37:26 +00006227void
6228Process::AddInvalidMemoryRegion (const LoadRange &region)
6229{
6230 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6231}
6232
6233bool
6234Process::RemoveInvalidMemoryRange (const LoadRange &region)
6235{
6236 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6237}
6238
Jim Ingham372787f2012-04-07 00:00:41 +00006239void
6240Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6241{
6242 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6243}
6244
6245bool
6246Process::RunPreResumeActions ()
6247{
6248 bool result = true;
6249 while (!m_pre_resume_actions.empty())
6250 {
6251 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6252 m_pre_resume_actions.pop_back();
6253 bool this_result = action.callback (action.baton);
Jason Molenda55710932014-11-17 20:10:15 +00006254 if (result == true)
6255 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006256 }
6257 return result;
6258}
6259
6260void
6261Process::ClearPreResumeActions ()
6262{
6263 m_pre_resume_actions.clear();
6264}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006265
Greg Claytonfa559e52012-05-18 02:38:05 +00006266void
6267Process::Flush ()
6268{
6269 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006270 m_extended_thread_list.Flush();
6271 m_extended_thread_stop_id = 0;
6272 m_queue_list.Clear();
6273 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006274}
Greg Clayton90ba8112012-12-05 00:16:59 +00006275
6276void
6277Process::DidExec ()
6278{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006279 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6280 if (log)
6281 log->Printf ("Process::%s()", __FUNCTION__);
6282
Greg Clayton90ba8112012-12-05 00:16:59 +00006283 Target &target = GetTarget();
6284 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006285 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006286 m_dynamic_checkers_ap.reset();
6287 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006288 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006289 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006290 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006291 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006292 m_image_tokens.clear();
6293 m_allocated_memory_cache.Clear();
6294 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006295 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006296 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006297 m_memory_cache.Clear(true);
Greg Claytona97c4d22014-12-09 23:31:02 +00006298 m_stop_info_override_callback = NULL;
Greg Clayton90ba8112012-12-05 00:16:59 +00006299 DoDidExec();
6300 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006301 // Flush the process (threads and all stack frames) after running CompleteAttach()
6302 // in case the dynamic loader loaded things in new locations.
6303 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006304
6305 // After we figure out what was loaded/unloaded in CompleteAttach,
6306 // we need to let the target know so it can do any cleanup it needs to.
6307 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006308}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006309
Jim Ingham1460e4b2014-01-10 23:46:59 +00006310addr_t
6311Process::ResolveIndirectFunction(const Address *address, Error &error)
6312{
6313 if (address == nullptr)
6314 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006315 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006316 return LLDB_INVALID_ADDRESS;
6317 }
6318
6319 addr_t function_addr = LLDB_INVALID_ADDRESS;
6320
6321 addr_t addr = address->GetLoadAddress(&GetTarget());
6322 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6323 if (iter != m_resolved_indirect_addresses.end())
6324 {
6325 function_addr = (*iter).second;
6326 }
6327 else
6328 {
6329 if (!InferiorCall(this, address, function_addr))
6330 {
6331 Symbol *symbol = address->CalculateSymbolContextSymbol();
6332 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6333 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6334 function_addr = LLDB_INVALID_ADDRESS;
6335 }
6336 else
6337 {
6338 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6339 }
6340 }
6341 return function_addr;
6342}
6343
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006344void
6345Process::ModulesDidLoad (ModuleList &module_list)
6346{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006347 SystemRuntime *sys_runtime = GetSystemRuntime();
6348 if (sys_runtime)
6349 {
6350 sys_runtime->ModulesDidLoad (module_list);
6351 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006352
Kuba Breckaafdf8422014-10-10 23:43:03 +00006353 GetJITLoaders().ModulesDidLoad (module_list);
6354
6355 // Give runtimes a chance to be created.
6356 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6357
6358 // Tell runtimes about new modules.
6359 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6360 {
6361 InstrumentationRuntimeSP runtime = pos->second;
6362 runtime->ModulesDidLoad(module_list);
6363 }
6364
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006365}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006366
6367ThreadCollectionSP
6368Process::GetHistoryThreads(lldb::addr_t addr)
6369{
6370 ThreadCollectionSP threads;
6371
6372 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6373
6374 if (! memory_history.get()) {
6375 return threads;
6376 }
6377
6378 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6379
6380 return threads;
6381}
Kuba Brecka63927542014-10-11 01:59:32 +00006382
6383InstrumentationRuntimeSP
6384Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6385{
6386 InstrumentationRuntimeCollection::iterator pos;
6387 pos = m_instrumentation_runtimes.find (type);
6388 if (pos == m_instrumentation_runtimes.end())
6389 {
6390 return InstrumentationRuntimeSP();
6391 }
6392 else
6393 return (*pos).second;
6394}