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